1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAGISel.h"
15 #include "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuilder.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/CFG.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/GCMetadata.h"
25 #include "llvm/CodeGen/GCStrategy.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
32 #include "llvm/CodeGen/SchedulerRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DebugInfo.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetIntrinsicInfo.h"
50 #include "llvm/Target/TargetLibraryInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
56 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #define DEBUG_TYPE "isel"
62 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
63 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
64 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
65 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
66 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
67 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
68 STATISTIC(NumFastIselFailLowerArguments,
69 "Number of entry blocks where fast isel failed to lower arguments");
73 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
74 cl::desc("Enable extra verbose messages in the \"fast\" "
75 "instruction selector"));
78 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
79 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
80 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
81 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
82 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
83 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
84 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
86 // Standard binary operators...
87 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
88 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
89 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
90 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
91 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
92 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
93 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
94 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
95 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
96 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
97 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
98 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
100 // Logical operators...
101 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
102 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
103 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
105 // Memory instructions...
106 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
107 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
108 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
109 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
110 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
111 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
112 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
114 // Convert instructions...
115 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
116 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
117 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
118 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
119 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
120 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
121 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
122 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
123 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
124 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
125 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
126 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
128 // Other instructions...
129 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
130 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
131 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
132 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
133 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
134 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
135 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
136 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
137 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
138 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
139 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
140 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
141 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
142 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
143 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
145 // Intrinsic instructions...
146 STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call");
147 STATISTIC(NumFastIselFailSAddWithOverflow,
148 "Fast isel fails on sadd.with.overflow");
149 STATISTIC(NumFastIselFailUAddWithOverflow,
150 "Fast isel fails on uadd.with.overflow");
151 STATISTIC(NumFastIselFailSSubWithOverflow,
152 "Fast isel fails on ssub.with.overflow");
153 STATISTIC(NumFastIselFailUSubWithOverflow,
154 "Fast isel fails on usub.with.overflow");
155 STATISTIC(NumFastIselFailSMulWithOverflow,
156 "Fast isel fails on smul.with.overflow");
157 STATISTIC(NumFastIselFailUMulWithOverflow,
158 "Fast isel fails on umul.with.overflow");
159 STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress");
160 STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call");
161 STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call");
162 STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call");
166 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
167 cl::desc("Enable verbose messages in the \"fast\" "
168 "instruction selector"));
170 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
171 cl::desc("Enable abort calls when \"fast\" instruction selection "
172 "fails to lower an instruction"));
174 EnableFastISelAbortArgs("fast-isel-abort-args", cl::Hidden,
175 cl::desc("Enable abort calls when \"fast\" instruction selection "
176 "fails to lower a formal argument"));
180 cl::desc("use Machine Branch Probability Info"),
181 cl::init(true), cl::Hidden);
184 static cl::opt<std::string>
185 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
186 cl::desc("Only display the basic block whose name "
187 "matches this for all view-*-dags options"));
189 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
190 cl::desc("Pop up a window to show dags before the first "
191 "dag combine pass"));
193 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
194 cl::desc("Pop up a window to show dags before legalize types"));
196 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
197 cl::desc("Pop up a window to show dags before legalize"));
199 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
200 cl::desc("Pop up a window to show dags before the second "
201 "dag combine pass"));
203 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
204 cl::desc("Pop up a window to show dags before the post legalize types"
205 " dag combine pass"));
207 ViewISelDAGs("view-isel-dags", cl::Hidden,
208 cl::desc("Pop up a window to show isel dags as they are selected"));
210 ViewSchedDAGs("view-sched-dags", cl::Hidden,
211 cl::desc("Pop up a window to show sched dags as they are processed"));
213 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
214 cl::desc("Pop up a window to show SUnit dags after they are processed"));
216 static const bool ViewDAGCombine1 = false,
217 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
218 ViewDAGCombine2 = false,
219 ViewDAGCombineLT = false,
220 ViewISelDAGs = false, ViewSchedDAGs = false,
221 ViewSUnitDAGs = false;
224 //===---------------------------------------------------------------------===//
226 /// RegisterScheduler class - Track the registration of instruction schedulers.
228 //===---------------------------------------------------------------------===//
229 MachinePassRegistry RegisterScheduler::Registry;
231 //===---------------------------------------------------------------------===//
233 /// ISHeuristic command line option for instruction schedulers.
235 //===---------------------------------------------------------------------===//
236 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
237 RegisterPassParser<RegisterScheduler> >
238 ISHeuristic("pre-RA-sched",
239 cl::init(&createDefaultScheduler), cl::Hidden,
240 cl::desc("Instruction schedulers available (before register"
243 static RegisterScheduler
244 defaultListDAGScheduler("default", "Best scheduler for the target",
245 createDefaultScheduler);
248 //===--------------------------------------------------------------------===//
249 /// \brief This class is used by SelectionDAGISel to temporarily override
250 /// the optimization level on a per-function basis.
251 class OptLevelChanger {
252 SelectionDAGISel &IS;
253 CodeGenOpt::Level SavedOptLevel;
257 OptLevelChanger(SelectionDAGISel &ISel,
258 CodeGenOpt::Level NewOptLevel) : IS(ISel) {
259 SavedOptLevel = IS.OptLevel;
260 if (NewOptLevel == SavedOptLevel)
262 IS.OptLevel = NewOptLevel;
263 IS.TM.setOptLevel(NewOptLevel);
264 SavedFastISel = IS.TM.Options.EnableFastISel;
265 if (NewOptLevel == CodeGenOpt::None)
266 IS.TM.setFastISel(true);
267 DEBUG(dbgs() << "\nChanging optimization level for Function "
268 << IS.MF->getFunction()->getName() << "\n");
269 DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
270 << " ; After: -O" << NewOptLevel << "\n");
274 if (IS.OptLevel == SavedOptLevel)
276 DEBUG(dbgs() << "\nRestoring optimization level for Function "
277 << IS.MF->getFunction()->getName() << "\n");
278 DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
279 << " ; After: -O" << SavedOptLevel << "\n");
280 IS.OptLevel = SavedOptLevel;
281 IS.TM.setOptLevel(SavedOptLevel);
282 IS.TM.setFastISel(SavedFastISel);
286 //===--------------------------------------------------------------------===//
287 /// createDefaultScheduler - This creates an instruction scheduler appropriate
289 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
290 CodeGenOpt::Level OptLevel) {
291 const TargetLowering *TLI = IS->TLI;
292 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
294 if (OptLevel == CodeGenOpt::None || ST.useMachineScheduler() ||
295 TLI->getSchedulingPreference() == Sched::Source)
296 return createSourceListDAGScheduler(IS, OptLevel);
297 if (TLI->getSchedulingPreference() == Sched::RegPressure)
298 return createBURRListDAGScheduler(IS, OptLevel);
299 if (TLI->getSchedulingPreference() == Sched::Hybrid)
300 return createHybridListDAGScheduler(IS, OptLevel);
301 if (TLI->getSchedulingPreference() == Sched::VLIW)
302 return createVLIWDAGScheduler(IS, OptLevel);
303 assert(TLI->getSchedulingPreference() == Sched::ILP &&
304 "Unknown sched type!");
305 return createILPListDAGScheduler(IS, OptLevel);
309 // EmitInstrWithCustomInserter - This method should be implemented by targets
310 // that mark instructions with the 'usesCustomInserter' flag. These
311 // instructions are special in various ways, which require special support to
312 // insert. The specified MachineInstr is created but not inserted into any
313 // basic blocks, and this method is called to expand it into a sequence of
314 // instructions, potentially also creating new basic blocks and control flow.
315 // When new basic blocks are inserted and the edges from MBB to its successors
316 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
319 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
320 MachineBasicBlock *MBB) const {
322 dbgs() << "If a target marks an instruction with "
323 "'usesCustomInserter', it must implement "
324 "TargetLowering::EmitInstrWithCustomInserter!";
326 llvm_unreachable(nullptr);
329 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
330 SDNode *Node) const {
331 assert(!MI->hasPostISelHook() &&
332 "If a target marks an instruction with 'hasPostISelHook', "
333 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
336 //===----------------------------------------------------------------------===//
337 // SelectionDAGISel code
338 //===----------------------------------------------------------------------===//
340 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
341 CodeGenOpt::Level OL) :
342 MachineFunctionPass(ID), TM(tm),
343 FuncInfo(new FunctionLoweringInfo()),
344 CurDAG(new SelectionDAG(tm, OL)),
345 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
349 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
350 initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
351 initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
352 initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
355 SelectionDAGISel::~SelectionDAGISel() {
361 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
362 AU.addRequired<AliasAnalysis>();
363 AU.addPreserved<AliasAnalysis>();
364 AU.addRequired<GCModuleInfo>();
365 AU.addPreserved<GCModuleInfo>();
366 AU.addRequired<TargetLibraryInfo>();
367 if (UseMBPI && OptLevel != CodeGenOpt::None)
368 AU.addRequired<BranchProbabilityInfo>();
369 MachineFunctionPass::getAnalysisUsage(AU);
372 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
373 /// may trap on it. In this case we have to split the edge so that the path
374 /// through the predecessor block that doesn't go to the phi block doesn't
375 /// execute the possibly trapping instruction.
377 /// This is required for correctness, so it must be done at -O0.
379 static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
380 // Loop for blocks with phi nodes.
381 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
382 PHINode *PN = dyn_cast<PHINode>(BB->begin());
386 // For each block with a PHI node, check to see if any of the input values
387 // are potentially trapping constant expressions. Constant expressions are
388 // the only potentially trapping value that can occur as the argument to a
390 for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
391 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
392 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
393 if (!CE || !CE->canTrap()) continue;
395 // The only case we have to worry about is when the edge is critical.
396 // Since this block has a PHI Node, we assume it has multiple input
397 // edges: check to see if the pred has multiple successors.
398 BasicBlock *Pred = PN->getIncomingBlock(i);
399 if (Pred->getTerminator()->getNumSuccessors() == 1)
402 // Okay, we have to split this edge.
403 SplitCriticalEdge(Pred->getTerminator(),
404 GetSuccessorNumber(Pred, BB), SDISel, true);
410 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
411 // Do some sanity-checking on the command-line options.
412 assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
413 "-fast-isel-verbose requires -fast-isel");
414 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
415 "-fast-isel-abort requires -fast-isel");
417 const Function &Fn = *mf.getFunction();
420 // Reset the target options before resetting the optimization
422 // FIXME: This is a horrible hack and should be processed via
423 // codegen looking at the optimization level explicitly when
424 // it wants to look at it.
425 TM.resetTargetOptions(Fn);
426 // Reset OptLevel to None for optnone functions.
427 CodeGenOpt::Level NewOptLevel = OptLevel;
428 if (Fn.hasFnAttribute(Attribute::OptimizeNone))
429 NewOptLevel = CodeGenOpt::None;
430 OptLevelChanger OLC(*this, NewOptLevel);
432 TII = MF->getSubtarget().getInstrInfo();
433 TLI = MF->getSubtarget().getTargetLowering();
434 RegInfo = &MF->getRegInfo();
435 AA = &getAnalysis<AliasAnalysis>();
436 LibInfo = &getAnalysis<TargetLibraryInfo>();
437 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
439 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
441 SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
444 FuncInfo->set(Fn, *MF, CurDAG);
446 if (UseMBPI && OptLevel != CodeGenOpt::None)
447 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
449 FuncInfo->BPI = nullptr;
451 SDB->init(GFI, *AA, LibInfo);
453 MF->setHasInlineAsm(false);
455 SelectAllBasicBlocks(Fn);
457 // If the first basic block in the function has live ins that need to be
458 // copied into vregs, emit the copies into the top of the block before
459 // emitting the code for the block.
460 MachineBasicBlock *EntryMBB = MF->begin();
461 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
462 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
464 DenseMap<unsigned, unsigned> LiveInMap;
465 if (!FuncInfo->ArgDbgValues.empty())
466 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
467 E = RegInfo->livein_end(); LI != E; ++LI)
469 LiveInMap.insert(std::make_pair(LI->first, LI->second));
471 // Insert DBG_VALUE instructions for function arguments to the entry block.
472 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
473 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
474 bool hasFI = MI->getOperand(0).isFI();
476 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
477 if (TargetRegisterInfo::isPhysicalRegister(Reg))
478 EntryMBB->insert(EntryMBB->begin(), MI);
480 MachineInstr *Def = RegInfo->getVRegDef(Reg);
482 MachineBasicBlock::iterator InsertPos = Def;
483 // FIXME: VR def may not be in entry block.
484 Def->getParent()->insert(std::next(InsertPos), MI);
486 DEBUG(dbgs() << "Dropping debug info for dead vreg"
487 << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
490 // If Reg is live-in then update debug info to track its copy in a vreg.
491 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
492 if (LDI != LiveInMap.end()) {
493 assert(!hasFI && "There's no handling of frame pointer updating here yet "
495 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
496 MachineBasicBlock::iterator InsertPos = Def;
497 const MDNode *Variable = MI->getDebugVariable();
498 const MDNode *Expr = MI->getDebugExpression();
499 bool IsIndirect = MI->isIndirectDebugValue();
500 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
501 // Def is never a terminator here, so it is ok to increment InsertPos.
502 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
503 TII->get(TargetOpcode::DBG_VALUE), IsIndirect, LDI->second, Offset,
506 // If this vreg is directly copied into an exported register then
507 // that COPY instructions also need DBG_VALUE, if it is the only
508 // user of LDI->second.
509 MachineInstr *CopyUseMI = nullptr;
510 for (MachineRegisterInfo::use_instr_iterator
511 UI = RegInfo->use_instr_begin(LDI->second),
512 E = RegInfo->use_instr_end(); UI != E; ) {
513 MachineInstr *UseMI = &*(UI++);
514 if (UseMI->isDebugValue()) continue;
515 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
516 CopyUseMI = UseMI; continue;
518 // Otherwise this is another use or second copy use.
519 CopyUseMI = nullptr; break;
522 MachineInstr *NewMI =
523 BuildMI(*MF, CopyUseMI->getDebugLoc(),
524 TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
525 CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
526 MachineBasicBlock::iterator Pos = CopyUseMI;
527 EntryMBB->insertAfter(Pos, NewMI);
532 // Determine if there are any calls in this machine function.
533 MachineFrameInfo *MFI = MF->getFrameInfo();
534 for (const auto &MBB : *MF) {
535 if (MFI->hasCalls() && MF->hasInlineAsm())
538 for (const auto &MI : MBB) {
539 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
540 if ((MCID.isCall() && !MCID.isReturn()) ||
541 MI.isStackAligningInlineAsm()) {
542 MFI->setHasCalls(true);
544 if (MI.isInlineAsm()) {
545 MF->setHasInlineAsm(true);
550 // Determine if there is a call to setjmp in the machine function.
551 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
553 // Replace forward-declared registers with the registers containing
554 // the desired value.
555 MachineRegisterInfo &MRI = MF->getRegInfo();
556 for (DenseMap<unsigned, unsigned>::iterator
557 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
559 unsigned From = I->first;
560 unsigned To = I->second;
561 // If To is also scheduled to be replaced, find what its ultimate
564 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
568 // Make sure the new register has a sufficiently constrained register class.
569 if (TargetRegisterInfo::isVirtualRegister(From) &&
570 TargetRegisterInfo::isVirtualRegister(To))
571 MRI.constrainRegClass(To, MRI.getRegClass(From));
573 MRI.replaceRegWith(From, To);
576 // Freeze the set of reserved registers now that MachineFrameInfo has been
577 // set up. All the information required by getReservedRegs() should be
579 MRI.freezeReservedRegs(*MF);
581 // Release function-specific state. SDB and CurDAG are already cleared
585 DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
586 DEBUG(MF->print(dbgs()));
591 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
592 BasicBlock::const_iterator End,
594 // Lower all of the non-terminator instructions. If a call is emitted
595 // as a tail call, cease emitting nodes for this block. Terminators
596 // are handled below.
597 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
600 // Make sure the root of the DAG is up-to-date.
601 CurDAG->setRoot(SDB->getControlRoot());
602 HadTailCall = SDB->HasTailCall;
605 // Final step, emit the lowered DAG as machine code.
609 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
610 SmallPtrSet<SDNode*, 128> VisitedNodes;
611 SmallVector<SDNode*, 128> Worklist;
613 Worklist.push_back(CurDAG->getRoot().getNode());
619 SDNode *N = Worklist.pop_back_val();
621 // If we've already seen this node, ignore it.
622 if (!VisitedNodes.insert(N).second)
625 // Otherwise, add all chain operands to the worklist.
626 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
627 if (N->getOperand(i).getValueType() == MVT::Other)
628 Worklist.push_back(N->getOperand(i).getNode());
630 // If this is a CopyToReg with a vreg dest, process it.
631 if (N->getOpcode() != ISD::CopyToReg)
634 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
635 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
638 // Ignore non-scalar or non-integer values.
639 SDValue Src = N->getOperand(2);
640 EVT SrcVT = Src.getValueType();
641 if (!SrcVT.isInteger() || SrcVT.isVector())
644 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
645 CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
646 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
647 } while (!Worklist.empty());
650 void SelectionDAGISel::CodeGenAndEmitDAG() {
651 std::string GroupName;
652 if (TimePassesIsEnabled)
653 GroupName = "Instruction Selection and Scheduling";
654 std::string BlockName;
655 int BlockNumber = -1;
657 bool MatchFilterBB = false; (void)MatchFilterBB;
659 MatchFilterBB = (!FilterDAGBasicBlockName.empty() &&
660 FilterDAGBasicBlockName ==
661 FuncInfo->MBB->getBasicBlock()->getName().str());
664 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
665 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
669 BlockNumber = FuncInfo->MBB->getNumber();
670 BlockName = MF->getName().str() + ":" +
671 FuncInfo->MBB->getBasicBlock()->getName().str();
673 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
674 << " '" << BlockName << "'\n"; CurDAG->dump());
676 if (ViewDAGCombine1 && MatchFilterBB)
677 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
679 // Run the DAG combiner in pre-legalize mode.
681 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
682 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
685 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
686 << " '" << BlockName << "'\n"; CurDAG->dump());
688 // Second step, hack on the DAG until it only uses operations and types that
689 // the target supports.
690 if (ViewLegalizeTypesDAGs && MatchFilterBB)
691 CurDAG->viewGraph("legalize-types input for " + BlockName);
695 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
696 Changed = CurDAG->LegalizeTypes();
699 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
700 << " '" << BlockName << "'\n"; CurDAG->dump());
702 CurDAG->NewNodesMustHaveLegalTypes = true;
705 if (ViewDAGCombineLT && MatchFilterBB)
706 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
708 // Run the DAG combiner in post-type-legalize mode.
710 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
711 TimePassesIsEnabled);
712 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
715 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
716 << " '" << BlockName << "'\n"; CurDAG->dump());
721 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
722 Changed = CurDAG->LegalizeVectors();
727 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
728 CurDAG->LegalizeTypes();
731 if (ViewDAGCombineLT && MatchFilterBB)
732 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
734 // Run the DAG combiner in post-type-legalize mode.
736 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
737 TimePassesIsEnabled);
738 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
741 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
742 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
745 if (ViewLegalizeDAGs && MatchFilterBB)
746 CurDAG->viewGraph("legalize input for " + BlockName);
749 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
753 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
754 << " '" << BlockName << "'\n"; CurDAG->dump());
756 if (ViewDAGCombine2 && MatchFilterBB)
757 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
759 // Run the DAG combiner in post-legalize mode.
761 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
762 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
765 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
766 << " '" << BlockName << "'\n"; CurDAG->dump());
768 if (OptLevel != CodeGenOpt::None)
769 ComputeLiveOutVRegInfo();
771 if (ViewISelDAGs && MatchFilterBB)
772 CurDAG->viewGraph("isel input for " + BlockName);
774 // Third, instruction select all of the operations to machine code, adding the
775 // code to the MachineBasicBlock.
777 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
778 DoInstructionSelection();
781 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
782 << " '" << BlockName << "'\n"; CurDAG->dump());
784 if (ViewSchedDAGs && MatchFilterBB)
785 CurDAG->viewGraph("scheduler input for " + BlockName);
787 // Schedule machine code.
788 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
790 NamedRegionTimer T("Instruction Scheduling", GroupName,
791 TimePassesIsEnabled);
792 Scheduler->Run(CurDAG, FuncInfo->MBB);
795 if (ViewSUnitDAGs && MatchFilterBB) Scheduler->viewGraph();
797 // Emit machine code to BB. This can change 'BB' to the last block being
799 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
801 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
803 // FuncInfo->InsertPt is passed by reference and set to the end of the
804 // scheduled instructions.
805 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
808 // If the block was split, make sure we update any references that are used to
809 // update PHI nodes later on.
810 if (FirstMBB != LastMBB)
811 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
813 // Free the scheduler state.
815 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
816 TimePassesIsEnabled);
820 // Free the SelectionDAG state, now that we're finished with it.
825 /// ISelUpdater - helper class to handle updates of the instruction selection
827 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
828 SelectionDAG::allnodes_iterator &ISelPosition;
830 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
831 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
833 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
834 /// deleted is the current ISelPosition node, update ISelPosition.
836 void NodeDeleted(SDNode *N, SDNode *E) override {
837 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
841 } // end anonymous namespace
843 void SelectionDAGISel::DoInstructionSelection() {
844 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
845 << FuncInfo->MBB->getNumber()
846 << " '" << FuncInfo->MBB->getName() << "'\n");
850 // Select target instructions for the DAG.
852 // Number all nodes with a topological order and set DAGSize.
853 DAGSize = CurDAG->AssignTopologicalOrder();
855 // Create a dummy node (which is not added to allnodes), that adds
856 // a reference to the root node, preventing it from being deleted,
857 // and tracking any changes of the root.
858 HandleSDNode Dummy(CurDAG->getRoot());
859 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
862 // Make sure that ISelPosition gets properly updated when nodes are deleted
863 // in calls made from this function.
864 ISelUpdater ISU(*CurDAG, ISelPosition);
866 // The AllNodes list is now topological-sorted. Visit the
867 // nodes by starting at the end of the list (the root of the
868 // graph) and preceding back toward the beginning (the entry
870 while (ISelPosition != CurDAG->allnodes_begin()) {
871 SDNode *Node = --ISelPosition;
872 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
873 // but there are currently some corner cases that it misses. Also, this
874 // makes it theoretically possible to disable the DAGCombiner.
875 if (Node->use_empty())
878 SDNode *ResNode = Select(Node);
880 // FIXME: This is pretty gross. 'Select' should be changed to not return
881 // anything at all and this code should be nuked with a tactical strike.
883 // If node should not be replaced, continue with the next one.
884 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
888 ReplaceUses(Node, ResNode);
891 // If after the replacement this node is not used any more,
892 // remove this dead node.
893 if (Node->use_empty()) // Don't delete EntryToken, etc.
894 CurDAG->RemoveDeadNode(Node);
897 CurDAG->setRoot(Dummy.getValue());
900 DEBUG(dbgs() << "===== Instruction selection ends:\n");
902 PostprocessISelDAG();
905 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
906 /// do other setup for EH landing-pad blocks.
907 void SelectionDAGISel::PrepareEHLandingPad() {
908 MachineBasicBlock *MBB = FuncInfo->MBB;
910 // Add a label to mark the beginning of the landing pad. Deletion of the
911 // landing pad can thus be detected via the MachineModuleInfo.
912 MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
914 // Assign the call site to the landing pad's begin label.
915 MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
917 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
918 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
921 // Mark exception register as live in.
922 const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy());
923 if (unsigned Reg = TLI->getExceptionPointerRegister())
924 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
926 // Mark exception selector register as live in.
927 if (unsigned Reg = TLI->getExceptionSelectorRegister())
928 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
931 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
932 /// side-effect free and is either dead or folded into a generated instruction.
933 /// Return false if it needs to be emitted.
934 static bool isFoldedOrDeadInstruction(const Instruction *I,
935 FunctionLoweringInfo *FuncInfo) {
936 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
937 !isa<TerminatorInst>(I) && // Terminators aren't folded.
938 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
939 !isa<LandingPadInst>(I) && // Landingpad instructions aren't folded.
940 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
944 // Collect per Instruction statistics for fast-isel misses. Only those
945 // instructions that cause the bail are accounted for. It does not account for
946 // instructions higher in the block. Thus, summing the per instructions stats
947 // will not add up to what is reported by NumFastIselFailures.
948 static void collectFailStats(const Instruction *I) {
949 switch (I->getOpcode()) {
950 default: assert (0 && "<Invalid operator> ");
953 case Instruction::Ret: NumFastIselFailRet++; return;
954 case Instruction::Br: NumFastIselFailBr++; return;
955 case Instruction::Switch: NumFastIselFailSwitch++; return;
956 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
957 case Instruction::Invoke: NumFastIselFailInvoke++; return;
958 case Instruction::Resume: NumFastIselFailResume++; return;
959 case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
961 // Standard binary operators...
962 case Instruction::Add: NumFastIselFailAdd++; return;
963 case Instruction::FAdd: NumFastIselFailFAdd++; return;
964 case Instruction::Sub: NumFastIselFailSub++; return;
965 case Instruction::FSub: NumFastIselFailFSub++; return;
966 case Instruction::Mul: NumFastIselFailMul++; return;
967 case Instruction::FMul: NumFastIselFailFMul++; return;
968 case Instruction::UDiv: NumFastIselFailUDiv++; return;
969 case Instruction::SDiv: NumFastIselFailSDiv++; return;
970 case Instruction::FDiv: NumFastIselFailFDiv++; return;
971 case Instruction::URem: NumFastIselFailURem++; return;
972 case Instruction::SRem: NumFastIselFailSRem++; return;
973 case Instruction::FRem: NumFastIselFailFRem++; return;
975 // Logical operators...
976 case Instruction::And: NumFastIselFailAnd++; return;
977 case Instruction::Or: NumFastIselFailOr++; return;
978 case Instruction::Xor: NumFastIselFailXor++; return;
980 // Memory instructions...
981 case Instruction::Alloca: NumFastIselFailAlloca++; return;
982 case Instruction::Load: NumFastIselFailLoad++; return;
983 case Instruction::Store: NumFastIselFailStore++; return;
984 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
985 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
986 case Instruction::Fence: NumFastIselFailFence++; return;
987 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
989 // Convert instructions...
990 case Instruction::Trunc: NumFastIselFailTrunc++; return;
991 case Instruction::ZExt: NumFastIselFailZExt++; return;
992 case Instruction::SExt: NumFastIselFailSExt++; return;
993 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
994 case Instruction::FPExt: NumFastIselFailFPExt++; return;
995 case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
996 case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
997 case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
998 case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
999 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
1000 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
1001 case Instruction::BitCast: NumFastIselFailBitCast++; return;
1003 // Other instructions...
1004 case Instruction::ICmp: NumFastIselFailICmp++; return;
1005 case Instruction::FCmp: NumFastIselFailFCmp++; return;
1006 case Instruction::PHI: NumFastIselFailPHI++; return;
1007 case Instruction::Select: NumFastIselFailSelect++; return;
1008 case Instruction::Call: {
1009 if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) {
1010 switch (Intrinsic->getIntrinsicID()) {
1012 NumFastIselFailIntrinsicCall++; return;
1013 case Intrinsic::sadd_with_overflow:
1014 NumFastIselFailSAddWithOverflow++; return;
1015 case Intrinsic::uadd_with_overflow:
1016 NumFastIselFailUAddWithOverflow++; return;
1017 case Intrinsic::ssub_with_overflow:
1018 NumFastIselFailSSubWithOverflow++; return;
1019 case Intrinsic::usub_with_overflow:
1020 NumFastIselFailUSubWithOverflow++; return;
1021 case Intrinsic::smul_with_overflow:
1022 NumFastIselFailSMulWithOverflow++; return;
1023 case Intrinsic::umul_with_overflow:
1024 NumFastIselFailUMulWithOverflow++; return;
1025 case Intrinsic::frameaddress:
1026 NumFastIselFailFrameaddress++; return;
1027 case Intrinsic::sqrt:
1028 NumFastIselFailSqrt++; return;
1029 case Intrinsic::experimental_stackmap:
1030 NumFastIselFailStackMap++; return;
1031 case Intrinsic::experimental_patchpoint_void: // fall-through
1032 case Intrinsic::experimental_patchpoint_i64:
1033 NumFastIselFailPatchPoint++; return;
1036 NumFastIselFailCall++;
1039 case Instruction::Shl: NumFastIselFailShl++; return;
1040 case Instruction::LShr: NumFastIselFailLShr++; return;
1041 case Instruction::AShr: NumFastIselFailAShr++; return;
1042 case Instruction::VAArg: NumFastIselFailVAArg++; return;
1043 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
1044 case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
1045 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
1046 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
1047 case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
1048 case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
1053 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1054 // Initialize the Fast-ISel state, if needed.
1055 FastISel *FastIS = nullptr;
1056 if (TM.Options.EnableFastISel)
1057 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1059 // Iterate over all basic blocks in the function.
1060 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1061 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
1062 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
1063 const BasicBlock *LLVMBB = *I;
1065 if (OptLevel != CodeGenOpt::None) {
1066 bool AllPredsVisited = true;
1067 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1069 if (!FuncInfo->VisitedBBs.count(*PI)) {
1070 AllPredsVisited = false;
1075 if (AllPredsVisited) {
1076 for (BasicBlock::const_iterator I = LLVMBB->begin();
1077 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1078 FuncInfo->ComputePHILiveOutRegInfo(PN);
1080 for (BasicBlock::const_iterator I = LLVMBB->begin();
1081 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1082 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1085 FuncInfo->VisitedBBs.insert(LLVMBB);
1088 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
1089 BasicBlock::const_iterator const End = LLVMBB->end();
1090 BasicBlock::const_iterator BI = End;
1092 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1093 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1095 // Setup an EH landing-pad block.
1096 FuncInfo->ExceptionPointerVirtReg = 0;
1097 FuncInfo->ExceptionSelectorVirtReg = 0;
1098 if (FuncInfo->MBB->isLandingPad())
1099 PrepareEHLandingPad();
1101 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1103 FastIS->startNewBlock();
1105 // Emit code for any incoming arguments. This must happen before
1106 // beginning FastISel on the entry block.
1107 if (LLVMBB == &Fn.getEntryBlock()) {
1110 // Lower any arguments needed in this block if this is the entry block.
1111 if (!FastIS->lowerArguments()) {
1112 // Fast isel failed to lower these arguments
1113 ++NumFastIselFailLowerArguments;
1114 if (EnableFastISelAbortArgs)
1115 llvm_unreachable("FastISel didn't lower all arguments");
1117 // Use SelectionDAG argument lowering
1119 CurDAG->setRoot(SDB->getControlRoot());
1121 CodeGenAndEmitDAG();
1124 // If we inserted any instructions at the beginning, make a note of
1125 // where they are, so we can be sure to emit subsequent instructions
1127 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1128 FastIS->setLastLocalValue(std::prev(FuncInfo->InsertPt));
1130 FastIS->setLastLocalValue(nullptr);
1133 unsigned NumFastIselRemaining = std::distance(Begin, End);
1134 // Do FastISel on as many instructions as possible.
1135 for (; BI != Begin; --BI) {
1136 const Instruction *Inst = std::prev(BI);
1138 // If we no longer require this instruction, skip it.
1139 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1140 --NumFastIselRemaining;
1144 // Bottom-up: reset the insert pos at the top, after any local-value
1146 FastIS->recomputeInsertPt();
1148 // Try to select the instruction with FastISel.
1149 if (FastIS->selectInstruction(Inst)) {
1150 --NumFastIselRemaining;
1151 ++NumFastIselSuccess;
1152 // If fast isel succeeded, skip over all the folded instructions, and
1153 // then see if there is a load right before the selected instructions.
1154 // Try to fold the load if so.
1155 const Instruction *BeforeInst = Inst;
1156 while (BeforeInst != Begin) {
1157 BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
1158 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1161 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1162 BeforeInst->hasOneUse() &&
1163 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1164 // If we succeeded, don't re-select the load.
1165 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1166 --NumFastIselRemaining;
1167 ++NumFastIselSuccess;
1173 if (EnableFastISelVerbose2)
1174 collectFailStats(Inst);
1177 // Then handle certain instructions as single-LLVM-Instruction blocks.
1178 if (isa<CallInst>(Inst)) {
1180 if (EnableFastISelVerbose || EnableFastISelAbort) {
1181 dbgs() << "FastISel missed call: ";
1185 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
1186 unsigned &R = FuncInfo->ValueMap[Inst];
1188 R = FuncInfo->CreateRegs(Inst->getType());
1191 bool HadTailCall = false;
1192 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1193 SelectBasicBlock(Inst, BI, HadTailCall);
1195 // If the call was emitted as a tail call, we're done with the block.
1196 // We also need to delete any previously emitted instructions.
1198 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1203 // Recompute NumFastIselRemaining as Selection DAG instruction
1204 // selection may have handled the call, input args, etc.
1205 unsigned RemainingNow = std::distance(Begin, BI);
1206 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1207 NumFastIselRemaining = RemainingNow;
1211 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
1212 // Don't abort, and use a different message for terminator misses.
1213 NumFastIselFailures += NumFastIselRemaining;
1214 if (EnableFastISelVerbose || EnableFastISelAbort) {
1215 dbgs() << "FastISel missed terminator: ";
1219 NumFastIselFailures += NumFastIselRemaining;
1220 if (EnableFastISelVerbose || EnableFastISelAbort) {
1221 dbgs() << "FastISel miss: ";
1224 if (EnableFastISelAbort)
1225 // The "fast" selector couldn't handle something and bailed.
1226 // For the purpose of debugging, just abort.
1227 llvm_unreachable("FastISel didn't select the entire block");
1232 FastIS->recomputeInsertPt();
1234 // Lower any arguments needed in this block if this is the entry block.
1235 if (LLVMBB == &Fn.getEntryBlock()) {
1244 ++NumFastIselBlocks;
1247 // Run SelectionDAG instruction selection on the remainder of the block
1248 // not handled by FastISel. If FastISel is not run, this is the entire
1251 SelectBasicBlock(Begin, BI, HadTailCall);
1255 FuncInfo->PHINodesToUpdate.clear();
1259 SDB->clearDanglingDebugInfo();
1260 SDB->SPDescriptor.resetPerFunctionState();
1263 /// Given that the input MI is before a partial terminator sequence TSeq, return
1264 /// true if M + TSeq also a partial terminator sequence.
1266 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1267 /// lowering copy vregs into physical registers, which are then passed into
1268 /// terminator instructors so we can satisfy ABI constraints. A partial
1269 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1270 /// may be the whole terminator sequence).
1271 static bool MIIsInTerminatorSequence(const MachineInstr *MI) {
1272 // If we do not have a copy or an implicit def, we return true if and only if
1273 // MI is a debug value.
1274 if (!MI->isCopy() && !MI->isImplicitDef())
1275 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1276 // physical registers if there is debug info associated with the terminator
1277 // of our mbb. We want to include said debug info in our terminator
1278 // sequence, so we return true in that case.
1279 return MI->isDebugValue();
1281 // We have left the terminator sequence if we are not doing one of the
1284 // 1. Copying a vreg into a physical register.
1285 // 2. Copying a vreg into a vreg.
1286 // 3. Defining a register via an implicit def.
1288 // OPI should always be a register definition...
1289 MachineInstr::const_mop_iterator OPI = MI->operands_begin();
1290 if (!OPI->isReg() || !OPI->isDef())
1293 // Defining any register via an implicit def is always ok.
1294 if (MI->isImplicitDef())
1297 // Grab the copy source...
1298 MachineInstr::const_mop_iterator OPI2 = OPI;
1300 assert(OPI2 != MI->operands_end()
1301 && "Should have a copy implying we should have 2 arguments.");
1303 // Make sure that the copy dest is not a vreg when the copy source is a
1304 // physical register.
1305 if (!OPI2->isReg() ||
1306 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
1307 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
1313 /// Find the split point at which to splice the end of BB into its success stack
1314 /// protector check machine basic block.
1316 /// On many platforms, due to ABI constraints, terminators, even before register
1317 /// allocation, use physical registers. This creates an issue for us since
1318 /// physical registers at this point can not travel across basic
1319 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1320 /// when they enter functions and moves them through a sequence of copies back
1321 /// into the physical registers right before the terminator creating a
1322 /// ``Terminator Sequence''. This function is searching for the beginning of the
1323 /// terminator sequence so that we can ensure that we splice off not just the
1324 /// terminator, but additionally the copies that move the vregs into the
1325 /// physical registers.
1326 static MachineBasicBlock::iterator
1327 FindSplitPointForStackProtector(MachineBasicBlock *BB, DebugLoc DL) {
1328 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1330 if (SplitPoint == BB->begin())
1333 MachineBasicBlock::iterator Start = BB->begin();
1334 MachineBasicBlock::iterator Previous = SplitPoint;
1337 while (MIIsInTerminatorSequence(Previous)) {
1338 SplitPoint = Previous;
1339 if (Previous == Start)
1348 SelectionDAGISel::FinishBasicBlock() {
1350 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1351 << FuncInfo->PHINodesToUpdate.size() << "\n";
1352 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1353 dbgs() << "Node " << i << " : ("
1354 << FuncInfo->PHINodesToUpdate[i].first
1355 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1357 const bool MustUpdatePHINodes = SDB->SwitchCases.empty() &&
1358 SDB->JTCases.empty() &&
1359 SDB->BitTestCases.empty();
1361 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1362 // PHI nodes in successors.
1363 if (MustUpdatePHINodes) {
1364 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1365 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1366 assert(PHI->isPHI() &&
1367 "This is not a machine PHI node that we are updating!");
1368 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1370 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1374 // Handle stack protector.
1375 if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1376 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1377 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1379 // Find the split point to split the parent mbb. At the same time copy all
1380 // physical registers used in the tail of parent mbb into virtual registers
1381 // before the split point and back into physical registers after the split
1382 // point. This prevents us needing to deal with Live-ins and many other
1383 // register allocation issues caused by us splitting the parent mbb. The
1384 // register allocator will clean up said virtual copies later on.
1385 MachineBasicBlock::iterator SplitPoint =
1386 FindSplitPointForStackProtector(ParentMBB, SDB->getCurDebugLoc());
1388 // Splice the terminator of ParentMBB into SuccessMBB.
1389 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1393 // Add compare/jump on neq/jump to the parent BB.
1394 FuncInfo->MBB = ParentMBB;
1395 FuncInfo->InsertPt = ParentMBB->end();
1396 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1397 CurDAG->setRoot(SDB->getRoot());
1399 CodeGenAndEmitDAG();
1401 // CodeGen Failure MBB if we have not codegened it yet.
1402 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1403 if (!FailureMBB->size()) {
1404 FuncInfo->MBB = FailureMBB;
1405 FuncInfo->InsertPt = FailureMBB->end();
1406 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1407 CurDAG->setRoot(SDB->getRoot());
1409 CodeGenAndEmitDAG();
1412 // Clear the Per-BB State.
1413 SDB->SPDescriptor.resetPerBBState();
1416 // If we updated PHI Nodes, return early.
1417 if (MustUpdatePHINodes)
1420 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1421 // Lower header first, if it wasn't already lowered
1422 if (!SDB->BitTestCases[i].Emitted) {
1423 // Set the current basic block to the mbb we wish to insert the code into
1424 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1425 FuncInfo->InsertPt = FuncInfo->MBB->end();
1427 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1428 CurDAG->setRoot(SDB->getRoot());
1430 CodeGenAndEmitDAG();
1433 uint32_t UnhandledWeight = 0;
1434 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
1435 UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
1437 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1438 UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
1439 // Set the current basic block to the mbb we wish to insert the code into
1440 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1441 FuncInfo->InsertPt = FuncInfo->MBB->end();
1444 SDB->visitBitTestCase(SDB->BitTestCases[i],
1445 SDB->BitTestCases[i].Cases[j+1].ThisBB,
1447 SDB->BitTestCases[i].Reg,
1448 SDB->BitTestCases[i].Cases[j],
1451 SDB->visitBitTestCase(SDB->BitTestCases[i],
1452 SDB->BitTestCases[i].Default,
1454 SDB->BitTestCases[i].Reg,
1455 SDB->BitTestCases[i].Cases[j],
1459 CurDAG->setRoot(SDB->getRoot());
1461 CodeGenAndEmitDAG();
1465 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1467 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1468 MachineBasicBlock *PHIBB = PHI->getParent();
1469 assert(PHI->isPHI() &&
1470 "This is not a machine PHI node that we are updating!");
1471 // This is "default" BB. We have two jumps to it. From "header" BB and
1472 // from last "case" BB.
1473 if (PHIBB == SDB->BitTestCases[i].Default)
1474 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1475 .addMBB(SDB->BitTestCases[i].Parent)
1476 .addReg(FuncInfo->PHINodesToUpdate[pi].second)
1477 .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
1478 // One of "cases" BB.
1479 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1481 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1482 if (cBB->isSuccessor(PHIBB))
1483 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1487 SDB->BitTestCases.clear();
1489 // If the JumpTable record is filled in, then we need to emit a jump table.
1490 // Updating the PHI nodes is tricky in this case, since we need to determine
1491 // whether the PHI is a successor of the range check MBB or the jump table MBB
1492 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1493 // Lower header first, if it wasn't already lowered
1494 if (!SDB->JTCases[i].first.Emitted) {
1495 // Set the current basic block to the mbb we wish to insert the code into
1496 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1497 FuncInfo->InsertPt = FuncInfo->MBB->end();
1499 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1501 CurDAG->setRoot(SDB->getRoot());
1503 CodeGenAndEmitDAG();
1506 // Set the current basic block to the mbb we wish to insert the code into
1507 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1508 FuncInfo->InsertPt = FuncInfo->MBB->end();
1510 SDB->visitJumpTable(SDB->JTCases[i].second);
1511 CurDAG->setRoot(SDB->getRoot());
1513 CodeGenAndEmitDAG();
1516 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1518 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1519 MachineBasicBlock *PHIBB = PHI->getParent();
1520 assert(PHI->isPHI() &&
1521 "This is not a machine PHI node that we are updating!");
1522 // "default" BB. We can go there only from header BB.
1523 if (PHIBB == SDB->JTCases[i].second.Default)
1524 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1525 .addMBB(SDB->JTCases[i].first.HeaderBB);
1526 // JT BB. Just iterate over successors here
1527 if (FuncInfo->MBB->isSuccessor(PHIBB))
1528 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1531 SDB->JTCases.clear();
1533 // If the switch block involved a branch to one of the actual successors, we
1534 // need to update PHI nodes in that block.
1535 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1536 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1537 assert(PHI->isPHI() &&
1538 "This is not a machine PHI node that we are updating!");
1539 if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
1540 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1543 // If we generated any switch lowering information, build and codegen any
1544 // additional DAGs necessary.
1545 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1546 // Set the current basic block to the mbb we wish to insert the code into
1547 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1548 FuncInfo->InsertPt = FuncInfo->MBB->end();
1550 // Determine the unique successors.
1551 SmallVector<MachineBasicBlock *, 2> Succs;
1552 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1553 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1554 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1556 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1557 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1558 CurDAG->setRoot(SDB->getRoot());
1560 CodeGenAndEmitDAG();
1562 // Remember the last block, now that any splitting is done, for use in
1563 // populating PHI nodes in successors.
1564 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1566 // Handle any PHI nodes in successors of this chunk, as if we were coming
1567 // from the original BB before switch expansion. Note that PHI nodes can
1568 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1569 // handle them the right number of times.
1570 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1571 FuncInfo->MBB = Succs[i];
1572 FuncInfo->InsertPt = FuncInfo->MBB->end();
1573 // FuncInfo->MBB may have been removed from the CFG if a branch was
1575 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1576 for (MachineBasicBlock::iterator
1577 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1578 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1579 MachineInstrBuilder PHI(*MF, MBBI);
1580 // This value for this PHI node is recorded in PHINodesToUpdate.
1581 for (unsigned pn = 0; ; ++pn) {
1582 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1583 "Didn't find PHI entry!");
1584 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1585 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1593 SDB->SwitchCases.clear();
1597 /// Create the scheduler. If a specific scheduler was specified
1598 /// via the SchedulerRegistry, use it, otherwise select the
1599 /// one preferred by the target.
1601 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1602 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1606 RegisterScheduler::setDefault(Ctor);
1609 return Ctor(this, OptLevel);
1612 //===----------------------------------------------------------------------===//
1613 // Helper functions used by the generated instruction selector.
1614 //===----------------------------------------------------------------------===//
1615 // Calls to these methods are generated by tblgen.
1617 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1618 /// the dag combiner simplified the 255, we still want to match. RHS is the
1619 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1620 /// specified in the .td file (e.g. 255).
1621 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1622 int64_t DesiredMaskS) const {
1623 const APInt &ActualMask = RHS->getAPIntValue();
1624 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1626 // If the actual mask exactly matches, success!
1627 if (ActualMask == DesiredMask)
1630 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1631 if (ActualMask.intersects(~DesiredMask))
1634 // Otherwise, the DAG Combiner may have proven that the value coming in is
1635 // either already zero or is not demanded. Check for known zero input bits.
1636 APInt NeededMask = DesiredMask & ~ActualMask;
1637 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1640 // TODO: check to see if missing bits are just not demanded.
1642 // Otherwise, this pattern doesn't match.
1646 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1647 /// the dag combiner simplified the 255, we still want to match. RHS is the
1648 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1649 /// specified in the .td file (e.g. 255).
1650 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1651 int64_t DesiredMaskS) const {
1652 const APInt &ActualMask = RHS->getAPIntValue();
1653 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1655 // If the actual mask exactly matches, success!
1656 if (ActualMask == DesiredMask)
1659 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1660 if (ActualMask.intersects(~DesiredMask))
1663 // Otherwise, the DAG Combiner may have proven that the value coming in is
1664 // either already zero or is not demanded. Check for known zero input bits.
1665 APInt NeededMask = DesiredMask & ~ActualMask;
1667 APInt KnownZero, KnownOne;
1668 CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
1670 // If all the missing bits in the or are already known to be set, match!
1671 if ((NeededMask & KnownOne) == NeededMask)
1674 // TODO: check to see if missing bits are just not demanded.
1676 // Otherwise, this pattern doesn't match.
1681 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1682 /// by tblgen. Others should not call it.
1683 void SelectionDAGISel::
1684 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1685 std::vector<SDValue> InOps;
1686 std::swap(InOps, Ops);
1688 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1689 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1690 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1691 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1693 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1694 if (InOps[e-1].getValueType() == MVT::Glue)
1695 --e; // Don't process a glue operand if it is here.
1698 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1699 if (!InlineAsm::isMemKind(Flags)) {
1700 // Just skip over this operand, copying the operands verbatim.
1701 Ops.insert(Ops.end(), InOps.begin()+i,
1702 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1703 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1705 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1706 "Memory operand with multiple values?");
1707 // Otherwise, this is a memory operand. Ask the target to select it.
1708 std::vector<SDValue> SelOps;
1709 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1710 report_fatal_error("Could not match memory address. Inline asm"
1713 // Add this to the output node.
1715 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1716 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1717 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1722 // Add the glue input back if present.
1723 if (e != InOps.size())
1724 Ops.push_back(InOps.back());
1727 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1730 static SDNode *findGlueUse(SDNode *N) {
1731 unsigned FlagResNo = N->getNumValues()-1;
1732 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1733 SDUse &Use = I.getUse();
1734 if (Use.getResNo() == FlagResNo)
1735 return Use.getUser();
1740 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1741 /// This function recursively traverses up the operand chain, ignoring
1743 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1744 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
1745 bool IgnoreChains) {
1746 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1747 // greater than all of its (recursive) operands. If we scan to a point where
1748 // 'use' is smaller than the node we're scanning for, then we know we will
1751 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1752 // happen because we scan down to newly selected nodes in the case of glue
1754 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1757 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1758 // won't fail if we scan it again.
1759 if (!Visited.insert(Use).second)
1762 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1763 // Ignore chain uses, they are validated by HandleMergeInputChains.
1764 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1767 SDNode *N = Use->getOperand(i).getNode();
1769 if (Use == ImmedUse || Use == Root)
1770 continue; // We are not looking for immediate use.
1775 // Traverse up the operand chain.
1776 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1782 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1783 /// operand node N of U during instruction selection that starts at Root.
1784 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1785 SDNode *Root) const {
1786 if (OptLevel == CodeGenOpt::None) return false;
1787 return N.hasOneUse();
1790 /// IsLegalToFold - Returns true if the specific operand node N of
1791 /// U can be folded during instruction selection that starts at Root.
1792 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1793 CodeGenOpt::Level OptLevel,
1794 bool IgnoreChains) {
1795 if (OptLevel == CodeGenOpt::None) return false;
1797 // If Root use can somehow reach N through a path that that doesn't contain
1798 // U then folding N would create a cycle. e.g. In the following
1799 // diagram, Root can reach N through X. If N is folded into into Root, then
1800 // X is both a predecessor and a successor of U.
1811 // * indicates nodes to be folded together.
1813 // If Root produces glue, then it gets (even more) interesting. Since it
1814 // will be "glued" together with its glue use in the scheduler, we need to
1815 // check if it might reach N.
1834 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1835 // (call it Fold), then X is a predecessor of GU and a successor of
1836 // Fold. But since Fold and GU are glued together, this will create
1837 // a cycle in the scheduling graph.
1839 // If the node has glue, walk down the graph to the "lowest" node in the
1841 EVT VT = Root->getValueType(Root->getNumValues()-1);
1842 while (VT == MVT::Glue) {
1843 SDNode *GU = findGlueUse(Root);
1847 VT = Root->getValueType(Root->getNumValues()-1);
1849 // If our query node has a glue result with a use, we've walked up it. If
1850 // the user (which has already been selected) has a chain or indirectly uses
1851 // the chain, our WalkChainUsers predicate will not consider it. Because of
1852 // this, we cannot ignore chains in this predicate.
1853 IgnoreChains = false;
1857 SmallPtrSet<SDNode*, 16> Visited;
1858 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1861 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1862 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1863 SelectInlineAsmMemoryOperands(Ops);
1865 EVT VTs[] = { MVT::Other, MVT::Glue };
1866 SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N), VTs, Ops);
1868 return New.getNode();
1872 *SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
1874 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(0));
1875 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
1877 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0));
1878 SDValue New = CurDAG->getCopyFromReg(
1879 CurDAG->getEntryNode(), dl, Reg, Op->getValueType(0));
1881 return New.getNode();
1885 *SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
1887 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
1888 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
1889 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
1890 Op->getOperand(2).getValueType());
1891 SDValue New = CurDAG->getCopyToReg(
1892 CurDAG->getEntryNode(), dl, Reg, Op->getOperand(2));
1894 return New.getNode();
1899 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1900 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1903 /// GetVBR - decode a vbr encoding whose top bit is set.
1904 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
1905 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1906 assert(Val >= 128 && "Not a VBR");
1907 Val &= 127; // Remove first vbr bit.
1912 NextBits = MatcherTable[Idx++];
1913 Val |= (NextBits&127) << Shift;
1915 } while (NextBits & 128);
1921 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1922 /// interior glue and chain results to use the new glue and chain results.
1923 void SelectionDAGISel::
1924 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1925 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1927 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1928 bool isMorphNodeTo) {
1929 SmallVector<SDNode*, 4> NowDeadNodes;
1931 // Now that all the normal results are replaced, we replace the chain and
1932 // glue results if present.
1933 if (!ChainNodesMatched.empty()) {
1934 assert(InputChain.getNode() &&
1935 "Matched input chains but didn't produce a chain");
1936 // Loop over all of the nodes we matched that produced a chain result.
1937 // Replace all the chain results with the final chain we ended up with.
1938 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1939 SDNode *ChainNode = ChainNodesMatched[i];
1941 // If this node was already deleted, don't look at it.
1942 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1945 // Don't replace the results of the root node if we're doing a
1947 if (ChainNode == NodeToMatch && isMorphNodeTo)
1950 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1951 if (ChainVal.getValueType() == MVT::Glue)
1952 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1953 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1954 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
1956 // If the node became dead and we haven't already seen it, delete it.
1957 if (ChainNode->use_empty() &&
1958 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1959 NowDeadNodes.push_back(ChainNode);
1963 // If the result produces glue, update any glue results in the matched
1964 // pattern with the glue result.
1965 if (InputGlue.getNode()) {
1966 // Handle any interior nodes explicitly marked.
1967 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1968 SDNode *FRN = GlueResultNodesMatched[i];
1970 // If this node was already deleted, don't look at it.
1971 if (FRN->getOpcode() == ISD::DELETED_NODE)
1974 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
1975 "Doesn't have a glue result");
1976 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1979 // If the node became dead and we haven't already seen it, delete it.
1980 if (FRN->use_empty() &&
1981 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1982 NowDeadNodes.push_back(FRN);
1986 if (!NowDeadNodes.empty())
1987 CurDAG->RemoveDeadNodes(NowDeadNodes);
1989 DEBUG(dbgs() << "ISEL: Match complete!\n");
1995 CR_LeadsToInteriorNode
1998 /// WalkChainUsers - Walk down the users of the specified chained node that is
1999 /// part of the pattern we're matching, looking at all of the users we find.
2000 /// This determines whether something is an interior node, whether we have a
2001 /// non-pattern node in between two pattern nodes (which prevent folding because
2002 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
2003 /// between pattern nodes (in which case the TF becomes part of the pattern).
2005 /// The walk we do here is guaranteed to be small because we quickly get down to
2006 /// already selected nodes "below" us.
2008 WalkChainUsers(const SDNode *ChainedNode,
2009 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
2010 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
2011 ChainResult Result = CR_Simple;
2013 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
2014 E = ChainedNode->use_end(); UI != E; ++UI) {
2015 // Make sure the use is of the chain, not some other value we produce.
2016 if (UI.getUse().getValueType() != MVT::Other) continue;
2020 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
2023 // If we see an already-selected machine node, then we've gone beyond the
2024 // pattern that we're selecting down into the already selected chunk of the
2026 unsigned UserOpcode = User->getOpcode();
2027 if (User->isMachineOpcode() ||
2028 UserOpcode == ISD::CopyToReg ||
2029 UserOpcode == ISD::CopyFromReg ||
2030 UserOpcode == ISD::INLINEASM ||
2031 UserOpcode == ISD::EH_LABEL ||
2032 UserOpcode == ISD::LIFETIME_START ||
2033 UserOpcode == ISD::LIFETIME_END) {
2034 // If their node ID got reset to -1 then they've already been selected.
2035 // Treat them like a MachineOpcode.
2036 if (User->getNodeId() == -1)
2040 // If we have a TokenFactor, we handle it specially.
2041 if (User->getOpcode() != ISD::TokenFactor) {
2042 // If the node isn't a token factor and isn't part of our pattern, then it
2043 // must be a random chained node in between two nodes we're selecting.
2044 // This happens when we have something like:
2049 // Because we structurally match the load/store as a read/modify/write,
2050 // but the call is chained between them. We cannot fold in this case
2051 // because it would induce a cycle in the graph.
2052 if (!std::count(ChainedNodesInPattern.begin(),
2053 ChainedNodesInPattern.end(), User))
2054 return CR_InducesCycle;
2056 // Otherwise we found a node that is part of our pattern. For example in:
2060 // This would happen when we're scanning down from the load and see the
2061 // store as a user. Record that there is a use of ChainedNode that is
2062 // part of the pattern and keep scanning uses.
2063 Result = CR_LeadsToInteriorNode;
2064 InteriorChainedNodes.push_back(User);
2068 // If we found a TokenFactor, there are two cases to consider: first if the
2069 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
2070 // uses of the TF are in our pattern) we just want to ignore it. Second,
2071 // the TokenFactor can be sandwiched in between two chained nodes, like so:
2077 // | \ DAG's like cheese
2080 // [TokenFactor] [Op]
2087 // In this case, the TokenFactor becomes part of our match and we rewrite it
2088 // as a new TokenFactor.
2090 // To distinguish these two cases, do a recursive walk down the uses.
2091 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
2093 // If the uses of the TokenFactor are just already-selected nodes, ignore
2094 // it, it is "below" our pattern.
2096 case CR_InducesCycle:
2097 // If the uses of the TokenFactor lead to nodes that are not part of our
2098 // pattern that are not selected, folding would turn this into a cycle,
2100 return CR_InducesCycle;
2101 case CR_LeadsToInteriorNode:
2102 break; // Otherwise, keep processing.
2105 // Okay, we know we're in the interesting interior case. The TokenFactor
2106 // is now going to be considered part of the pattern so that we rewrite its
2107 // uses (it may have uses that are not part of the pattern) with the
2108 // ultimate chain result of the generated code. We will also add its chain
2109 // inputs as inputs to the ultimate TokenFactor we create.
2110 Result = CR_LeadsToInteriorNode;
2111 ChainedNodesInPattern.push_back(User);
2112 InteriorChainedNodes.push_back(User);
2119 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2120 /// operation for when the pattern matched at least one node with a chains. The
2121 /// input vector contains a list of all of the chained nodes that we match. We
2122 /// must determine if this is a valid thing to cover (i.e. matching it won't
2123 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2124 /// be used as the input node chain for the generated nodes.
2126 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2127 SelectionDAG *CurDAG) {
2128 // Walk all of the chained nodes we've matched, recursively scanning down the
2129 // users of the chain result. This adds any TokenFactor nodes that are caught
2130 // in between chained nodes to the chained and interior nodes list.
2131 SmallVector<SDNode*, 3> InteriorChainedNodes;
2132 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2133 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
2134 InteriorChainedNodes) == CR_InducesCycle)
2135 return SDValue(); // Would induce a cycle.
2138 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
2139 // that we are interested in. Form our input TokenFactor node.
2140 SmallVector<SDValue, 3> InputChains;
2141 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2142 // Add the input chain of this node to the InputChains list (which will be
2143 // the operands of the generated TokenFactor) if it's not an interior node.
2144 SDNode *N = ChainNodesMatched[i];
2145 if (N->getOpcode() != ISD::TokenFactor) {
2146 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
2149 // Otherwise, add the input chain.
2150 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
2151 assert(InChain.getValueType() == MVT::Other && "Not a chain");
2152 InputChains.push_back(InChain);
2156 // If we have a token factor, we want to add all inputs of the token factor
2157 // that are not part of the pattern we're matching.
2158 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
2159 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
2160 N->getOperand(op).getNode()))
2161 InputChains.push_back(N->getOperand(op));
2165 if (InputChains.size() == 1)
2166 return InputChains[0];
2167 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2168 MVT::Other, InputChains);
2171 /// MorphNode - Handle morphing a node in place for the selector.
2172 SDNode *SelectionDAGISel::
2173 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2174 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2175 // It is possible we're using MorphNodeTo to replace a node with no
2176 // normal results with one that has a normal result (or we could be
2177 // adding a chain) and the input could have glue and chains as well.
2178 // In this case we need to shift the operands down.
2179 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2180 // than the old isel though.
2181 int OldGlueResultNo = -1, OldChainResultNo = -1;
2183 unsigned NTMNumResults = Node->getNumValues();
2184 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2185 OldGlueResultNo = NTMNumResults-1;
2186 if (NTMNumResults != 1 &&
2187 Node->getValueType(NTMNumResults-2) == MVT::Other)
2188 OldChainResultNo = NTMNumResults-2;
2189 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2190 OldChainResultNo = NTMNumResults-1;
2192 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2193 // that this deletes operands of the old node that become dead.
2194 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2196 // MorphNodeTo can operate in two ways: if an existing node with the
2197 // specified operands exists, it can just return it. Otherwise, it
2198 // updates the node in place to have the requested operands.
2200 // If we updated the node in place, reset the node ID. To the isel,
2201 // this should be just like a newly allocated machine node.
2205 unsigned ResNumResults = Res->getNumValues();
2206 // Move the glue if needed.
2207 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2208 (unsigned)OldGlueResultNo != ResNumResults-1)
2209 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
2210 SDValue(Res, ResNumResults-1));
2212 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2215 // Move the chain reference if needed.
2216 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2217 (unsigned)OldChainResultNo != ResNumResults-1)
2218 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
2219 SDValue(Res, ResNumResults-1));
2221 // Otherwise, no replacement happened because the node already exists. Replace
2222 // Uses of the old node with the new one.
2224 CurDAG->ReplaceAllUsesWith(Node, Res);
2229 /// CheckSame - Implements OP_CheckSame.
2230 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2231 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2233 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2234 // Accept if it is exactly the same as a previously recorded node.
2235 unsigned RecNo = MatcherTable[MatcherIndex++];
2236 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2237 return N == RecordedNodes[RecNo].first;
2240 /// CheckChildSame - Implements OP_CheckChildXSame.
2241 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2242 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2244 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes,
2246 if (ChildNo >= N.getNumOperands())
2247 return false; // Match fails if out of range child #.
2248 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2252 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2253 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2254 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2255 const SelectionDAGISel &SDISel) {
2256 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2259 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2260 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2261 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2262 const SelectionDAGISel &SDISel, SDNode *N) {
2263 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2266 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2267 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2269 uint16_t Opc = MatcherTable[MatcherIndex++];
2270 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2271 return N->getOpcode() == Opc;
2274 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2275 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2276 SDValue N, const TargetLowering *TLI) {
2277 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2278 if (N.getValueType() == VT) return true;
2280 // Handle the case when VT is iPTR.
2281 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
2284 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2285 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2286 SDValue N, const TargetLowering *TLI, unsigned ChildNo) {
2287 if (ChildNo >= N.getNumOperands())
2288 return false; // Match fails if out of range child #.
2289 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
2292 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2293 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2295 return cast<CondCodeSDNode>(N)->get() ==
2296 (ISD::CondCode)MatcherTable[MatcherIndex++];
2299 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2300 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2301 SDValue N, const TargetLowering *TLI) {
2302 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2303 if (cast<VTSDNode>(N)->getVT() == VT)
2306 // Handle the case when VT is iPTR.
2307 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
2310 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2311 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2313 int64_t Val = MatcherTable[MatcherIndex++];
2315 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2317 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2318 return C && C->getSExtValue() == Val;
2321 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2322 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2323 SDValue N, unsigned ChildNo) {
2324 if (ChildNo >= N.getNumOperands())
2325 return false; // Match fails if out of range child #.
2326 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2329 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2330 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2331 SDValue N, const SelectionDAGISel &SDISel) {
2332 int64_t Val = MatcherTable[MatcherIndex++];
2334 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2336 if (N->getOpcode() != ISD::AND) return false;
2338 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2339 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2342 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2343 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2344 SDValue N, const SelectionDAGISel &SDISel) {
2345 int64_t Val = MatcherTable[MatcherIndex++];
2347 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2349 if (N->getOpcode() != ISD::OR) return false;
2351 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2352 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2355 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2356 /// scope, evaluate the current node. If the current predicate is known to
2357 /// fail, set Result=true and return anything. If the current predicate is
2358 /// known to pass, set Result=false and return the MatcherIndex to continue
2359 /// with. If the current predicate is unknown, set Result=false and return the
2360 /// MatcherIndex to continue with.
2361 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2362 unsigned Index, SDValue N,
2364 const SelectionDAGISel &SDISel,
2365 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2366 switch (Table[Index++]) {
2369 return Index-1; // Could not evaluate this predicate.
2370 case SelectionDAGISel::OPC_CheckSame:
2371 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2373 case SelectionDAGISel::OPC_CheckChild0Same:
2374 case SelectionDAGISel::OPC_CheckChild1Same:
2375 case SelectionDAGISel::OPC_CheckChild2Same:
2376 case SelectionDAGISel::OPC_CheckChild3Same:
2377 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2378 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2380 case SelectionDAGISel::OPC_CheckPatternPredicate:
2381 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2383 case SelectionDAGISel::OPC_CheckPredicate:
2384 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2386 case SelectionDAGISel::OPC_CheckOpcode:
2387 Result = !::CheckOpcode(Table, Index, N.getNode());
2389 case SelectionDAGISel::OPC_CheckType:
2390 Result = !::CheckType(Table, Index, N, SDISel.TLI);
2392 case SelectionDAGISel::OPC_CheckChild0Type:
2393 case SelectionDAGISel::OPC_CheckChild1Type:
2394 case SelectionDAGISel::OPC_CheckChild2Type:
2395 case SelectionDAGISel::OPC_CheckChild3Type:
2396 case SelectionDAGISel::OPC_CheckChild4Type:
2397 case SelectionDAGISel::OPC_CheckChild5Type:
2398 case SelectionDAGISel::OPC_CheckChild6Type:
2399 case SelectionDAGISel::OPC_CheckChild7Type:
2400 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
2402 SelectionDAGISel::OPC_CheckChild0Type);
2404 case SelectionDAGISel::OPC_CheckCondCode:
2405 Result = !::CheckCondCode(Table, Index, N);
2407 case SelectionDAGISel::OPC_CheckValueType:
2408 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
2410 case SelectionDAGISel::OPC_CheckInteger:
2411 Result = !::CheckInteger(Table, Index, N);
2413 case SelectionDAGISel::OPC_CheckChild0Integer:
2414 case SelectionDAGISel::OPC_CheckChild1Integer:
2415 case SelectionDAGISel::OPC_CheckChild2Integer:
2416 case SelectionDAGISel::OPC_CheckChild3Integer:
2417 case SelectionDAGISel::OPC_CheckChild4Integer:
2418 Result = !::CheckChildInteger(Table, Index, N,
2419 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2421 case SelectionDAGISel::OPC_CheckAndImm:
2422 Result = !::CheckAndImm(Table, Index, N, SDISel);
2424 case SelectionDAGISel::OPC_CheckOrImm:
2425 Result = !::CheckOrImm(Table, Index, N, SDISel);
2433 /// FailIndex - If this match fails, this is the index to continue with.
2436 /// NodeStack - The node stack when the scope was formed.
2437 SmallVector<SDValue, 4> NodeStack;
2439 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2440 unsigned NumRecordedNodes;
2442 /// NumMatchedMemRefs - The number of matched memref entries.
2443 unsigned NumMatchedMemRefs;
2445 /// InputChain/InputGlue - The current chain/glue
2446 SDValue InputChain, InputGlue;
2448 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2449 bool HasChainNodesMatched, HasGlueResultNodesMatched;
2452 /// \\brief A DAG update listener to keep the matching state
2453 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2454 /// change the DAG while matching. X86 addressing mode matcher is an example
2456 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2458 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes;
2459 SmallVectorImpl<MatchScope> &MatchScopes;
2461 MatchStateUpdater(SelectionDAG &DAG,
2462 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN,
2463 SmallVectorImpl<MatchScope> &MS) :
2464 SelectionDAG::DAGUpdateListener(DAG),
2465 RecordedNodes(RN), MatchScopes(MS) { }
2467 void NodeDeleted(SDNode *N, SDNode *E) {
2468 // Some early-returns here to avoid the search if we deleted the node or
2469 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2470 // do, so it's unnecessary to update matching state at that point).
2471 // Neither of these can occur currently because we only install this
2472 // update listener during matching a complex patterns.
2473 if (!E || E->isMachineOpcode())
2475 // Performing linear search here does not matter because we almost never
2476 // run this code. You'd have to have a CSE during complex pattern
2478 for (auto &I : RecordedNodes)
2479 if (I.first.getNode() == N)
2482 for (auto &I : MatchScopes)
2483 for (auto &J : I.NodeStack)
2484 if (J.getNode() == N)
2490 SDNode *SelectionDAGISel::
2491 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2492 unsigned TableSize) {
2493 // FIXME: Should these even be selected? Handle these cases in the caller?
2494 switch (NodeToMatch->getOpcode()) {
2497 case ISD::EntryToken: // These nodes remain the same.
2498 case ISD::BasicBlock:
2500 case ISD::RegisterMask:
2501 case ISD::HANDLENODE:
2502 case ISD::MDNODE_SDNODE:
2503 case ISD::TargetConstant:
2504 case ISD::TargetConstantFP:
2505 case ISD::TargetConstantPool:
2506 case ISD::TargetFrameIndex:
2507 case ISD::TargetExternalSymbol:
2508 case ISD::TargetBlockAddress:
2509 case ISD::TargetJumpTable:
2510 case ISD::TargetGlobalTLSAddress:
2511 case ISD::TargetGlobalAddress:
2512 case ISD::TokenFactor:
2513 case ISD::CopyFromReg:
2514 case ISD::CopyToReg:
2516 case ISD::LIFETIME_START:
2517 case ISD::LIFETIME_END:
2518 NodeToMatch->setNodeId(-1); // Mark selected.
2520 case ISD::AssertSext:
2521 case ISD::AssertZext:
2522 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2523 NodeToMatch->getOperand(0));
2525 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2526 case ISD::READ_REGISTER: return Select_READ_REGISTER(NodeToMatch);
2527 case ISD::WRITE_REGISTER: return Select_WRITE_REGISTER(NodeToMatch);
2528 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2531 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2533 // Set up the node stack with NodeToMatch as the only node on the stack.
2534 SmallVector<SDValue, 8> NodeStack;
2535 SDValue N = SDValue(NodeToMatch, 0);
2536 NodeStack.push_back(N);
2538 // MatchScopes - Scopes used when matching, if a match failure happens, this
2539 // indicates where to continue checking.
2540 SmallVector<MatchScope, 8> MatchScopes;
2542 // RecordedNodes - This is the set of nodes that have been recorded by the
2543 // state machine. The second value is the parent of the node, or null if the
2544 // root is recorded.
2545 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2547 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2549 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2551 // These are the current input chain and glue for use when generating nodes.
2552 // Various Emit operations change these. For example, emitting a copytoreg
2553 // uses and updates these.
2554 SDValue InputChain, InputGlue;
2556 // ChainNodesMatched - If a pattern matches nodes that have input/output
2557 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2558 // which ones they are. The result is captured into this list so that we can
2559 // update the chain results when the pattern is complete.
2560 SmallVector<SDNode*, 3> ChainNodesMatched;
2561 SmallVector<SDNode*, 3> GlueResultNodesMatched;
2563 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2564 NodeToMatch->dump(CurDAG);
2567 // Determine where to start the interpreter. Normally we start at opcode #0,
2568 // but if the state machine starts with an OPC_SwitchOpcode, then we
2569 // accelerate the first lookup (which is guaranteed to be hot) with the
2570 // OpcodeOffset table.
2571 unsigned MatcherIndex = 0;
2573 if (!OpcodeOffset.empty()) {
2574 // Already computed the OpcodeOffset table, just index into it.
2575 if (N.getOpcode() < OpcodeOffset.size())
2576 MatcherIndex = OpcodeOffset[N.getOpcode()];
2577 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2579 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2580 // Otherwise, the table isn't computed, but the state machine does start
2581 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2582 // is the first time we're selecting an instruction.
2585 // Get the size of this case.
2586 unsigned CaseSize = MatcherTable[Idx++];
2588 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2589 if (CaseSize == 0) break;
2591 // Get the opcode, add the index to the table.
2592 uint16_t Opc = MatcherTable[Idx++];
2593 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2594 if (Opc >= OpcodeOffset.size())
2595 OpcodeOffset.resize((Opc+1)*2);
2596 OpcodeOffset[Opc] = Idx;
2600 // Okay, do the lookup for the first opcode.
2601 if (N.getOpcode() < OpcodeOffset.size())
2602 MatcherIndex = OpcodeOffset[N.getOpcode()];
2606 assert(MatcherIndex < TableSize && "Invalid index");
2608 unsigned CurrentOpcodeIndex = MatcherIndex;
2610 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2613 // Okay, the semantics of this operation are that we should push a scope
2614 // then evaluate the first child. However, pushing a scope only to have
2615 // the first check fail (which then pops it) is inefficient. If we can
2616 // determine immediately that the first check (or first several) will
2617 // immediately fail, don't even bother pushing a scope for them.
2621 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2622 if (NumToSkip & 128)
2623 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2624 // Found the end of the scope with no match.
2625 if (NumToSkip == 0) {
2630 FailIndex = MatcherIndex+NumToSkip;
2632 unsigned MatcherIndexOfPredicate = MatcherIndex;
2633 (void)MatcherIndexOfPredicate; // silence warning.
2635 // If we can't evaluate this predicate without pushing a scope (e.g. if
2636 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2637 // push the scope and evaluate the full predicate chain.
2639 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2640 Result, *this, RecordedNodes);
2644 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
2645 << "index " << MatcherIndexOfPredicate
2646 << ", continuing at " << FailIndex << "\n");
2647 ++NumDAGIselRetries;
2649 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2650 // move to the next case.
2651 MatcherIndex = FailIndex;
2654 // If the whole scope failed to match, bail.
2655 if (FailIndex == 0) break;
2657 // Push a MatchScope which indicates where to go if the first child fails
2659 MatchScope NewEntry;
2660 NewEntry.FailIndex = FailIndex;
2661 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2662 NewEntry.NumRecordedNodes = RecordedNodes.size();
2663 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2664 NewEntry.InputChain = InputChain;
2665 NewEntry.InputGlue = InputGlue;
2666 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2667 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2668 MatchScopes.push_back(NewEntry);
2671 case OPC_RecordNode: {
2672 // Remember this node, it may end up being an operand in the pattern.
2673 SDNode *Parent = nullptr;
2674 if (NodeStack.size() > 1)
2675 Parent = NodeStack[NodeStack.size()-2].getNode();
2676 RecordedNodes.push_back(std::make_pair(N, Parent));
2680 case OPC_RecordChild0: case OPC_RecordChild1:
2681 case OPC_RecordChild2: case OPC_RecordChild3:
2682 case OPC_RecordChild4: case OPC_RecordChild5:
2683 case OPC_RecordChild6: case OPC_RecordChild7: {
2684 unsigned ChildNo = Opcode-OPC_RecordChild0;
2685 if (ChildNo >= N.getNumOperands())
2686 break; // Match fails if out of range child #.
2688 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2692 case OPC_RecordMemRef:
2693 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2696 case OPC_CaptureGlueInput:
2697 // If the current node has an input glue, capture it in InputGlue.
2698 if (N->getNumOperands() != 0 &&
2699 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2700 InputGlue = N->getOperand(N->getNumOperands()-1);
2703 case OPC_MoveChild: {
2704 unsigned ChildNo = MatcherTable[MatcherIndex++];
2705 if (ChildNo >= N.getNumOperands())
2706 break; // Match fails if out of range child #.
2707 N = N.getOperand(ChildNo);
2708 NodeStack.push_back(N);
2712 case OPC_MoveParent:
2713 // Pop the current node off the NodeStack.
2714 NodeStack.pop_back();
2715 assert(!NodeStack.empty() && "Node stack imbalance!");
2716 N = NodeStack.back();
2720 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2723 case OPC_CheckChild0Same: case OPC_CheckChild1Same:
2724 case OPC_CheckChild2Same: case OPC_CheckChild3Same:
2725 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
2726 Opcode-OPC_CheckChild0Same))
2730 case OPC_CheckPatternPredicate:
2731 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2733 case OPC_CheckPredicate:
2734 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2738 case OPC_CheckComplexPat: {
2739 unsigned CPNum = MatcherTable[MatcherIndex++];
2740 unsigned RecNo = MatcherTable[MatcherIndex++];
2741 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2743 // If target can modify DAG during matching, keep the matching state
2745 std::unique_ptr<MatchStateUpdater> MSU;
2746 if (ComplexPatternFuncMutatesDAG())
2747 MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes,
2750 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2751 RecordedNodes[RecNo].first, CPNum,
2756 case OPC_CheckOpcode:
2757 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2761 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI))
2765 case OPC_SwitchOpcode: {
2766 unsigned CurNodeOpcode = N.getOpcode();
2767 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2770 // Get the size of this case.
2771 CaseSize = MatcherTable[MatcherIndex++];
2773 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2774 if (CaseSize == 0) break;
2776 uint16_t Opc = MatcherTable[MatcherIndex++];
2777 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2779 // If the opcode matches, then we will execute this case.
2780 if (CurNodeOpcode == Opc)
2783 // Otherwise, skip over this case.
2784 MatcherIndex += CaseSize;
2787 // If no cases matched, bail out.
2788 if (CaseSize == 0) break;
2790 // Otherwise, execute the case we found.
2791 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
2792 << " to " << MatcherIndex << "\n");
2796 case OPC_SwitchType: {
2797 MVT CurNodeVT = N.getSimpleValueType();
2798 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2801 // Get the size of this case.
2802 CaseSize = MatcherTable[MatcherIndex++];
2804 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2805 if (CaseSize == 0) break;
2807 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2808 if (CaseVT == MVT::iPTR)
2809 CaseVT = TLI->getPointerTy();
2811 // If the VT matches, then we will execute this case.
2812 if (CurNodeVT == CaseVT)
2815 // Otherwise, skip over this case.
2816 MatcherIndex += CaseSize;
2819 // If no cases matched, bail out.
2820 if (CaseSize == 0) break;
2822 // Otherwise, execute the case we found.
2823 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2824 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2827 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2828 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2829 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2830 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2831 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2832 Opcode-OPC_CheckChild0Type))
2835 case OPC_CheckCondCode:
2836 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2838 case OPC_CheckValueType:
2839 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI))
2842 case OPC_CheckInteger:
2843 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2845 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
2846 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
2847 case OPC_CheckChild4Integer:
2848 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
2849 Opcode-OPC_CheckChild0Integer)) break;
2851 case OPC_CheckAndImm:
2852 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2854 case OPC_CheckOrImm:
2855 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2858 case OPC_CheckFoldableChainNode: {
2859 assert(NodeStack.size() != 1 && "No parent node");
2860 // Verify that all intermediate nodes between the root and this one have
2862 bool HasMultipleUses = false;
2863 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2864 if (!NodeStack[i].hasOneUse()) {
2865 HasMultipleUses = true;
2868 if (HasMultipleUses) break;
2870 // Check to see that the target thinks this is profitable to fold and that
2871 // we can fold it without inducing cycles in the graph.
2872 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2874 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2875 NodeToMatch, OptLevel,
2876 true/*We validate our own chains*/))
2881 case OPC_EmitInteger: {
2882 MVT::SimpleValueType VT =
2883 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2884 int64_t Val = MatcherTable[MatcherIndex++];
2886 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2887 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2888 CurDAG->getTargetConstant(Val, VT), nullptr));
2891 case OPC_EmitRegister: {
2892 MVT::SimpleValueType VT =
2893 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2894 unsigned RegNo = MatcherTable[MatcherIndex++];
2895 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2896 CurDAG->getRegister(RegNo, VT), nullptr));
2899 case OPC_EmitRegister2: {
2900 // For targets w/ more than 256 register names, the register enum
2901 // values are stored in two bytes in the matcher table (just like
2903 MVT::SimpleValueType VT =
2904 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2905 unsigned RegNo = MatcherTable[MatcherIndex++];
2906 RegNo |= MatcherTable[MatcherIndex++] << 8;
2907 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2908 CurDAG->getRegister(RegNo, VT), nullptr));
2912 case OPC_EmitConvertToTarget: {
2913 // Convert from IMM/FPIMM to target version.
2914 unsigned RecNo = MatcherTable[MatcherIndex++];
2915 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
2916 SDValue Imm = RecordedNodes[RecNo].first;
2918 if (Imm->getOpcode() == ISD::Constant) {
2919 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
2920 Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
2921 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2922 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2923 Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
2926 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
2930 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2931 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2932 // These are space-optimized forms of OPC_EmitMergeInputChains.
2933 assert(!InputChain.getNode() &&
2934 "EmitMergeInputChains should be the first chain producing node");
2935 assert(ChainNodesMatched.empty() &&
2936 "Should only have one EmitMergeInputChains per match");
2938 // Read all of the chained nodes.
2939 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2940 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
2941 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2943 // FIXME: What if other value results of the node have uses not matched
2945 if (ChainNodesMatched.back() != NodeToMatch &&
2946 !RecordedNodes[RecNo].first.hasOneUse()) {
2947 ChainNodesMatched.clear();
2951 // Merge the input chains if they are not intra-pattern references.
2952 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2954 if (!InputChain.getNode())
2955 break; // Failed to merge.
2959 case OPC_EmitMergeInputChains: {
2960 assert(!InputChain.getNode() &&
2961 "EmitMergeInputChains should be the first chain producing node");
2962 // This node gets a list of nodes we matched in the input that have
2963 // chains. We want to token factor all of the input chains to these nodes
2964 // together. However, if any of the input chains is actually one of the
2965 // nodes matched in this pattern, then we have an intra-match reference.
2966 // Ignore these because the newly token factored chain should not refer to
2968 unsigned NumChains = MatcherTable[MatcherIndex++];
2969 assert(NumChains != 0 && "Can't TF zero chains");
2971 assert(ChainNodesMatched.empty() &&
2972 "Should only have one EmitMergeInputChains per match");
2974 // Read all of the chained nodes.
2975 for (unsigned i = 0; i != NumChains; ++i) {
2976 unsigned RecNo = MatcherTable[MatcherIndex++];
2977 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
2978 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2980 // FIXME: What if other value results of the node have uses not matched
2982 if (ChainNodesMatched.back() != NodeToMatch &&
2983 !RecordedNodes[RecNo].first.hasOneUse()) {
2984 ChainNodesMatched.clear();
2989 // If the inner loop broke out, the match fails.
2990 if (ChainNodesMatched.empty())
2993 // Merge the input chains if they are not intra-pattern references.
2994 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2996 if (!InputChain.getNode())
2997 break; // Failed to merge.
3002 case OPC_EmitCopyToReg: {
3003 unsigned RecNo = MatcherTable[MatcherIndex++];
3004 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3005 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3007 if (!InputChain.getNode())
3008 InputChain = CurDAG->getEntryNode();
3010 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3011 DestPhysReg, RecordedNodes[RecNo].first,
3014 InputGlue = InputChain.getValue(1);
3018 case OPC_EmitNodeXForm: {
3019 unsigned XFormNo = MatcherTable[MatcherIndex++];
3020 unsigned RecNo = MatcherTable[MatcherIndex++];
3021 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3022 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3023 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3028 case OPC_MorphNodeTo: {
3029 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3030 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3031 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3032 // Get the result VT list.
3033 unsigned NumVTs = MatcherTable[MatcherIndex++];
3034 SmallVector<EVT, 4> VTs;
3035 for (unsigned i = 0; i != NumVTs; ++i) {
3036 MVT::SimpleValueType VT =
3037 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3038 if (VT == MVT::iPTR)
3039 VT = TLI->getPointerTy().SimpleTy;
3043 if (EmitNodeInfo & OPFL_Chain)
3044 VTs.push_back(MVT::Other);
3045 if (EmitNodeInfo & OPFL_GlueOutput)
3046 VTs.push_back(MVT::Glue);
3048 // This is hot code, so optimize the two most common cases of 1 and 2
3051 if (VTs.size() == 1)
3052 VTList = CurDAG->getVTList(VTs[0]);
3053 else if (VTs.size() == 2)
3054 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3056 VTList = CurDAG->getVTList(VTs);
3058 // Get the operand list.
3059 unsigned NumOps = MatcherTable[MatcherIndex++];
3060 SmallVector<SDValue, 8> Ops;
3061 for (unsigned i = 0; i != NumOps; ++i) {
3062 unsigned RecNo = MatcherTable[MatcherIndex++];
3064 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3066 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3067 Ops.push_back(RecordedNodes[RecNo].first);
3070 // If there are variadic operands to add, handle them now.
3071 if (EmitNodeInfo & OPFL_VariadicInfo) {
3072 // Determine the start index to copy from.
3073 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3074 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3075 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3076 "Invalid variadic node");
3077 // Copy all of the variadic operands, not including a potential glue
3079 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3081 SDValue V = NodeToMatch->getOperand(i);
3082 if (V.getValueType() == MVT::Glue) break;
3087 // If this has chain/glue inputs, add them.
3088 if (EmitNodeInfo & OPFL_Chain)
3089 Ops.push_back(InputChain);
3090 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3091 Ops.push_back(InputGlue);
3094 SDNode *Res = nullptr;
3095 if (Opcode != OPC_MorphNodeTo) {
3096 // If this is a normal EmitNode command, just create the new node and
3097 // add the results to the RecordedNodes list.
3098 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3101 // Add all the non-glue/non-chain results to the RecordedNodes list.
3102 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3103 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3104 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3108 } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
3109 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
3111 // NodeToMatch was eliminated by CSE when the target changed the DAG.
3112 // We will visit the equivalent node later.
3113 DEBUG(dbgs() << "Node was eliminated by CSE\n");
3117 // If the node had chain/glue results, update our notion of the current
3119 if (EmitNodeInfo & OPFL_GlueOutput) {
3120 InputGlue = SDValue(Res, VTs.size()-1);
3121 if (EmitNodeInfo & OPFL_Chain)
3122 InputChain = SDValue(Res, VTs.size()-2);
3123 } else if (EmitNodeInfo & OPFL_Chain)
3124 InputChain = SDValue(Res, VTs.size()-1);
3126 // If the OPFL_MemRefs glue is set on this node, slap all of the
3127 // accumulated memrefs onto it.
3129 // FIXME: This is vastly incorrect for patterns with multiple outputs
3130 // instructions that access memory and for ComplexPatterns that match
3132 if (EmitNodeInfo & OPFL_MemRefs) {
3133 // Only attach load or store memory operands if the generated
3134 // instruction may load or store.
3135 const MCInstrDesc &MCID = TII->get(TargetOpc);
3136 bool mayLoad = MCID.mayLoad();
3137 bool mayStore = MCID.mayStore();
3139 unsigned NumMemRefs = 0;
3140 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3141 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3142 if ((*I)->isLoad()) {
3145 } else if ((*I)->isStore()) {
3153 MachineSDNode::mmo_iterator MemRefs =
3154 MF->allocateMemRefsArray(NumMemRefs);
3156 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
3157 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3158 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3159 if ((*I)->isLoad()) {
3162 } else if ((*I)->isStore()) {
3170 cast<MachineSDNode>(Res)
3171 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
3175 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
3176 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
3178 // If this was a MorphNodeTo then we're completely done!
3179 if (Opcode == OPC_MorphNodeTo) {
3180 // Update chain and glue uses.
3181 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
3182 InputGlue, GlueResultNodesMatched, true);
3189 case OPC_MarkGlueResults: {
3190 unsigned NumNodes = MatcherTable[MatcherIndex++];
3192 // Read and remember all the glue-result nodes.
3193 for (unsigned i = 0; i != NumNodes; ++i) {
3194 unsigned RecNo = MatcherTable[MatcherIndex++];
3196 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3198 assert(RecNo < RecordedNodes.size() && "Invalid MarkGlueResults");
3199 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3204 case OPC_CompleteMatch: {
3205 // The match has been completed, and any new nodes (if any) have been
3206 // created. Patch up references to the matched dag to use the newly
3208 unsigned NumResults = MatcherTable[MatcherIndex++];
3210 for (unsigned i = 0; i != NumResults; ++i) {
3211 unsigned ResSlot = MatcherTable[MatcherIndex++];
3213 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3215 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3216 SDValue Res = RecordedNodes[ResSlot].first;
3218 assert(i < NodeToMatch->getNumValues() &&
3219 NodeToMatch->getValueType(i) != MVT::Other &&
3220 NodeToMatch->getValueType(i) != MVT::Glue &&
3221 "Invalid number of results to complete!");
3222 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3223 NodeToMatch->getValueType(i) == MVT::iPTR ||
3224 Res.getValueType() == MVT::iPTR ||
3225 NodeToMatch->getValueType(i).getSizeInBits() ==
3226 Res.getValueType().getSizeInBits()) &&
3227 "invalid replacement");
3228 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
3231 // If the root node defines glue, add it to the glue nodes to update list.
3232 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
3233 GlueResultNodesMatched.push_back(NodeToMatch);
3235 // Update chain and glue uses.
3236 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
3237 InputGlue, GlueResultNodesMatched, false);
3239 assert(NodeToMatch->use_empty() &&
3240 "Didn't replace all uses of the node?");
3242 // FIXME: We just return here, which interacts correctly with SelectRoot
3243 // above. We should fix this to not return an SDNode* anymore.
3248 // If the code reached this point, then the match failed. See if there is
3249 // another child to try in the current 'Scope', otherwise pop it until we
3250 // find a case to check.
3251 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
3252 ++NumDAGIselRetries;
3254 if (MatchScopes.empty()) {
3255 CannotYetSelect(NodeToMatch);
3259 // Restore the interpreter state back to the point where the scope was
3261 MatchScope &LastScope = MatchScopes.back();
3262 RecordedNodes.resize(LastScope.NumRecordedNodes);
3264 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3265 N = NodeStack.back();
3267 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3268 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3269 MatcherIndex = LastScope.FailIndex;
3271 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3273 InputChain = LastScope.InputChain;
3274 InputGlue = LastScope.InputGlue;
3275 if (!LastScope.HasChainNodesMatched)
3276 ChainNodesMatched.clear();
3277 if (!LastScope.HasGlueResultNodesMatched)
3278 GlueResultNodesMatched.clear();
3280 // Check to see what the offset is at the new MatcherIndex. If it is zero
3281 // we have reached the end of this scope, otherwise we have another child
3282 // in the current scope to try.
3283 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3284 if (NumToSkip & 128)
3285 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3287 // If we have another child in this scope to match, update FailIndex and
3289 if (NumToSkip != 0) {
3290 LastScope.FailIndex = MatcherIndex+NumToSkip;
3294 // End of this scope, pop it and try the next child in the containing
3296 MatchScopes.pop_back();
3303 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3305 raw_string_ostream Msg(msg);
3306 Msg << "Cannot select: ";
3308 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3309 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3310 N->getOpcode() != ISD::INTRINSIC_VOID) {
3311 N->printrFull(Msg, CurDAG);
3312 Msg << "\nIn function: " << MF->getName();
3314 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3316 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3317 if (iid < Intrinsic::num_intrinsics)
3318 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
3319 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3320 Msg << "target intrinsic %" << TII->getName(iid);
3322 Msg << "unknown intrinsic #" << iid;
3324 report_fatal_error(Msg.str());
3327 char SelectionDAGISel::ID = 0;