1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/SelectionDAG.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/Analysis/EHPersonalities.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
35 #include "llvm/CodeGen/SchedulerRegistry.h"
36 #include "llvm/CodeGen/SelectionDAGISel.h"
37 #include "llvm/CodeGen/StackProtector.h"
38 #include "llvm/CodeGen/WinEHFuncInfo.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/InlineAsm.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/MC/MCAsmInfo.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/Timer.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetIntrinsicInfo.h"
56 #include "llvm/Target/TargetLowering.h"
57 #include "llvm/Target/TargetMachine.h"
58 #include "llvm/Target/TargetOptions.h"
59 #include "llvm/Target/TargetRegisterInfo.h"
60 #include "llvm/Target/TargetSubtargetInfo.h"
61 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
62 #include <algorithm>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "isel"
67 
68 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
69 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
70 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
71 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
72 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
73 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
74 STATISTIC(NumFastIselFailLowerArguments,
75           "Number of entry blocks where fast isel failed to lower arguments");
76 
77 #ifndef NDEBUG
78 static cl::opt<bool>
79 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
80           cl::desc("Enable extra verbose messages in the \"fast\" "
81                    "instruction selector"));
82 
83   // Terminators
84 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
85 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
86 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
87 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
88 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
89 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
90 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
91 
92   // Standard binary operators...
93 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
94 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
95 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
96 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
97 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
98 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
99 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
100 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
101 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
102 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
103 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
104 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
105 
106   // Logical operators...
107 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
108 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
109 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
110 
111   // Memory instructions...
112 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
113 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
114 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
115 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
116 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
117 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
118 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
119 
120   // Convert instructions...
121 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
122 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
123 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
124 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
125 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
126 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
127 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
128 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
129 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
130 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
131 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
132 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
133 
134   // Other instructions...
135 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
136 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
137 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
138 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
139 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
140 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
141 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
142 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
143 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
144 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
145 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
146 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
147 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
148 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
149 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
150 
151 // Intrinsic instructions...
152 STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call");
153 STATISTIC(NumFastIselFailSAddWithOverflow,
154           "Fast isel fails on sadd.with.overflow");
155 STATISTIC(NumFastIselFailUAddWithOverflow,
156           "Fast isel fails on uadd.with.overflow");
157 STATISTIC(NumFastIselFailSSubWithOverflow,
158           "Fast isel fails on ssub.with.overflow");
159 STATISTIC(NumFastIselFailUSubWithOverflow,
160           "Fast isel fails on usub.with.overflow");
161 STATISTIC(NumFastIselFailSMulWithOverflow,
162           "Fast isel fails on smul.with.overflow");
163 STATISTIC(NumFastIselFailUMulWithOverflow,
164           "Fast isel fails on umul.with.overflow");
165 STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress");
166 STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call");
167 STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call");
168 STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call");
169 #endif
170 
171 static cl::opt<bool>
172 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
173           cl::desc("Enable verbose messages in the \"fast\" "
174                    "instruction selector"));
175 static cl::opt<int> EnableFastISelAbort(
176     "fast-isel-abort", cl::Hidden,
177     cl::desc("Enable abort calls when \"fast\" instruction selection "
178              "fails to lower an instruction: 0 disable the abort, 1 will "
179              "abort but for args, calls and terminators, 2 will also "
180              "abort for argument lowering, and 3 will never fallback "
181              "to SelectionDAG."));
182 
183 static cl::opt<bool>
184 UseMBPI("use-mbpi",
185         cl::desc("use Machine Branch Probability Info"),
186         cl::init(true), cl::Hidden);
187 
188 #ifndef NDEBUG
189 static cl::opt<std::string>
190 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
191                         cl::desc("Only display the basic block whose name "
192                                  "matches this for all view-*-dags options"));
193 static cl::opt<bool>
194 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
195           cl::desc("Pop up a window to show dags before the first "
196                    "dag combine pass"));
197 static cl::opt<bool>
198 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
199           cl::desc("Pop up a window to show dags before legalize types"));
200 static cl::opt<bool>
201 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
202           cl::desc("Pop up a window to show dags before legalize"));
203 static cl::opt<bool>
204 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
205           cl::desc("Pop up a window to show dags before the second "
206                    "dag combine pass"));
207 static cl::opt<bool>
208 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
209           cl::desc("Pop up a window to show dags before the post legalize types"
210                    " dag combine pass"));
211 static cl::opt<bool>
212 ViewISelDAGs("view-isel-dags", cl::Hidden,
213           cl::desc("Pop up a window to show isel dags as they are selected"));
214 static cl::opt<bool>
215 ViewSchedDAGs("view-sched-dags", cl::Hidden,
216           cl::desc("Pop up a window to show sched dags as they are processed"));
217 static cl::opt<bool>
218 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
219       cl::desc("Pop up a window to show SUnit dags after they are processed"));
220 #else
221 static const bool ViewDAGCombine1 = false,
222                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
223                   ViewDAGCombine2 = false,
224                   ViewDAGCombineLT = false,
225                   ViewISelDAGs = false, ViewSchedDAGs = false,
226                   ViewSUnitDAGs = false;
227 #endif
228 
229 //===---------------------------------------------------------------------===//
230 ///
231 /// RegisterScheduler class - Track the registration of instruction schedulers.
232 ///
233 //===---------------------------------------------------------------------===//
234 MachinePassRegistry RegisterScheduler::Registry;
235 
236 //===---------------------------------------------------------------------===//
237 ///
238 /// ISHeuristic command line option for instruction schedulers.
239 ///
240 //===---------------------------------------------------------------------===//
241 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
242                RegisterPassParser<RegisterScheduler> >
243 ISHeuristic("pre-RA-sched",
244             cl::init(&createDefaultScheduler), cl::Hidden,
245             cl::desc("Instruction schedulers available (before register"
246                      " allocation):"));
247 
248 static RegisterScheduler
249 defaultListDAGScheduler("default", "Best scheduler for the target",
250                         createDefaultScheduler);
251 
252 namespace llvm {
253   //===--------------------------------------------------------------------===//
254   /// \brief This class is used by SelectionDAGISel to temporarily override
255   /// the optimization level on a per-function basis.
256   class OptLevelChanger {
257     SelectionDAGISel &IS;
258     CodeGenOpt::Level SavedOptLevel;
259     bool SavedFastISel;
260 
261   public:
262     OptLevelChanger(SelectionDAGISel &ISel,
263                     CodeGenOpt::Level NewOptLevel) : IS(ISel) {
264       SavedOptLevel = IS.OptLevel;
265       if (NewOptLevel == SavedOptLevel)
266         return;
267       IS.OptLevel = NewOptLevel;
268       IS.TM.setOptLevel(NewOptLevel);
269       DEBUG(dbgs() << "\nChanging optimization level for Function "
270             << IS.MF->getFunction()->getName() << "\n");
271       DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
272             << " ; After: -O" << NewOptLevel << "\n");
273       SavedFastISel = IS.TM.Options.EnableFastISel;
274       if (NewOptLevel == CodeGenOpt::None) {
275         IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
276         DEBUG(dbgs() << "\tFastISel is "
277               << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
278               << "\n");
279       }
280     }
281 
282     ~OptLevelChanger() {
283       if (IS.OptLevel == SavedOptLevel)
284         return;
285       DEBUG(dbgs() << "\nRestoring optimization level for Function "
286             << IS.MF->getFunction()->getName() << "\n");
287       DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
288             << " ; After: -O" << SavedOptLevel << "\n");
289       IS.OptLevel = SavedOptLevel;
290       IS.TM.setOptLevel(SavedOptLevel);
291       IS.TM.setFastISel(SavedFastISel);
292     }
293   };
294 
295   //===--------------------------------------------------------------------===//
296   /// createDefaultScheduler - This creates an instruction scheduler appropriate
297   /// for the target.
298   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
299                                              CodeGenOpt::Level OptLevel) {
300     const TargetLowering *TLI = IS->TLI;
301     const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
302 
303     // Try first to see if the Target has its own way of selecting a scheduler
304     if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
305       return SchedulerCtor(IS, OptLevel);
306     }
307 
308     if (OptLevel == CodeGenOpt::None ||
309         (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
310         TLI->getSchedulingPreference() == Sched::Source)
311       return createSourceListDAGScheduler(IS, OptLevel);
312     if (TLI->getSchedulingPreference() == Sched::RegPressure)
313       return createBURRListDAGScheduler(IS, OptLevel);
314     if (TLI->getSchedulingPreference() == Sched::Hybrid)
315       return createHybridListDAGScheduler(IS, OptLevel);
316     if (TLI->getSchedulingPreference() == Sched::VLIW)
317       return createVLIWDAGScheduler(IS, OptLevel);
318     assert(TLI->getSchedulingPreference() == Sched::ILP &&
319            "Unknown sched type!");
320     return createILPListDAGScheduler(IS, OptLevel);
321   }
322 } // end namespace llvm
323 
324 // EmitInstrWithCustomInserter - This method should be implemented by targets
325 // that mark instructions with the 'usesCustomInserter' flag.  These
326 // instructions are special in various ways, which require special support to
327 // insert.  The specified MachineInstr is created but not inserted into any
328 // basic blocks, and this method is called to expand it into a sequence of
329 // instructions, potentially also creating new basic blocks and control flow.
330 // When new basic blocks are inserted and the edges from MBB to its successors
331 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
332 // DenseMap.
333 MachineBasicBlock *
334 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
335                                             MachineBasicBlock *MBB) const {
336 #ifndef NDEBUG
337   dbgs() << "If a target marks an instruction with "
338           "'usesCustomInserter', it must implement "
339           "TargetLowering::EmitInstrWithCustomInserter!";
340 #endif
341   llvm_unreachable(nullptr);
342 }
343 
344 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
345                                                    SDNode *Node) const {
346   assert(!MI->hasPostISelHook() &&
347          "If a target marks an instruction with 'hasPostISelHook', "
348          "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
349 }
350 
351 //===----------------------------------------------------------------------===//
352 // SelectionDAGISel code
353 //===----------------------------------------------------------------------===//
354 
355 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
356                                    CodeGenOpt::Level OL) :
357   MachineFunctionPass(ID), TM(tm),
358   FuncInfo(new FunctionLoweringInfo()),
359   CurDAG(new SelectionDAG(tm, OL)),
360   SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
361   GFI(),
362   OptLevel(OL),
363   DAGSize(0) {
364     initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
365     initializeBranchProbabilityInfoWrapperPassPass(
366         *PassRegistry::getPassRegistry());
367     initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
368     initializeTargetLibraryInfoWrapperPassPass(
369         *PassRegistry::getPassRegistry());
370   }
371 
372 SelectionDAGISel::~SelectionDAGISel() {
373   delete SDB;
374   delete CurDAG;
375   delete FuncInfo;
376 }
377 
378 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
379   AU.addRequired<AAResultsWrapperPass>();
380   AU.addRequired<GCModuleInfo>();
381   AU.addRequired<StackProtector>();
382   AU.addPreserved<StackProtector>();
383   AU.addPreserved<GCModuleInfo>();
384   AU.addRequired<TargetLibraryInfoWrapperPass>();
385   if (UseMBPI && OptLevel != CodeGenOpt::None)
386     AU.addRequired<BranchProbabilityInfoWrapperPass>();
387   MachineFunctionPass::getAnalysisUsage(AU);
388 }
389 
390 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
391 /// may trap on it.  In this case we have to split the edge so that the path
392 /// through the predecessor block that doesn't go to the phi block doesn't
393 /// execute the possibly trapping instruction.
394 ///
395 /// This is required for correctness, so it must be done at -O0.
396 ///
397 static void SplitCriticalSideEffectEdges(Function &Fn) {
398   // Loop for blocks with phi nodes.
399   for (BasicBlock &BB : Fn) {
400     PHINode *PN = dyn_cast<PHINode>(BB.begin());
401     if (!PN) continue;
402 
403   ReprocessBlock:
404     // For each block with a PHI node, check to see if any of the input values
405     // are potentially trapping constant expressions.  Constant expressions are
406     // the only potentially trapping value that can occur as the argument to a
407     // PHI.
408     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
409       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
410         ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
411         if (!CE || !CE->canTrap()) continue;
412 
413         // The only case we have to worry about is when the edge is critical.
414         // Since this block has a PHI Node, we assume it has multiple input
415         // edges: check to see if the pred has multiple successors.
416         BasicBlock *Pred = PN->getIncomingBlock(i);
417         if (Pred->getTerminator()->getNumSuccessors() == 1)
418           continue;
419 
420         // Okay, we have to split this edge.
421         SplitCriticalEdge(
422             Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
423             CriticalEdgeSplittingOptions().setMergeIdenticalEdges());
424         goto ReprocessBlock;
425       }
426   }
427 }
428 
429 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
430   // Do some sanity-checking on the command-line options.
431   assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
432          "-fast-isel-verbose requires -fast-isel");
433   assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
434          "-fast-isel-abort > 0 requires -fast-isel");
435 
436   const Function &Fn = *mf.getFunction();
437   MF = &mf;
438 
439   // Reset the target options before resetting the optimization
440   // level below.
441   // FIXME: This is a horrible hack and should be processed via
442   // codegen looking at the optimization level explicitly when
443   // it wants to look at it.
444   TM.resetTargetOptions(Fn);
445   // Reset OptLevel to None for optnone functions.
446   CodeGenOpt::Level NewOptLevel = OptLevel;
447   if (Fn.hasFnAttribute(Attribute::OptimizeNone))
448     NewOptLevel = CodeGenOpt::None;
449   OptLevelChanger OLC(*this, NewOptLevel);
450 
451   TII = MF->getSubtarget().getInstrInfo();
452   TLI = MF->getSubtarget().getTargetLowering();
453   RegInfo = &MF->getRegInfo();
454   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
455   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
456   GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
457 
458   DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
459 
460   SplitCriticalSideEffectEdges(const_cast<Function &>(Fn));
461 
462   CurDAG->init(*MF);
463   FuncInfo->set(Fn, *MF, CurDAG);
464 
465   if (UseMBPI && OptLevel != CodeGenOpt::None)
466     FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
467   else
468     FuncInfo->BPI = nullptr;
469 
470   SDB->init(GFI, *AA, LibInfo);
471 
472   MF->setHasInlineAsm(false);
473 
474   FuncInfo->SplitCSR = false;
475 
476   // We split CSR if the target supports it for the given function
477   // and the function has only return exits.
478   if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
479     FuncInfo->SplitCSR = true;
480 
481     // Collect all the return blocks.
482     for (const BasicBlock &BB : Fn) {
483       if (!succ_empty(&BB))
484         continue;
485 
486       const TerminatorInst *Term = BB.getTerminator();
487       if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
488         continue;
489 
490       // Bail out if the exit block is not Return nor Unreachable.
491       FuncInfo->SplitCSR = false;
492       break;
493     }
494   }
495 
496   MachineBasicBlock *EntryMBB = &MF->front();
497   if (FuncInfo->SplitCSR)
498     // This performs initialization so lowering for SplitCSR will be correct.
499     TLI->initializeSplitCSR(EntryMBB);
500 
501   SelectAllBasicBlocks(Fn);
502 
503   // If the first basic block in the function has live ins that need to be
504   // copied into vregs, emit the copies into the top of the block before
505   // emitting the code for the block.
506   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
507   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
508 
509   // Insert copies in the entry block and the return blocks.
510   if (FuncInfo->SplitCSR) {
511     SmallVector<MachineBasicBlock*, 4> Returns;
512     // Collect all the return blocks.
513     for (MachineBasicBlock &MBB : mf) {
514       if (!MBB.succ_empty())
515         continue;
516 
517       MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
518       if (Term != MBB.end() && Term->isReturn()) {
519         Returns.push_back(&MBB);
520         continue;
521       }
522     }
523     TLI->insertCopiesSplitCSR(EntryMBB, Returns);
524   }
525 
526   DenseMap<unsigned, unsigned> LiveInMap;
527   if (!FuncInfo->ArgDbgValues.empty())
528     for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
529            E = RegInfo->livein_end(); LI != E; ++LI)
530       if (LI->second)
531         LiveInMap.insert(std::make_pair(LI->first, LI->second));
532 
533   // Insert DBG_VALUE instructions for function arguments to the entry block.
534   for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
535     MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
536     bool hasFI = MI->getOperand(0).isFI();
537     unsigned Reg =
538         hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
539     if (TargetRegisterInfo::isPhysicalRegister(Reg))
540       EntryMBB->insert(EntryMBB->begin(), MI);
541     else {
542       MachineInstr *Def = RegInfo->getVRegDef(Reg);
543       if (Def) {
544         MachineBasicBlock::iterator InsertPos = Def;
545         // FIXME: VR def may not be in entry block.
546         Def->getParent()->insert(std::next(InsertPos), MI);
547       } else
548         DEBUG(dbgs() << "Dropping debug info for dead vreg"
549               << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
550     }
551 
552     // If Reg is live-in then update debug info to track its copy in a vreg.
553     DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
554     if (LDI != LiveInMap.end()) {
555       assert(!hasFI && "There's no handling of frame pointer updating here yet "
556                        "- add if needed");
557       MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
558       MachineBasicBlock::iterator InsertPos = Def;
559       const MDNode *Variable = MI->getDebugVariable();
560       const MDNode *Expr = MI->getDebugExpression();
561       DebugLoc DL = MI->getDebugLoc();
562       bool IsIndirect = MI->isIndirectDebugValue();
563       unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
564       assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
565              "Expected inlined-at fields to agree");
566       // Def is never a terminator here, so it is ok to increment InsertPos.
567       BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
568               IsIndirect, LDI->second, Offset, Variable, Expr);
569 
570       // If this vreg is directly copied into an exported register then
571       // that COPY instructions also need DBG_VALUE, if it is the only
572       // user of LDI->second.
573       MachineInstr *CopyUseMI = nullptr;
574       for (MachineRegisterInfo::use_instr_iterator
575            UI = RegInfo->use_instr_begin(LDI->second),
576            E = RegInfo->use_instr_end(); UI != E; ) {
577         MachineInstr *UseMI = &*(UI++);
578         if (UseMI->isDebugValue()) continue;
579         if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
580           CopyUseMI = UseMI; continue;
581         }
582         // Otherwise this is another use or second copy use.
583         CopyUseMI = nullptr; break;
584       }
585       if (CopyUseMI) {
586         // Use MI's debug location, which describes where Variable was
587         // declared, rather than whatever is attached to CopyUseMI.
588         MachineInstr *NewMI =
589             BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
590                     CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
591         MachineBasicBlock::iterator Pos = CopyUseMI;
592         EntryMBB->insertAfter(Pos, NewMI);
593       }
594     }
595   }
596 
597   // Determine if there are any calls in this machine function.
598   MachineFrameInfo *MFI = MF->getFrameInfo();
599   for (const auto &MBB : *MF) {
600     if (MFI->hasCalls() && MF->hasInlineAsm())
601       break;
602 
603     for (const auto &MI : MBB) {
604       const MCInstrDesc &MCID = TII->get(MI.getOpcode());
605       if ((MCID.isCall() && !MCID.isReturn()) ||
606           MI.isStackAligningInlineAsm()) {
607         MFI->setHasCalls(true);
608       }
609       if (MI.isInlineAsm()) {
610         MF->setHasInlineAsm(true);
611       }
612     }
613   }
614 
615   // Determine if there is a call to setjmp in the machine function.
616   MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
617 
618   // Replace forward-declared registers with the registers containing
619   // the desired value.
620   MachineRegisterInfo &MRI = MF->getRegInfo();
621   for (DenseMap<unsigned, unsigned>::iterator
622        I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
623        I != E; ++I) {
624     unsigned From = I->first;
625     unsigned To = I->second;
626     // If To is also scheduled to be replaced, find what its ultimate
627     // replacement is.
628     for (;;) {
629       DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
630       if (J == E) break;
631       To = J->second;
632     }
633     // Make sure the new register has a sufficiently constrained register class.
634     if (TargetRegisterInfo::isVirtualRegister(From) &&
635         TargetRegisterInfo::isVirtualRegister(To))
636       MRI.constrainRegClass(To, MRI.getRegClass(From));
637     // Replace it.
638 
639 
640     // Replacing one register with another won't touch the kill flags.
641     // We need to conservatively clear the kill flags as a kill on the old
642     // register might dominate existing uses of the new register.
643     if (!MRI.use_empty(To))
644       MRI.clearKillFlags(From);
645     MRI.replaceRegWith(From, To);
646   }
647 
648   if (TLI->hasCopyImplyingStackAdjustment(MF))
649     MFI->setHasCopyImplyingStackAdjustment(true);
650 
651   // Freeze the set of reserved registers now that MachineFrameInfo has been
652   // set up. All the information required by getReservedRegs() should be
653   // available now.
654   MRI.freezeReservedRegs(*MF);
655 
656   // Release function-specific state. SDB and CurDAG are already cleared
657   // at this point.
658   FuncInfo->clear();
659 
660   DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
661   DEBUG(MF->print(dbgs()));
662 
663   return true;
664 }
665 
666 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
667                                         BasicBlock::const_iterator End,
668                                         bool &HadTailCall) {
669   // Lower the instructions. If a call is emitted as a tail call, cease emitting
670   // nodes for this block.
671   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
672     SDB->visit(*I);
673 
674   // Make sure the root of the DAG is up-to-date.
675   CurDAG->setRoot(SDB->getControlRoot());
676   HadTailCall = SDB->HasTailCall;
677   SDB->clear();
678 
679   // Final step, emit the lowered DAG as machine code.
680   CodeGenAndEmitDAG();
681 }
682 
683 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
684   SmallPtrSet<SDNode*, 16> VisitedNodes;
685   SmallVector<SDNode*, 128> Worklist;
686 
687   Worklist.push_back(CurDAG->getRoot().getNode());
688 
689   APInt KnownZero;
690   APInt KnownOne;
691 
692   do {
693     SDNode *N = Worklist.pop_back_val();
694 
695     // If we've already seen this node, ignore it.
696     if (!VisitedNodes.insert(N).second)
697       continue;
698 
699     // Otherwise, add all chain operands to the worklist.
700     for (const SDValue &Op : N->op_values())
701       if (Op.getValueType() == MVT::Other)
702         Worklist.push_back(Op.getNode());
703 
704     // If this is a CopyToReg with a vreg dest, process it.
705     if (N->getOpcode() != ISD::CopyToReg)
706       continue;
707 
708     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
709     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
710       continue;
711 
712     // Ignore non-scalar or non-integer values.
713     SDValue Src = N->getOperand(2);
714     EVT SrcVT = Src.getValueType();
715     if (!SrcVT.isInteger() || SrcVT.isVector())
716       continue;
717 
718     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
719     CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
720     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
721   } while (!Worklist.empty());
722 }
723 
724 void SelectionDAGISel::CodeGenAndEmitDAG() {
725   std::string GroupName;
726   if (TimePassesIsEnabled)
727     GroupName = "Instruction Selection and Scheduling";
728   std::string BlockName;
729   int BlockNumber = -1;
730   (void)BlockNumber;
731   bool MatchFilterBB = false; (void)MatchFilterBB;
732 #ifndef NDEBUG
733   MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
734                    FilterDAGBasicBlockName ==
735                        FuncInfo->MBB->getBasicBlock()->getName().str());
736 #endif
737 #ifdef NDEBUG
738   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
739       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
740       ViewSUnitDAGs)
741 #endif
742   {
743     BlockNumber = FuncInfo->MBB->getNumber();
744     BlockName =
745         (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
746   }
747   DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
748         << " '" << BlockName << "'\n"; CurDAG->dump());
749 
750   if (ViewDAGCombine1 && MatchFilterBB)
751     CurDAG->viewGraph("dag-combine1 input for " + BlockName);
752 
753   // Run the DAG combiner in pre-legalize mode.
754   {
755     NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
756     CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
757   }
758 
759   DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
760         << " '" << BlockName << "'\n"; CurDAG->dump());
761 
762   // Second step, hack on the DAG until it only uses operations and types that
763   // the target supports.
764   if (ViewLegalizeTypesDAGs && MatchFilterBB)
765     CurDAG->viewGraph("legalize-types input for " + BlockName);
766 
767   bool Changed;
768   {
769     NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
770     Changed = CurDAG->LegalizeTypes();
771   }
772 
773   DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
774         << " '" << BlockName << "'\n"; CurDAG->dump());
775 
776   CurDAG->NewNodesMustHaveLegalTypes = true;
777 
778   if (Changed) {
779     if (ViewDAGCombineLT && MatchFilterBB)
780       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
781 
782     // Run the DAG combiner in post-type-legalize mode.
783     {
784       NamedRegionTimer T("DAG Combining after legalize types", GroupName,
785                          TimePassesIsEnabled);
786       CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
787     }
788 
789     DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
790           << " '" << BlockName << "'\n"; CurDAG->dump());
791 
792   }
793 
794   {
795     NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
796     Changed = CurDAG->LegalizeVectors();
797   }
798 
799   if (Changed) {
800     {
801       NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
802       CurDAG->LegalizeTypes();
803     }
804 
805     if (ViewDAGCombineLT && MatchFilterBB)
806       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
807 
808     // Run the DAG combiner in post-type-legalize mode.
809     {
810       NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
811                          TimePassesIsEnabled);
812       CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
813     }
814 
815     DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
816           << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
817   }
818 
819   if (ViewLegalizeDAGs && MatchFilterBB)
820     CurDAG->viewGraph("legalize input for " + BlockName);
821 
822   {
823     NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
824     CurDAG->Legalize();
825   }
826 
827   DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
828         << " '" << BlockName << "'\n"; CurDAG->dump());
829 
830   if (ViewDAGCombine2 && MatchFilterBB)
831     CurDAG->viewGraph("dag-combine2 input for " + BlockName);
832 
833   // Run the DAG combiner in post-legalize mode.
834   {
835     NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
836     CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
837   }
838 
839   DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
840         << " '" << BlockName << "'\n"; CurDAG->dump());
841 
842   if (OptLevel != CodeGenOpt::None)
843     ComputeLiveOutVRegInfo();
844 
845   if (ViewISelDAGs && MatchFilterBB)
846     CurDAG->viewGraph("isel input for " + BlockName);
847 
848   // Third, instruction select all of the operations to machine code, adding the
849   // code to the MachineBasicBlock.
850   {
851     NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
852     DoInstructionSelection();
853   }
854 
855   DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
856         << " '" << BlockName << "'\n"; CurDAG->dump());
857 
858   if (ViewSchedDAGs && MatchFilterBB)
859     CurDAG->viewGraph("scheduler input for " + BlockName);
860 
861   // Schedule machine code.
862   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
863   {
864     NamedRegionTimer T("Instruction Scheduling", GroupName,
865                        TimePassesIsEnabled);
866     Scheduler->Run(CurDAG, FuncInfo->MBB);
867   }
868 
869   if (ViewSUnitDAGs && MatchFilterBB)
870     Scheduler->viewGraph();
871 
872   // Emit machine code to BB.  This can change 'BB' to the last block being
873   // inserted into.
874   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
875   {
876     NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
877 
878     // FuncInfo->InsertPt is passed by reference and set to the end of the
879     // scheduled instructions.
880     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
881   }
882 
883   // If the block was split, make sure we update any references that are used to
884   // update PHI nodes later on.
885   if (FirstMBB != LastMBB)
886     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
887 
888   // Free the scheduler state.
889   {
890     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
891                        TimePassesIsEnabled);
892     delete Scheduler;
893   }
894 
895   // Free the SelectionDAG state, now that we're finished with it.
896   CurDAG->clear();
897 }
898 
899 namespace {
900 /// ISelUpdater - helper class to handle updates of the instruction selection
901 /// graph.
902 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
903   SelectionDAG::allnodes_iterator &ISelPosition;
904 public:
905   ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
906     : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
907 
908   /// NodeDeleted - Handle nodes deleted from the graph. If the node being
909   /// deleted is the current ISelPosition node, update ISelPosition.
910   ///
911   void NodeDeleted(SDNode *N, SDNode *E) override {
912     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
913       ++ISelPosition;
914   }
915 };
916 } // end anonymous namespace
917 
918 void SelectionDAGISel::DoInstructionSelection() {
919   DEBUG(dbgs() << "===== Instruction selection begins: BB#"
920         << FuncInfo->MBB->getNumber()
921         << " '" << FuncInfo->MBB->getName() << "'\n");
922 
923   PreprocessISelDAG();
924 
925   // Select target instructions for the DAG.
926   {
927     // Number all nodes with a topological order and set DAGSize.
928     DAGSize = CurDAG->AssignTopologicalOrder();
929 
930     // Create a dummy node (which is not added to allnodes), that adds
931     // a reference to the root node, preventing it from being deleted,
932     // and tracking any changes of the root.
933     HandleSDNode Dummy(CurDAG->getRoot());
934     SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
935     ++ISelPosition;
936 
937     // Make sure that ISelPosition gets properly updated when nodes are deleted
938     // in calls made from this function.
939     ISelUpdater ISU(*CurDAG, ISelPosition);
940 
941     // The AllNodes list is now topological-sorted. Visit the
942     // nodes by starting at the end of the list (the root of the
943     // graph) and preceding back toward the beginning (the entry
944     // node).
945     while (ISelPosition != CurDAG->allnodes_begin()) {
946       SDNode *Node = &*--ISelPosition;
947       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
948       // but there are currently some corner cases that it misses. Also, this
949       // makes it theoretically possible to disable the DAGCombiner.
950       if (Node->use_empty())
951         continue;
952 
953       SDNode *ResNode = Select(Node);
954 
955       // FIXME: This is pretty gross.  'Select' should be changed to not return
956       // anything at all and this code should be nuked with a tactical strike.
957 
958       // If node should not be replaced, continue with the next one.
959       if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
960         continue;
961       // Replace node.
962       if (ResNode) {
963         ReplaceUses(Node, ResNode);
964       }
965 
966       // If after the replacement this node is not used any more,
967       // remove this dead node.
968       if (Node->use_empty()) // Don't delete EntryToken, etc.
969         CurDAG->RemoveDeadNode(Node);
970     }
971 
972     CurDAG->setRoot(Dummy.getValue());
973   }
974 
975   DEBUG(dbgs() << "===== Instruction selection ends:\n");
976 
977   PostprocessISelDAG();
978 }
979 
980 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
981   for (const User *U : CPI->users()) {
982     if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
983       Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
984       if (IID == Intrinsic::eh_exceptionpointer ||
985           IID == Intrinsic::eh_exceptioncode)
986         return true;
987     }
988   }
989   return false;
990 }
991 
992 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
993 /// do other setup for EH landing-pad blocks.
994 bool SelectionDAGISel::PrepareEHLandingPad() {
995   MachineBasicBlock *MBB = FuncInfo->MBB;
996   const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
997   const BasicBlock *LLVMBB = MBB->getBasicBlock();
998   const TargetRegisterClass *PtrRC =
999       TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
1000 
1001   // Catchpads have one live-in register, which typically holds the exception
1002   // pointer or code.
1003   if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1004     if (hasExceptionPointerOrCodeUser(CPI)) {
1005       // Get or create the virtual register to hold the pointer or code.  Mark
1006       // the live in physreg and copy into the vreg.
1007       MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1008       assert(EHPhysReg && "target lacks exception pointer register");
1009       MBB->addLiveIn(EHPhysReg);
1010       unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1011       BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1012               TII->get(TargetOpcode::COPY), VReg)
1013           .addReg(EHPhysReg, RegState::Kill);
1014     }
1015     return true;
1016   }
1017 
1018   if (!LLVMBB->isLandingPad())
1019     return true;
1020 
1021   // Add a label to mark the beginning of the landing pad.  Deletion of the
1022   // landing pad can thus be detected via the MachineModuleInfo.
1023   MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
1024 
1025   // Assign the call site to the landing pad's begin label.
1026   MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1027 
1028   const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1029   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1030     .addSym(Label);
1031 
1032   // Mark exception register as live in.
1033   if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1034     FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1035 
1036   // Mark exception selector register as live in.
1037   if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1038     FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1039 
1040   return true;
1041 }
1042 
1043 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1044 /// side-effect free and is either dead or folded into a generated instruction.
1045 /// Return false if it needs to be emitted.
1046 static bool isFoldedOrDeadInstruction(const Instruction *I,
1047                                       FunctionLoweringInfo *FuncInfo) {
1048   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1049          !isa<TerminatorInst>(I) &&    // Terminators aren't folded.
1050          !isa<DbgInfoIntrinsic>(I) &&  // Debug instructions aren't folded.
1051          !I->isEHPad() &&              // EH pad instructions aren't folded.
1052          !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
1053 }
1054 
1055 #ifndef NDEBUG
1056 // Collect per Instruction statistics for fast-isel misses.  Only those
1057 // instructions that cause the bail are accounted for.  It does not account for
1058 // instructions higher in the block.  Thus, summing the per instructions stats
1059 // will not add up to what is reported by NumFastIselFailures.
1060 static void collectFailStats(const Instruction *I) {
1061   switch (I->getOpcode()) {
1062   default: assert (0 && "<Invalid operator> ");
1063 
1064   // Terminators
1065   case Instruction::Ret:         NumFastIselFailRet++; return;
1066   case Instruction::Br:          NumFastIselFailBr++; return;
1067   case Instruction::Switch:      NumFastIselFailSwitch++; return;
1068   case Instruction::IndirectBr:  NumFastIselFailIndirectBr++; return;
1069   case Instruction::Invoke:      NumFastIselFailInvoke++; return;
1070   case Instruction::Resume:      NumFastIselFailResume++; return;
1071   case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
1072 
1073   // Standard binary operators...
1074   case Instruction::Add:  NumFastIselFailAdd++; return;
1075   case Instruction::FAdd: NumFastIselFailFAdd++; return;
1076   case Instruction::Sub:  NumFastIselFailSub++; return;
1077   case Instruction::FSub: NumFastIselFailFSub++; return;
1078   case Instruction::Mul:  NumFastIselFailMul++; return;
1079   case Instruction::FMul: NumFastIselFailFMul++; return;
1080   case Instruction::UDiv: NumFastIselFailUDiv++; return;
1081   case Instruction::SDiv: NumFastIselFailSDiv++; return;
1082   case Instruction::FDiv: NumFastIselFailFDiv++; return;
1083   case Instruction::URem: NumFastIselFailURem++; return;
1084   case Instruction::SRem: NumFastIselFailSRem++; return;
1085   case Instruction::FRem: NumFastIselFailFRem++; return;
1086 
1087   // Logical operators...
1088   case Instruction::And: NumFastIselFailAnd++; return;
1089   case Instruction::Or:  NumFastIselFailOr++; return;
1090   case Instruction::Xor: NumFastIselFailXor++; return;
1091 
1092   // Memory instructions...
1093   case Instruction::Alloca:        NumFastIselFailAlloca++; return;
1094   case Instruction::Load:          NumFastIselFailLoad++; return;
1095   case Instruction::Store:         NumFastIselFailStore++; return;
1096   case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
1097   case Instruction::AtomicRMW:     NumFastIselFailAtomicRMW++; return;
1098   case Instruction::Fence:         NumFastIselFailFence++; return;
1099   case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
1100 
1101   // Convert instructions...
1102   case Instruction::Trunc:    NumFastIselFailTrunc++; return;
1103   case Instruction::ZExt:     NumFastIselFailZExt++; return;
1104   case Instruction::SExt:     NumFastIselFailSExt++; return;
1105   case Instruction::FPTrunc:  NumFastIselFailFPTrunc++; return;
1106   case Instruction::FPExt:    NumFastIselFailFPExt++; return;
1107   case Instruction::FPToUI:   NumFastIselFailFPToUI++; return;
1108   case Instruction::FPToSI:   NumFastIselFailFPToSI++; return;
1109   case Instruction::UIToFP:   NumFastIselFailUIToFP++; return;
1110   case Instruction::SIToFP:   NumFastIselFailSIToFP++; return;
1111   case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
1112   case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
1113   case Instruction::BitCast:  NumFastIselFailBitCast++; return;
1114 
1115   // Other instructions...
1116   case Instruction::ICmp:           NumFastIselFailICmp++; return;
1117   case Instruction::FCmp:           NumFastIselFailFCmp++; return;
1118   case Instruction::PHI:            NumFastIselFailPHI++; return;
1119   case Instruction::Select:         NumFastIselFailSelect++; return;
1120   case Instruction::Call: {
1121     if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) {
1122       switch (Intrinsic->getIntrinsicID()) {
1123       default:
1124         NumFastIselFailIntrinsicCall++; return;
1125       case Intrinsic::sadd_with_overflow:
1126         NumFastIselFailSAddWithOverflow++; return;
1127       case Intrinsic::uadd_with_overflow:
1128         NumFastIselFailUAddWithOverflow++; return;
1129       case Intrinsic::ssub_with_overflow:
1130         NumFastIselFailSSubWithOverflow++; return;
1131       case Intrinsic::usub_with_overflow:
1132         NumFastIselFailUSubWithOverflow++; return;
1133       case Intrinsic::smul_with_overflow:
1134         NumFastIselFailSMulWithOverflow++; return;
1135       case Intrinsic::umul_with_overflow:
1136         NumFastIselFailUMulWithOverflow++; return;
1137       case Intrinsic::frameaddress:
1138         NumFastIselFailFrameaddress++; return;
1139       case Intrinsic::sqrt:
1140           NumFastIselFailSqrt++; return;
1141       case Intrinsic::experimental_stackmap:
1142         NumFastIselFailStackMap++; return;
1143       case Intrinsic::experimental_patchpoint_void: // fall-through
1144       case Intrinsic::experimental_patchpoint_i64:
1145         NumFastIselFailPatchPoint++; return;
1146       }
1147     }
1148     NumFastIselFailCall++;
1149     return;
1150   }
1151   case Instruction::Shl:            NumFastIselFailShl++; return;
1152   case Instruction::LShr:           NumFastIselFailLShr++; return;
1153   case Instruction::AShr:           NumFastIselFailAShr++; return;
1154   case Instruction::VAArg:          NumFastIselFailVAArg++; return;
1155   case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
1156   case Instruction::InsertElement:  NumFastIselFailInsertElement++; return;
1157   case Instruction::ShuffleVector:  NumFastIselFailShuffleVector++; return;
1158   case Instruction::ExtractValue:   NumFastIselFailExtractValue++; return;
1159   case Instruction::InsertValue:    NumFastIselFailInsertValue++; return;
1160   case Instruction::LandingPad:     NumFastIselFailLandingPad++; return;
1161   }
1162 }
1163 #endif // NDEBUG
1164 
1165 /// Set up SwiftErrorVals by going through the function. If the function has
1166 /// swifterror argument, it will be the first entry.
1167 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI,
1168                                 FunctionLoweringInfo *FuncInfo) {
1169   if (!TLI->supportSwiftError())
1170     return;
1171 
1172   FuncInfo->SwiftErrorVals.clear();
1173   FuncInfo->SwiftErrorMap.clear();
1174   FuncInfo->SwiftErrorWorklist.clear();
1175 
1176   // Check if function has a swifterror argument.
1177   for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end();
1178        AI != AE; ++AI)
1179     if (AI->hasSwiftErrorAttr())
1180       FuncInfo->SwiftErrorVals.push_back(&*AI);
1181 
1182   for (const auto &LLVMBB : Fn)
1183     for (const auto &Inst : LLVMBB) {
1184       if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst))
1185         if (Alloca->isSwiftError())
1186           FuncInfo->SwiftErrorVals.push_back(Alloca);
1187     }
1188 }
1189 
1190 /// For each basic block, merge incoming swifterror values or simply propagate
1191 /// them. The merged results will be saved in SwiftErrorMap. For predecessors
1192 /// that are not yet visited, we create virtual registers to hold the swifterror
1193 /// values and save them in SwiftErrorWorklist.
1194 static void mergeIncomingSwiftErrors(FunctionLoweringInfo *FuncInfo,
1195                             const TargetLowering *TLI,
1196                             const TargetInstrInfo *TII,
1197                             const BasicBlock *LLVMBB,
1198                             SelectionDAGBuilder *SDB) {
1199   if (!TLI->supportSwiftError())
1200     return;
1201 
1202   // We should only do this when we have swifterror parameter or swifterror
1203   // alloc.
1204   if (FuncInfo->SwiftErrorVals.empty())
1205     return;
1206 
1207   // At beginning of a basic block, insert PHI nodes or get the virtual
1208   // register from the only predecessor, and update SwiftErrorMap; if one
1209   // of the predecessors is not visited, update SwiftErrorWorklist.
1210   // At end of a basic block, if a block is in SwiftErrorWorklist, insert copy
1211   // to sync up the virtual register assignment.
1212 
1213   // Always create a virtual register for each swifterror value in entry block.
1214   auto &DL = SDB->DAG.getDataLayout();
1215   const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1216   if (pred_begin(LLVMBB) == pred_end(LLVMBB)) {
1217     for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) {
1218       unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1219       // Assign Undef to Vreg. We construct MI directly to make sure it works
1220       // with FastISel.
1221       BuildMI(*FuncInfo->MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1222           TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
1223       FuncInfo->SwiftErrorMap[FuncInfo->MBB].push_back(VReg);
1224     }
1225     return;
1226   }
1227 
1228   if (auto *UniquePred = LLVMBB->getUniquePredecessor()) {
1229     auto *UniquePredMBB = FuncInfo->MBBMap[UniquePred];
1230     if (!FuncInfo->SwiftErrorMap.count(UniquePredMBB)) {
1231       // Update SwiftErrorWorklist with a new virtual register.
1232       for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) {
1233         unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1234         FuncInfo->SwiftErrorWorklist[UniquePredMBB].push_back(VReg);
1235         // Propagate the information from the single predecessor.
1236         FuncInfo->SwiftErrorMap[FuncInfo->MBB].push_back(VReg);
1237       }
1238       return;
1239     }
1240     // Propagate the information from the single predecessor.
1241     FuncInfo->SwiftErrorMap[FuncInfo->MBB] =
1242       FuncInfo->SwiftErrorMap[UniquePredMBB];
1243     return;
1244   }
1245 
1246   // For the case of multiple predecessors, update SwiftErrorWorklist.
1247   // Handle the case where we have two or more predecessors being the same.
1248   for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1249        PI != PE; ++PI) {
1250     auto *PredMBB = FuncInfo->MBBMap[*PI];
1251     if (!FuncInfo->SwiftErrorMap.count(PredMBB) &&
1252         !FuncInfo->SwiftErrorWorklist.count(PredMBB)) {
1253       for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) {
1254         unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1255         // When we actually visit the basic block PredMBB, we will materialize
1256         // the virtual register assignment in copySwiftErrorsToFinalVRegs.
1257         FuncInfo->SwiftErrorWorklist[PredMBB].push_back(VReg);
1258       }
1259     }
1260   }
1261 
1262   // For the case of multiple predecessors, create a virtual register for
1263   // each swifterror value and generate Phi node.
1264   for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) {
1265     unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1266     FuncInfo->SwiftErrorMap[FuncInfo->MBB].push_back(VReg);
1267 
1268     MachineInstrBuilder SwiftErrorPHI = BuildMI(*FuncInfo->MBB,
1269         FuncInfo->MBB->begin(), SDB->getCurDebugLoc(),
1270         TII->get(TargetOpcode::PHI), VReg);
1271     for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1272          PI != PE; ++PI) {
1273       auto *PredMBB = FuncInfo->MBBMap[*PI];
1274       unsigned SwiftErrorReg = FuncInfo->SwiftErrorMap.count(PredMBB) ?
1275         FuncInfo->SwiftErrorMap[PredMBB][I] :
1276         FuncInfo->SwiftErrorWorklist[PredMBB][I];
1277       SwiftErrorPHI.addReg(SwiftErrorReg)
1278                    .addMBB(PredMBB);
1279     }
1280   }
1281 }
1282 
1283 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1284   // Initialize the Fast-ISel state, if needed.
1285   FastISel *FastIS = nullptr;
1286   if (TM.Options.EnableFastISel)
1287     FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1288 
1289   setupSwiftErrorVals(Fn, TLI, FuncInfo);
1290 
1291   // Iterate over all basic blocks in the function.
1292   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1293   for (ReversePostOrderTraversal<const Function*>::rpo_iterator
1294        I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
1295     const BasicBlock *LLVMBB = *I;
1296 
1297     if (OptLevel != CodeGenOpt::None) {
1298       bool AllPredsVisited = true;
1299       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1300            PI != PE; ++PI) {
1301         if (!FuncInfo->VisitedBBs.count(*PI)) {
1302           AllPredsVisited = false;
1303           break;
1304         }
1305       }
1306 
1307       if (AllPredsVisited) {
1308         for (BasicBlock::const_iterator I = LLVMBB->begin();
1309              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1310           FuncInfo->ComputePHILiveOutRegInfo(PN);
1311       } else {
1312         for (BasicBlock::const_iterator I = LLVMBB->begin();
1313              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1314           FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1315       }
1316 
1317       FuncInfo->VisitedBBs.insert(LLVMBB);
1318     }
1319 
1320     BasicBlock::const_iterator const Begin =
1321         LLVMBB->getFirstNonPHI()->getIterator();
1322     BasicBlock::const_iterator const End = LLVMBB->end();
1323     BasicBlock::const_iterator BI = End;
1324 
1325     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1326     if (!FuncInfo->MBB)
1327       continue; // Some blocks like catchpads have no code or MBB.
1328     FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1329     mergeIncomingSwiftErrors(FuncInfo, TLI, TII, LLVMBB, SDB);
1330 
1331     // Setup an EH landing-pad block.
1332     FuncInfo->ExceptionPointerVirtReg = 0;
1333     FuncInfo->ExceptionSelectorVirtReg = 0;
1334     if (LLVMBB->isEHPad())
1335       if (!PrepareEHLandingPad())
1336         continue;
1337 
1338     // Before doing SelectionDAG ISel, see if FastISel has been requested.
1339     if (FastIS) {
1340       FastIS->startNewBlock();
1341 
1342       // Emit code for any incoming arguments. This must happen before
1343       // beginning FastISel on the entry block.
1344       if (LLVMBB == &Fn.getEntryBlock()) {
1345         ++NumEntryBlocks;
1346 
1347         // Lower any arguments needed in this block if this is the entry block.
1348         if (!FastIS->lowerArguments()) {
1349           // Fast isel failed to lower these arguments
1350           ++NumFastIselFailLowerArguments;
1351           if (EnableFastISelAbort > 1)
1352             report_fatal_error("FastISel didn't lower all arguments");
1353 
1354           // Use SelectionDAG argument lowering
1355           LowerArguments(Fn);
1356           CurDAG->setRoot(SDB->getControlRoot());
1357           SDB->clear();
1358           CodeGenAndEmitDAG();
1359         }
1360 
1361         // If we inserted any instructions at the beginning, make a note of
1362         // where they are, so we can be sure to emit subsequent instructions
1363         // after them.
1364         if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1365           FastIS->setLastLocalValue(std::prev(FuncInfo->InsertPt));
1366         else
1367           FastIS->setLastLocalValue(nullptr);
1368       }
1369 
1370       unsigned NumFastIselRemaining = std::distance(Begin, End);
1371       // Do FastISel on as many instructions as possible.
1372       for (; BI != Begin; --BI) {
1373         const Instruction *Inst = &*std::prev(BI);
1374 
1375         // If we no longer require this instruction, skip it.
1376         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1377           --NumFastIselRemaining;
1378           continue;
1379         }
1380 
1381         // Bottom-up: reset the insert pos at the top, after any local-value
1382         // instructions.
1383         FastIS->recomputeInsertPt();
1384 
1385         // Try to select the instruction with FastISel.
1386         if (FastIS->selectInstruction(Inst)) {
1387           --NumFastIselRemaining;
1388           ++NumFastIselSuccess;
1389           // If fast isel succeeded, skip over all the folded instructions, and
1390           // then see if there is a load right before the selected instructions.
1391           // Try to fold the load if so.
1392           const Instruction *BeforeInst = Inst;
1393           while (BeforeInst != &*Begin) {
1394             BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1395             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1396               break;
1397           }
1398           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1399               BeforeInst->hasOneUse() &&
1400               FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1401             // If we succeeded, don't re-select the load.
1402             BI = std::next(BasicBlock::const_iterator(BeforeInst));
1403             --NumFastIselRemaining;
1404             ++NumFastIselSuccess;
1405           }
1406           continue;
1407         }
1408 
1409 #ifndef NDEBUG
1410         if (EnableFastISelVerbose2)
1411           collectFailStats(Inst);
1412 #endif
1413 
1414         // Then handle certain instructions as single-LLVM-Instruction blocks.
1415         if (isa<CallInst>(Inst)) {
1416 
1417           if (EnableFastISelVerbose || EnableFastISelAbort) {
1418             dbgs() << "FastISel missed call: ";
1419             Inst->dump();
1420           }
1421           if (EnableFastISelAbort > 2)
1422             // FastISel selector couldn't handle something and bailed.
1423             // For the purpose of debugging, just abort.
1424             report_fatal_error("FastISel didn't select the entire block");
1425 
1426           if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1427               !Inst->use_empty()) {
1428             unsigned &R = FuncInfo->ValueMap[Inst];
1429             if (!R)
1430               R = FuncInfo->CreateRegs(Inst->getType());
1431           }
1432 
1433           bool HadTailCall = false;
1434           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1435           SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1436 
1437           // If the call was emitted as a tail call, we're done with the block.
1438           // We also need to delete any previously emitted instructions.
1439           if (HadTailCall) {
1440             FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1441             --BI;
1442             break;
1443           }
1444 
1445           // Recompute NumFastIselRemaining as Selection DAG instruction
1446           // selection may have handled the call, input args, etc.
1447           unsigned RemainingNow = std::distance(Begin, BI);
1448           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1449           NumFastIselRemaining = RemainingNow;
1450           continue;
1451         }
1452 
1453         bool ShouldAbort = EnableFastISelAbort;
1454         if (EnableFastISelVerbose || EnableFastISelAbort) {
1455           if (isa<TerminatorInst>(Inst)) {
1456             // Use a different message for terminator misses.
1457             dbgs() << "FastISel missed terminator: ";
1458             // Don't abort unless for terminator unless the level is really high
1459             ShouldAbort = (EnableFastISelAbort > 2);
1460           } else {
1461             dbgs() << "FastISel miss: ";
1462           }
1463           Inst->dump();
1464         }
1465         if (ShouldAbort)
1466           // FastISel selector couldn't handle something and bailed.
1467           // For the purpose of debugging, just abort.
1468           report_fatal_error("FastISel didn't select the entire block");
1469 
1470         NumFastIselFailures += NumFastIselRemaining;
1471         break;
1472       }
1473 
1474       FastIS->recomputeInsertPt();
1475     } else {
1476       // Lower any arguments needed in this block if this is the entry block.
1477       if (LLVMBB == &Fn.getEntryBlock()) {
1478         ++NumEntryBlocks;
1479         LowerArguments(Fn);
1480       }
1481     }
1482     if (getAnalysis<StackProtector>().shouldEmitSDCheck(*LLVMBB))
1483       SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB]);
1484 
1485     if (Begin != BI)
1486       ++NumDAGBlocks;
1487     else
1488       ++NumFastIselBlocks;
1489 
1490     if (Begin != BI) {
1491       // Run SelectionDAG instruction selection on the remainder of the block
1492       // not handled by FastISel. If FastISel is not run, this is the entire
1493       // block.
1494       bool HadTailCall;
1495       SelectBasicBlock(Begin, BI, HadTailCall);
1496     }
1497 
1498     FinishBasicBlock();
1499     FuncInfo->PHINodesToUpdate.clear();
1500   }
1501 
1502   delete FastIS;
1503   SDB->clearDanglingDebugInfo();
1504   SDB->SPDescriptor.resetPerFunctionState();
1505 }
1506 
1507 /// Given that the input MI is before a partial terminator sequence TSeq, return
1508 /// true if M + TSeq also a partial terminator sequence.
1509 ///
1510 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1511 /// lowering copy vregs into physical registers, which are then passed into
1512 /// terminator instructors so we can satisfy ABI constraints. A partial
1513 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1514 /// may be the whole terminator sequence).
1515 static bool MIIsInTerminatorSequence(const MachineInstr *MI) {
1516   // If we do not have a copy or an implicit def, we return true if and only if
1517   // MI is a debug value.
1518   if (!MI->isCopy() && !MI->isImplicitDef())
1519     // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1520     // physical registers if there is debug info associated with the terminator
1521     // of our mbb. We want to include said debug info in our terminator
1522     // sequence, so we return true in that case.
1523     return MI->isDebugValue();
1524 
1525   // We have left the terminator sequence if we are not doing one of the
1526   // following:
1527   //
1528   // 1. Copying a vreg into a physical register.
1529   // 2. Copying a vreg into a vreg.
1530   // 3. Defining a register via an implicit def.
1531 
1532   // OPI should always be a register definition...
1533   MachineInstr::const_mop_iterator OPI = MI->operands_begin();
1534   if (!OPI->isReg() || !OPI->isDef())
1535     return false;
1536 
1537   // Defining any register via an implicit def is always ok.
1538   if (MI->isImplicitDef())
1539     return true;
1540 
1541   // Grab the copy source...
1542   MachineInstr::const_mop_iterator OPI2 = OPI;
1543   ++OPI2;
1544   assert(OPI2 != MI->operands_end()
1545          && "Should have a copy implying we should have 2 arguments.");
1546 
1547   // Make sure that the copy dest is not a vreg when the copy source is a
1548   // physical register.
1549   if (!OPI2->isReg() ||
1550       (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
1551        TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
1552     return false;
1553 
1554   return true;
1555 }
1556 
1557 /// Find the split point at which to splice the end of BB into its success stack
1558 /// protector check machine basic block.
1559 ///
1560 /// On many platforms, due to ABI constraints, terminators, even before register
1561 /// allocation, use physical registers. This creates an issue for us since
1562 /// physical registers at this point can not travel across basic
1563 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1564 /// when they enter functions and moves them through a sequence of copies back
1565 /// into the physical registers right before the terminator creating a
1566 /// ``Terminator Sequence''. This function is searching for the beginning of the
1567 /// terminator sequence so that we can ensure that we splice off not just the
1568 /// terminator, but additionally the copies that move the vregs into the
1569 /// physical registers.
1570 static MachineBasicBlock::iterator
1571 FindSplitPointForStackProtector(MachineBasicBlock *BB, DebugLoc DL) {
1572   MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1573   //
1574   if (SplitPoint == BB->begin())
1575     return SplitPoint;
1576 
1577   MachineBasicBlock::iterator Start = BB->begin();
1578   MachineBasicBlock::iterator Previous = SplitPoint;
1579   --Previous;
1580 
1581   while (MIIsInTerminatorSequence(Previous)) {
1582     SplitPoint = Previous;
1583     if (Previous == Start)
1584       break;
1585     --Previous;
1586   }
1587 
1588   return SplitPoint;
1589 }
1590 
1591 void
1592 SelectionDAGISel::FinishBasicBlock() {
1593   DEBUG(dbgs() << "Total amount of phi nodes to update: "
1594                << FuncInfo->PHINodesToUpdate.size() << "\n";
1595         for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1596           dbgs() << "Node " << i << " : ("
1597                  << FuncInfo->PHINodesToUpdate[i].first
1598                  << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1599 
1600   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1601   // PHI nodes in successors.
1602   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1603     MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1604     assert(PHI->isPHI() &&
1605            "This is not a machine PHI node that we are updating!");
1606     if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1607       continue;
1608     PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1609   }
1610 
1611   // Handle stack protector.
1612   if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1613     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1614     MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1615 
1616     // Find the split point to split the parent mbb. At the same time copy all
1617     // physical registers used in the tail of parent mbb into virtual registers
1618     // before the split point and back into physical registers after the split
1619     // point. This prevents us needing to deal with Live-ins and many other
1620     // register allocation issues caused by us splitting the parent mbb. The
1621     // register allocator will clean up said virtual copies later on.
1622     MachineBasicBlock::iterator SplitPoint =
1623       FindSplitPointForStackProtector(ParentMBB, SDB->getCurDebugLoc());
1624 
1625     // Splice the terminator of ParentMBB into SuccessMBB.
1626     SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1627                        SplitPoint,
1628                        ParentMBB->end());
1629 
1630     // Add compare/jump on neq/jump to the parent BB.
1631     FuncInfo->MBB = ParentMBB;
1632     FuncInfo->InsertPt = ParentMBB->end();
1633     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1634     CurDAG->setRoot(SDB->getRoot());
1635     SDB->clear();
1636     CodeGenAndEmitDAG();
1637 
1638     // CodeGen Failure MBB if we have not codegened it yet.
1639     MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1640     if (FailureMBB->empty()) {
1641       FuncInfo->MBB = FailureMBB;
1642       FuncInfo->InsertPt = FailureMBB->end();
1643       SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1644       CurDAG->setRoot(SDB->getRoot());
1645       SDB->clear();
1646       CodeGenAndEmitDAG();
1647     }
1648 
1649     // Clear the Per-BB State.
1650     SDB->SPDescriptor.resetPerBBState();
1651   }
1652 
1653   // Lower each BitTestBlock.
1654   for (auto &BTB : SDB->BitTestCases) {
1655     // Lower header first, if it wasn't already lowered
1656     if (!BTB.Emitted) {
1657       // Set the current basic block to the mbb we wish to insert the code into
1658       FuncInfo->MBB = BTB.Parent;
1659       FuncInfo->InsertPt = FuncInfo->MBB->end();
1660       // Emit the code
1661       SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1662       CurDAG->setRoot(SDB->getRoot());
1663       SDB->clear();
1664       CodeGenAndEmitDAG();
1665     }
1666 
1667     BranchProbability UnhandledProb = BTB.Prob;
1668     for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1669       UnhandledProb -= BTB.Cases[j].ExtraProb;
1670       // Set the current basic block to the mbb we wish to insert the code into
1671       FuncInfo->MBB = BTB.Cases[j].ThisBB;
1672       FuncInfo->InsertPt = FuncInfo->MBB->end();
1673       // Emit the code
1674 
1675       // If all cases cover a contiguous range, it is not necessary to jump to
1676       // the default block after the last bit test fails. This is because the
1677       // range check during bit test header creation has guaranteed that every
1678       // case here doesn't go outside the range. In this case, there is no need
1679       // to perform the last bit test, as it will always be true. Instead, make
1680       // the second-to-last bit-test fall through to the target of the last bit
1681       // test, and delete the last bit test.
1682 
1683       MachineBasicBlock *NextMBB;
1684       if (BTB.ContiguousRange && j + 2 == ej) {
1685         // Second-to-last bit-test with contiguous range: fall through to the
1686         // target of the final bit test.
1687         NextMBB = BTB.Cases[j + 1].TargetBB;
1688       } else if (j + 1 == ej) {
1689         // For the last bit test, fall through to Default.
1690         NextMBB = BTB.Default;
1691       } else {
1692         // Otherwise, fall through to the next bit test.
1693         NextMBB = BTB.Cases[j + 1].ThisBB;
1694       }
1695 
1696       SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1697                             FuncInfo->MBB);
1698 
1699       CurDAG->setRoot(SDB->getRoot());
1700       SDB->clear();
1701       CodeGenAndEmitDAG();
1702 
1703       if (BTB.ContiguousRange && j + 2 == ej) {
1704         // Since we're not going to use the final bit test, remove it.
1705         BTB.Cases.pop_back();
1706         break;
1707       }
1708     }
1709 
1710     // Update PHI Nodes
1711     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1712          pi != pe; ++pi) {
1713       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1714       MachineBasicBlock *PHIBB = PHI->getParent();
1715       assert(PHI->isPHI() &&
1716              "This is not a machine PHI node that we are updating!");
1717       // This is "default" BB. We have two jumps to it. From "header" BB and
1718       // from last "case" BB, unless the latter was skipped.
1719       if (PHIBB == BTB.Default) {
1720         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
1721         if (!BTB.ContiguousRange) {
1722           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1723               .addMBB(BTB.Cases.back().ThisBB);
1724          }
1725       }
1726       // One of "cases" BB.
1727       for (unsigned j = 0, ej = BTB.Cases.size();
1728            j != ej; ++j) {
1729         MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
1730         if (cBB->isSuccessor(PHIBB))
1731           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1732       }
1733     }
1734   }
1735   SDB->BitTestCases.clear();
1736 
1737   // If the JumpTable record is filled in, then we need to emit a jump table.
1738   // Updating the PHI nodes is tricky in this case, since we need to determine
1739   // whether the PHI is a successor of the range check MBB or the jump table MBB
1740   for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1741     // Lower header first, if it wasn't already lowered
1742     if (!SDB->JTCases[i].first.Emitted) {
1743       // Set the current basic block to the mbb we wish to insert the code into
1744       FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1745       FuncInfo->InsertPt = FuncInfo->MBB->end();
1746       // Emit the code
1747       SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1748                                 FuncInfo->MBB);
1749       CurDAG->setRoot(SDB->getRoot());
1750       SDB->clear();
1751       CodeGenAndEmitDAG();
1752     }
1753 
1754     // Set the current basic block to the mbb we wish to insert the code into
1755     FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1756     FuncInfo->InsertPt = FuncInfo->MBB->end();
1757     // Emit the code
1758     SDB->visitJumpTable(SDB->JTCases[i].second);
1759     CurDAG->setRoot(SDB->getRoot());
1760     SDB->clear();
1761     CodeGenAndEmitDAG();
1762 
1763     // Update PHI Nodes
1764     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1765          pi != pe; ++pi) {
1766       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1767       MachineBasicBlock *PHIBB = PHI->getParent();
1768       assert(PHI->isPHI() &&
1769              "This is not a machine PHI node that we are updating!");
1770       // "default" BB. We can go there only from header BB.
1771       if (PHIBB == SDB->JTCases[i].second.Default)
1772         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1773            .addMBB(SDB->JTCases[i].first.HeaderBB);
1774       // JT BB. Just iterate over successors here
1775       if (FuncInfo->MBB->isSuccessor(PHIBB))
1776         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1777     }
1778   }
1779   SDB->JTCases.clear();
1780 
1781   // If we generated any switch lowering information, build and codegen any
1782   // additional DAGs necessary.
1783   for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1784     // Set the current basic block to the mbb we wish to insert the code into
1785     FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1786     FuncInfo->InsertPt = FuncInfo->MBB->end();
1787 
1788     // Determine the unique successors.
1789     SmallVector<MachineBasicBlock *, 2> Succs;
1790     Succs.push_back(SDB->SwitchCases[i].TrueBB);
1791     if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1792       Succs.push_back(SDB->SwitchCases[i].FalseBB);
1793 
1794     // Emit the code. Note that this could result in FuncInfo->MBB being split.
1795     SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1796     CurDAG->setRoot(SDB->getRoot());
1797     SDB->clear();
1798     CodeGenAndEmitDAG();
1799 
1800     // Remember the last block, now that any splitting is done, for use in
1801     // populating PHI nodes in successors.
1802     MachineBasicBlock *ThisBB = FuncInfo->MBB;
1803 
1804     // Handle any PHI nodes in successors of this chunk, as if we were coming
1805     // from the original BB before switch expansion.  Note that PHI nodes can
1806     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1807     // handle them the right number of times.
1808     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1809       FuncInfo->MBB = Succs[i];
1810       FuncInfo->InsertPt = FuncInfo->MBB->end();
1811       // FuncInfo->MBB may have been removed from the CFG if a branch was
1812       // constant folded.
1813       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1814         for (MachineBasicBlock::iterator
1815              MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1816              MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1817           MachineInstrBuilder PHI(*MF, MBBI);
1818           // This value for this PHI node is recorded in PHINodesToUpdate.
1819           for (unsigned pn = 0; ; ++pn) {
1820             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1821                    "Didn't find PHI entry!");
1822             if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1823               PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1824               break;
1825             }
1826           }
1827         }
1828       }
1829     }
1830   }
1831   SDB->SwitchCases.clear();
1832 }
1833 
1834 /// Create the scheduler. If a specific scheduler was specified
1835 /// via the SchedulerRegistry, use it, otherwise select the
1836 /// one preferred by the target.
1837 ///
1838 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1839   return ISHeuristic(this, OptLevel);
1840 }
1841 
1842 //===----------------------------------------------------------------------===//
1843 // Helper functions used by the generated instruction selector.
1844 //===----------------------------------------------------------------------===//
1845 // Calls to these methods are generated by tblgen.
1846 
1847 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1848 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1849 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1850 /// specified in the .td file (e.g. 255).
1851 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1852                                     int64_t DesiredMaskS) const {
1853   const APInt &ActualMask = RHS->getAPIntValue();
1854   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1855 
1856   // If the actual mask exactly matches, success!
1857   if (ActualMask == DesiredMask)
1858     return true;
1859 
1860   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1861   if (ActualMask.intersects(~DesiredMask))
1862     return false;
1863 
1864   // Otherwise, the DAG Combiner may have proven that the value coming in is
1865   // either already zero or is not demanded.  Check for known zero input bits.
1866   APInt NeededMask = DesiredMask & ~ActualMask;
1867   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1868     return true;
1869 
1870   // TODO: check to see if missing bits are just not demanded.
1871 
1872   // Otherwise, this pattern doesn't match.
1873   return false;
1874 }
1875 
1876 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
1877 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1878 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1879 /// specified in the .td file (e.g. 255).
1880 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1881                                    int64_t DesiredMaskS) const {
1882   const APInt &ActualMask = RHS->getAPIntValue();
1883   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1884 
1885   // If the actual mask exactly matches, success!
1886   if (ActualMask == DesiredMask)
1887     return true;
1888 
1889   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1890   if (ActualMask.intersects(~DesiredMask))
1891     return false;
1892 
1893   // Otherwise, the DAG Combiner may have proven that the value coming in is
1894   // either already zero or is not demanded.  Check for known zero input bits.
1895   APInt NeededMask = DesiredMask & ~ActualMask;
1896 
1897   APInt KnownZero, KnownOne;
1898   CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
1899 
1900   // If all the missing bits in the or are already known to be set, match!
1901   if ((NeededMask & KnownOne) == NeededMask)
1902     return true;
1903 
1904   // TODO: check to see if missing bits are just not demanded.
1905 
1906   // Otherwise, this pattern doesn't match.
1907   return false;
1908 }
1909 
1910 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1911 /// by tblgen.  Others should not call it.
1912 void SelectionDAGISel::
1913 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SDLoc DL) {
1914   std::vector<SDValue> InOps;
1915   std::swap(InOps, Ops);
1916 
1917   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1918   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
1919   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
1920   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
1921 
1922   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1923   if (InOps[e-1].getValueType() == MVT::Glue)
1924     --e;  // Don't process a glue operand if it is here.
1925 
1926   while (i != e) {
1927     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1928     if (!InlineAsm::isMemKind(Flags)) {
1929       // Just skip over this operand, copying the operands verbatim.
1930       Ops.insert(Ops.end(), InOps.begin()+i,
1931                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1932       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1933     } else {
1934       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1935              "Memory operand with multiple values?");
1936 
1937       unsigned TiedToOperand;
1938       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
1939         // We need the constraint ID from the operand this is tied to.
1940         unsigned CurOp = InlineAsm::Op_FirstOperand;
1941         Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1942         for (; TiedToOperand; --TiedToOperand) {
1943           CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
1944           Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1945         }
1946       }
1947 
1948       // Otherwise, this is a memory operand.  Ask the target to select it.
1949       std::vector<SDValue> SelOps;
1950       if (SelectInlineAsmMemoryOperand(InOps[i+1],
1951                                        InlineAsm::getMemoryConstraintID(Flags),
1952                                        SelOps))
1953         report_fatal_error("Could not match memory address.  Inline asm"
1954                            " failure!");
1955 
1956       // Add this to the output node.
1957       unsigned NewFlags =
1958         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1959       Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
1960       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1961       i += 2;
1962     }
1963   }
1964 
1965   // Add the glue input back if present.
1966   if (e != InOps.size())
1967     Ops.push_back(InOps.back());
1968 }
1969 
1970 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1971 /// SDNode.
1972 ///
1973 static SDNode *findGlueUse(SDNode *N) {
1974   unsigned FlagResNo = N->getNumValues()-1;
1975   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1976     SDUse &Use = I.getUse();
1977     if (Use.getResNo() == FlagResNo)
1978       return Use.getUser();
1979   }
1980   return nullptr;
1981 }
1982 
1983 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1984 /// This function recursively traverses up the operand chain, ignoring
1985 /// certain nodes.
1986 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1987                           SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
1988                           bool IgnoreChains) {
1989   // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1990   // greater than all of its (recursive) operands.  If we scan to a point where
1991   // 'use' is smaller than the node we're scanning for, then we know we will
1992   // never find it.
1993   //
1994   // The Use may be -1 (unassigned) if it is a newly allocated node.  This can
1995   // happen because we scan down to newly selected nodes in the case of glue
1996   // uses.
1997   if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1998     return false;
1999 
2000   // Don't revisit nodes if we already scanned it and didn't fail, we know we
2001   // won't fail if we scan it again.
2002   if (!Visited.insert(Use).second)
2003     return false;
2004 
2005   for (const SDValue &Op : Use->op_values()) {
2006     // Ignore chain uses, they are validated by HandleMergeInputChains.
2007     if (Op.getValueType() == MVT::Other && IgnoreChains)
2008       continue;
2009 
2010     SDNode *N = Op.getNode();
2011     if (N == Def) {
2012       if (Use == ImmedUse || Use == Root)
2013         continue;  // We are not looking for immediate use.
2014       assert(N != Root);
2015       return true;
2016     }
2017 
2018     // Traverse up the operand chain.
2019     if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
2020       return true;
2021   }
2022   return false;
2023 }
2024 
2025 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2026 /// operand node N of U during instruction selection that starts at Root.
2027 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
2028                                           SDNode *Root) const {
2029   if (OptLevel == CodeGenOpt::None) return false;
2030   return N.hasOneUse();
2031 }
2032 
2033 /// IsLegalToFold - Returns true if the specific operand node N of
2034 /// U can be folded during instruction selection that starts at Root.
2035 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
2036                                      CodeGenOpt::Level OptLevel,
2037                                      bool IgnoreChains) {
2038   if (OptLevel == CodeGenOpt::None) return false;
2039 
2040   // If Root use can somehow reach N through a path that that doesn't contain
2041   // U then folding N would create a cycle. e.g. In the following
2042   // diagram, Root can reach N through X. If N is folded into into Root, then
2043   // X is both a predecessor and a successor of U.
2044   //
2045   //          [N*]           //
2046   //         ^   ^           //
2047   //        /     \          //
2048   //      [U*]    [X]?       //
2049   //        ^     ^          //
2050   //         \   /           //
2051   //          \ /            //
2052   //         [Root*]         //
2053   //
2054   // * indicates nodes to be folded together.
2055   //
2056   // If Root produces glue, then it gets (even more) interesting. Since it
2057   // will be "glued" together with its glue use in the scheduler, we need to
2058   // check if it might reach N.
2059   //
2060   //          [N*]           //
2061   //         ^   ^           //
2062   //        /     \          //
2063   //      [U*]    [X]?       //
2064   //        ^       ^        //
2065   //         \       \       //
2066   //          \      |       //
2067   //         [Root*] |       //
2068   //          ^      |       //
2069   //          f      |       //
2070   //          |      /       //
2071   //         [Y]    /        //
2072   //           ^   /         //
2073   //           f  /          //
2074   //           | /           //
2075   //          [GU]           //
2076   //
2077   // If GU (glue use) indirectly reaches N (the load), and Root folds N
2078   // (call it Fold), then X is a predecessor of GU and a successor of
2079   // Fold. But since Fold and GU are glued together, this will create
2080   // a cycle in the scheduling graph.
2081 
2082   // If the node has glue, walk down the graph to the "lowest" node in the
2083   // glueged set.
2084   EVT VT = Root->getValueType(Root->getNumValues()-1);
2085   while (VT == MVT::Glue) {
2086     SDNode *GU = findGlueUse(Root);
2087     if (!GU)
2088       break;
2089     Root = GU;
2090     VT = Root->getValueType(Root->getNumValues()-1);
2091 
2092     // If our query node has a glue result with a use, we've walked up it.  If
2093     // the user (which has already been selected) has a chain or indirectly uses
2094     // the chain, our WalkChainUsers predicate will not consider it.  Because of
2095     // this, we cannot ignore chains in this predicate.
2096     IgnoreChains = false;
2097   }
2098 
2099 
2100   SmallPtrSet<SDNode*, 16> Visited;
2101   return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
2102 }
2103 
2104 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2105   SDLoc DL(N);
2106 
2107   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2108   SelectInlineAsmMemoryOperands(Ops, DL);
2109 
2110   const EVT VTs[] = {MVT::Other, MVT::Glue};
2111   SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops);
2112   New->setNodeId(-1);
2113   return New.getNode();
2114 }
2115 
2116 SDNode
2117 *SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2118   SDLoc dl(Op);
2119   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2120   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2121   unsigned Reg =
2122       TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0),
2123                              *CurDAG);
2124   SDValue New = CurDAG->getCopyFromReg(
2125                         Op->getOperand(0), dl, Reg, Op->getValueType(0));
2126   New->setNodeId(-1);
2127   return New.getNode();
2128 }
2129 
2130 SDNode
2131 *SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2132   SDLoc dl(Op);
2133   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2134   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2135   unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
2136                                         Op->getOperand(2).getValueType(),
2137                                         *CurDAG);
2138   SDValue New = CurDAG->getCopyToReg(
2139                         Op->getOperand(0), dl, Reg, Op->getOperand(2));
2140   New->setNodeId(-1);
2141   return New.getNode();
2142 }
2143 
2144 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
2145   return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
2146 }
2147 
2148 /// GetVBR - decode a vbr encoding whose top bit is set.
2149 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t
2150 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2151   assert(Val >= 128 && "Not a VBR");
2152   Val &= 127;  // Remove first vbr bit.
2153 
2154   unsigned Shift = 7;
2155   uint64_t NextBits;
2156   do {
2157     NextBits = MatcherTable[Idx++];
2158     Val |= (NextBits&127) << Shift;
2159     Shift += 7;
2160   } while (NextBits & 128);
2161 
2162   return Val;
2163 }
2164 
2165 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
2166 /// interior glue and chain results to use the new glue and chain results.
2167 void SelectionDAGISel::
2168 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
2169                     const SmallVectorImpl<SDNode*> &ChainNodesMatched,
2170                     SDValue InputGlue,
2171                     const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
2172                     bool isMorphNodeTo) {
2173   SmallVector<SDNode*, 4> NowDeadNodes;
2174 
2175   // Now that all the normal results are replaced, we replace the chain and
2176   // glue results if present.
2177   if (!ChainNodesMatched.empty()) {
2178     assert(InputChain.getNode() &&
2179            "Matched input chains but didn't produce a chain");
2180     // Loop over all of the nodes we matched that produced a chain result.
2181     // Replace all the chain results with the final chain we ended up with.
2182     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2183       SDNode *ChainNode = ChainNodesMatched[i];
2184 
2185       // If this node was already deleted, don't look at it.
2186       if (ChainNode->getOpcode() == ISD::DELETED_NODE)
2187         continue;
2188 
2189       // Don't replace the results of the root node if we're doing a
2190       // MorphNodeTo.
2191       if (ChainNode == NodeToMatch && isMorphNodeTo)
2192         continue;
2193 
2194       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2195       if (ChainVal.getValueType() == MVT::Glue)
2196         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2197       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2198       CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
2199 
2200       // If the node became dead and we haven't already seen it, delete it.
2201       if (ChainNode->use_empty() &&
2202           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
2203         NowDeadNodes.push_back(ChainNode);
2204     }
2205   }
2206 
2207   // If the result produces glue, update any glue results in the matched
2208   // pattern with the glue result.
2209   if (InputGlue.getNode()) {
2210     // Handle any interior nodes explicitly marked.
2211     for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
2212       SDNode *FRN = GlueResultNodesMatched[i];
2213 
2214       // If this node was already deleted, don't look at it.
2215       if (FRN->getOpcode() == ISD::DELETED_NODE)
2216         continue;
2217 
2218       assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
2219              "Doesn't have a glue result");
2220       CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
2221                                         InputGlue);
2222 
2223       // If the node became dead and we haven't already seen it, delete it.
2224       if (FRN->use_empty() &&
2225           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
2226         NowDeadNodes.push_back(FRN);
2227     }
2228   }
2229 
2230   if (!NowDeadNodes.empty())
2231     CurDAG->RemoveDeadNodes(NowDeadNodes);
2232 
2233   DEBUG(dbgs() << "ISEL: Match complete!\n");
2234 }
2235 
2236 enum ChainResult {
2237   CR_Simple,
2238   CR_InducesCycle,
2239   CR_LeadsToInteriorNode
2240 };
2241 
2242 /// WalkChainUsers - Walk down the users of the specified chained node that is
2243 /// part of the pattern we're matching, looking at all of the users we find.
2244 /// This determines whether something is an interior node, whether we have a
2245 /// non-pattern node in between two pattern nodes (which prevent folding because
2246 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
2247 /// between pattern nodes (in which case the TF becomes part of the pattern).
2248 ///
2249 /// The walk we do here is guaranteed to be small because we quickly get down to
2250 /// already selected nodes "below" us.
2251 static ChainResult
2252 WalkChainUsers(const SDNode *ChainedNode,
2253                SmallVectorImpl<SDNode *> &ChainedNodesInPattern,
2254                DenseMap<const SDNode *, ChainResult> &TokenFactorResult,
2255                SmallVectorImpl<SDNode *> &InteriorChainedNodes) {
2256   ChainResult Result = CR_Simple;
2257 
2258   for (SDNode::use_iterator UI = ChainedNode->use_begin(),
2259          E = ChainedNode->use_end(); UI != E; ++UI) {
2260     // Make sure the use is of the chain, not some other value we produce.
2261     if (UI.getUse().getValueType() != MVT::Other) continue;
2262 
2263     SDNode *User = *UI;
2264 
2265     if (User->getOpcode() == ISD::HANDLENODE)  // Root of the graph.
2266       continue;
2267 
2268     // If we see an already-selected machine node, then we've gone beyond the
2269     // pattern that we're selecting down into the already selected chunk of the
2270     // DAG.
2271     unsigned UserOpcode = User->getOpcode();
2272     if (User->isMachineOpcode() ||
2273         UserOpcode == ISD::CopyToReg ||
2274         UserOpcode == ISD::CopyFromReg ||
2275         UserOpcode == ISD::INLINEASM ||
2276         UserOpcode == ISD::EH_LABEL ||
2277         UserOpcode == ISD::LIFETIME_START ||
2278         UserOpcode == ISD::LIFETIME_END) {
2279       // If their node ID got reset to -1 then they've already been selected.
2280       // Treat them like a MachineOpcode.
2281       if (User->getNodeId() == -1)
2282         continue;
2283     }
2284 
2285     // If we have a TokenFactor, we handle it specially.
2286     if (User->getOpcode() != ISD::TokenFactor) {
2287       // If the node isn't a token factor and isn't part of our pattern, then it
2288       // must be a random chained node in between two nodes we're selecting.
2289       // This happens when we have something like:
2290       //   x = load ptr
2291       //   call
2292       //   y = x+4
2293       //   store y -> ptr
2294       // Because we structurally match the load/store as a read/modify/write,
2295       // but the call is chained between them.  We cannot fold in this case
2296       // because it would induce a cycle in the graph.
2297       if (!std::count(ChainedNodesInPattern.begin(),
2298                       ChainedNodesInPattern.end(), User))
2299         return CR_InducesCycle;
2300 
2301       // Otherwise we found a node that is part of our pattern.  For example in:
2302       //   x = load ptr
2303       //   y = x+4
2304       //   store y -> ptr
2305       // This would happen when we're scanning down from the load and see the
2306       // store as a user.  Record that there is a use of ChainedNode that is
2307       // part of the pattern and keep scanning uses.
2308       Result = CR_LeadsToInteriorNode;
2309       InteriorChainedNodes.push_back(User);
2310       continue;
2311     }
2312 
2313     // If we found a TokenFactor, there are two cases to consider: first if the
2314     // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
2315     // uses of the TF are in our pattern) we just want to ignore it.  Second,
2316     // the TokenFactor can be sandwiched in between two chained nodes, like so:
2317     //     [Load chain]
2318     //         ^
2319     //         |
2320     //       [Load]
2321     //       ^    ^
2322     //       |    \                    DAG's like cheese
2323     //      /       \                       do you?
2324     //     /         |
2325     // [TokenFactor] [Op]
2326     //     ^          ^
2327     //     |          |
2328     //      \        /
2329     //       \      /
2330     //       [Store]
2331     //
2332     // In this case, the TokenFactor becomes part of our match and we rewrite it
2333     // as a new TokenFactor.
2334     //
2335     // To distinguish these two cases, do a recursive walk down the uses.
2336     auto MemoizeResult = TokenFactorResult.find(User);
2337     bool Visited = MemoizeResult != TokenFactorResult.end();
2338     // Recursively walk chain users only if the result is not memoized.
2339     if (!Visited) {
2340       auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult,
2341                                 InteriorChainedNodes);
2342       MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first;
2343     }
2344     switch (MemoizeResult->second) {
2345     case CR_Simple:
2346       // If the uses of the TokenFactor are just already-selected nodes, ignore
2347       // it, it is "below" our pattern.
2348       continue;
2349     case CR_InducesCycle:
2350       // If the uses of the TokenFactor lead to nodes that are not part of our
2351       // pattern that are not selected, folding would turn this into a cycle,
2352       // bail out now.
2353       return CR_InducesCycle;
2354     case CR_LeadsToInteriorNode:
2355       break;  // Otherwise, keep processing.
2356     }
2357 
2358     // Okay, we know we're in the interesting interior case.  The TokenFactor
2359     // is now going to be considered part of the pattern so that we rewrite its
2360     // uses (it may have uses that are not part of the pattern) with the
2361     // ultimate chain result of the generated code.  We will also add its chain
2362     // inputs as inputs to the ultimate TokenFactor we create.
2363     Result = CR_LeadsToInteriorNode;
2364     if (!Visited) {
2365       ChainedNodesInPattern.push_back(User);
2366       InteriorChainedNodes.push_back(User);
2367     }
2368   }
2369 
2370   return Result;
2371 }
2372 
2373 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2374 /// operation for when the pattern matched at least one node with a chains.  The
2375 /// input vector contains a list of all of the chained nodes that we match.  We
2376 /// must determine if this is a valid thing to cover (i.e. matching it won't
2377 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2378 /// be used as the input node chain for the generated nodes.
2379 static SDValue
2380 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2381                        SelectionDAG *CurDAG) {
2382   // Used for memoization. Without it WalkChainUsers could take exponential
2383   // time to run.
2384   DenseMap<const SDNode *, ChainResult> TokenFactorResult;
2385   // Walk all of the chained nodes we've matched, recursively scanning down the
2386   // users of the chain result. This adds any TokenFactor nodes that are caught
2387   // in between chained nodes to the chained and interior nodes list.
2388   SmallVector<SDNode*, 3> InteriorChainedNodes;
2389   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2390     if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
2391                        TokenFactorResult,
2392                        InteriorChainedNodes) == CR_InducesCycle)
2393       return SDValue(); // Would induce a cycle.
2394   }
2395 
2396   // Okay, we have walked all the matched nodes and collected TokenFactor nodes
2397   // that we are interested in.  Form our input TokenFactor node.
2398   SmallVector<SDValue, 3> InputChains;
2399   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2400     // Add the input chain of this node to the InputChains list (which will be
2401     // the operands of the generated TokenFactor) if it's not an interior node.
2402     SDNode *N = ChainNodesMatched[i];
2403     if (N->getOpcode() != ISD::TokenFactor) {
2404       if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
2405         continue;
2406 
2407       // Otherwise, add the input chain.
2408       SDValue InChain = ChainNodesMatched[i]->getOperand(0);
2409       assert(InChain.getValueType() == MVT::Other && "Not a chain");
2410       InputChains.push_back(InChain);
2411       continue;
2412     }
2413 
2414     // If we have a token factor, we want to add all inputs of the token factor
2415     // that are not part of the pattern we're matching.
2416     for (const SDValue &Op : N->op_values()) {
2417       if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
2418                       Op.getNode()))
2419         InputChains.push_back(Op);
2420     }
2421   }
2422 
2423   if (InputChains.size() == 1)
2424     return InputChains[0];
2425   return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2426                          MVT::Other, InputChains);
2427 }
2428 
2429 /// MorphNode - Handle morphing a node in place for the selector.
2430 SDNode *SelectionDAGISel::
2431 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2432           ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2433   // It is possible we're using MorphNodeTo to replace a node with no
2434   // normal results with one that has a normal result (or we could be
2435   // adding a chain) and the input could have glue and chains as well.
2436   // In this case we need to shift the operands down.
2437   // FIXME: This is a horrible hack and broken in obscure cases, no worse
2438   // than the old isel though.
2439   int OldGlueResultNo = -1, OldChainResultNo = -1;
2440 
2441   unsigned NTMNumResults = Node->getNumValues();
2442   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2443     OldGlueResultNo = NTMNumResults-1;
2444     if (NTMNumResults != 1 &&
2445         Node->getValueType(NTMNumResults-2) == MVT::Other)
2446       OldChainResultNo = NTMNumResults-2;
2447   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2448     OldChainResultNo = NTMNumResults-1;
2449 
2450   // Call the underlying SelectionDAG routine to do the transmogrification. Note
2451   // that this deletes operands of the old node that become dead.
2452   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2453 
2454   // MorphNodeTo can operate in two ways: if an existing node with the
2455   // specified operands exists, it can just return it.  Otherwise, it
2456   // updates the node in place to have the requested operands.
2457   if (Res == Node) {
2458     // If we updated the node in place, reset the node ID.  To the isel,
2459     // this should be just like a newly allocated machine node.
2460     Res->setNodeId(-1);
2461   }
2462 
2463   unsigned ResNumResults = Res->getNumValues();
2464   // Move the glue if needed.
2465   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2466       (unsigned)OldGlueResultNo != ResNumResults-1)
2467     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
2468                                       SDValue(Res, ResNumResults-1));
2469 
2470   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2471     --ResNumResults;
2472 
2473   // Move the chain reference if needed.
2474   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2475       (unsigned)OldChainResultNo != ResNumResults-1)
2476     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
2477                                       SDValue(Res, ResNumResults-1));
2478 
2479   // Otherwise, no replacement happened because the node already exists. Replace
2480   // Uses of the old node with the new one.
2481   if (Res != Node)
2482     CurDAG->ReplaceAllUsesWith(Node, Res);
2483 
2484   return Res;
2485 }
2486 
2487 /// CheckSame - Implements OP_CheckSame.
2488 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2489 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2490           SDValue N,
2491           const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2492   // Accept if it is exactly the same as a previously recorded node.
2493   unsigned RecNo = MatcherTable[MatcherIndex++];
2494   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2495   return N == RecordedNodes[RecNo].first;
2496 }
2497 
2498 /// CheckChildSame - Implements OP_CheckChildXSame.
2499 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2500 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2501              SDValue N,
2502              const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes,
2503              unsigned ChildNo) {
2504   if (ChildNo >= N.getNumOperands())
2505     return false;  // Match fails if out of range child #.
2506   return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2507                      RecordedNodes);
2508 }
2509 
2510 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2511 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2512 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2513                       const SelectionDAGISel &SDISel) {
2514   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2515 }
2516 
2517 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2518 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2519 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2520                    const SelectionDAGISel &SDISel, SDNode *N) {
2521   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2522 }
2523 
2524 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2525 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2526             SDNode *N) {
2527   uint16_t Opc = MatcherTable[MatcherIndex++];
2528   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2529   return N->getOpcode() == Opc;
2530 }
2531 
2532 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2533 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2534           const TargetLowering *TLI, const DataLayout &DL) {
2535   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2536   if (N.getValueType() == VT) return true;
2537 
2538   // Handle the case when VT is iPTR.
2539   return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2540 }
2541 
2542 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2543 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2544                SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2545                unsigned ChildNo) {
2546   if (ChildNo >= N.getNumOperands())
2547     return false;  // Match fails if out of range child #.
2548   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2549                      DL);
2550 }
2551 
2552 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2553 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2554               SDValue N) {
2555   return cast<CondCodeSDNode>(N)->get() ==
2556       (ISD::CondCode)MatcherTable[MatcherIndex++];
2557 }
2558 
2559 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2560 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2561                SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2562   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2563   if (cast<VTSDNode>(N)->getVT() == VT)
2564     return true;
2565 
2566   // Handle the case when VT is iPTR.
2567   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2568 }
2569 
2570 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2571 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2572              SDValue N) {
2573   int64_t Val = MatcherTable[MatcherIndex++];
2574   if (Val & 128)
2575     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2576 
2577   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2578   return C && C->getSExtValue() == Val;
2579 }
2580 
2581 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2582 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2583                   SDValue N, unsigned ChildNo) {
2584   if (ChildNo >= N.getNumOperands())
2585     return false;  // Match fails if out of range child #.
2586   return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2587 }
2588 
2589 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2590 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2591             SDValue N, const SelectionDAGISel &SDISel) {
2592   int64_t Val = MatcherTable[MatcherIndex++];
2593   if (Val & 128)
2594     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2595 
2596   if (N->getOpcode() != ISD::AND) return false;
2597 
2598   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2599   return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2600 }
2601 
2602 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2603 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2604            SDValue N, const SelectionDAGISel &SDISel) {
2605   int64_t Val = MatcherTable[MatcherIndex++];
2606   if (Val & 128)
2607     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2608 
2609   if (N->getOpcode() != ISD::OR) return false;
2610 
2611   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2612   return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2613 }
2614 
2615 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2616 /// scope, evaluate the current node.  If the current predicate is known to
2617 /// fail, set Result=true and return anything.  If the current predicate is
2618 /// known to pass, set Result=false and return the MatcherIndex to continue
2619 /// with.  If the current predicate is unknown, set Result=false and return the
2620 /// MatcherIndex to continue with.
2621 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2622                                        unsigned Index, SDValue N,
2623                                        bool &Result,
2624                                        const SelectionDAGISel &SDISel,
2625                  SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2626   switch (Table[Index++]) {
2627   default:
2628     Result = false;
2629     return Index-1;  // Could not evaluate this predicate.
2630   case SelectionDAGISel::OPC_CheckSame:
2631     Result = !::CheckSame(Table, Index, N, RecordedNodes);
2632     return Index;
2633   case SelectionDAGISel::OPC_CheckChild0Same:
2634   case SelectionDAGISel::OPC_CheckChild1Same:
2635   case SelectionDAGISel::OPC_CheckChild2Same:
2636   case SelectionDAGISel::OPC_CheckChild3Same:
2637     Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2638                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2639     return Index;
2640   case SelectionDAGISel::OPC_CheckPatternPredicate:
2641     Result = !::CheckPatternPredicate(Table, Index, SDISel);
2642     return Index;
2643   case SelectionDAGISel::OPC_CheckPredicate:
2644     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2645     return Index;
2646   case SelectionDAGISel::OPC_CheckOpcode:
2647     Result = !::CheckOpcode(Table, Index, N.getNode());
2648     return Index;
2649   case SelectionDAGISel::OPC_CheckType:
2650     Result = !::CheckType(Table, Index, N, SDISel.TLI,
2651                           SDISel.CurDAG->getDataLayout());
2652     return Index;
2653   case SelectionDAGISel::OPC_CheckChild0Type:
2654   case SelectionDAGISel::OPC_CheckChild1Type:
2655   case SelectionDAGISel::OPC_CheckChild2Type:
2656   case SelectionDAGISel::OPC_CheckChild3Type:
2657   case SelectionDAGISel::OPC_CheckChild4Type:
2658   case SelectionDAGISel::OPC_CheckChild5Type:
2659   case SelectionDAGISel::OPC_CheckChild6Type:
2660   case SelectionDAGISel::OPC_CheckChild7Type:
2661     Result = !::CheckChildType(
2662                  Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2663                  Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
2664     return Index;
2665   case SelectionDAGISel::OPC_CheckCondCode:
2666     Result = !::CheckCondCode(Table, Index, N);
2667     return Index;
2668   case SelectionDAGISel::OPC_CheckValueType:
2669     Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2670                                SDISel.CurDAG->getDataLayout());
2671     return Index;
2672   case SelectionDAGISel::OPC_CheckInteger:
2673     Result = !::CheckInteger(Table, Index, N);
2674     return Index;
2675   case SelectionDAGISel::OPC_CheckChild0Integer:
2676   case SelectionDAGISel::OPC_CheckChild1Integer:
2677   case SelectionDAGISel::OPC_CheckChild2Integer:
2678   case SelectionDAGISel::OPC_CheckChild3Integer:
2679   case SelectionDAGISel::OPC_CheckChild4Integer:
2680     Result = !::CheckChildInteger(Table, Index, N,
2681                      Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2682     return Index;
2683   case SelectionDAGISel::OPC_CheckAndImm:
2684     Result = !::CheckAndImm(Table, Index, N, SDISel);
2685     return Index;
2686   case SelectionDAGISel::OPC_CheckOrImm:
2687     Result = !::CheckOrImm(Table, Index, N, SDISel);
2688     return Index;
2689   }
2690 }
2691 
2692 namespace {
2693 struct MatchScope {
2694   /// FailIndex - If this match fails, this is the index to continue with.
2695   unsigned FailIndex;
2696 
2697   /// NodeStack - The node stack when the scope was formed.
2698   SmallVector<SDValue, 4> NodeStack;
2699 
2700   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2701   unsigned NumRecordedNodes;
2702 
2703   /// NumMatchedMemRefs - The number of matched memref entries.
2704   unsigned NumMatchedMemRefs;
2705 
2706   /// InputChain/InputGlue - The current chain/glue
2707   SDValue InputChain, InputGlue;
2708 
2709   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2710   bool HasChainNodesMatched, HasGlueResultNodesMatched;
2711 };
2712 
2713 /// \\brief A DAG update listener to keep the matching state
2714 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2715 /// change the DAG while matching.  X86 addressing mode matcher is an example
2716 /// for this.
2717 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2718 {
2719       SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes;
2720       SmallVectorImpl<MatchScope> &MatchScopes;
2721 public:
2722   MatchStateUpdater(SelectionDAG &DAG,
2723                     SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN,
2724                     SmallVectorImpl<MatchScope> &MS) :
2725     SelectionDAG::DAGUpdateListener(DAG),
2726     RecordedNodes(RN), MatchScopes(MS) { }
2727 
2728   void NodeDeleted(SDNode *N, SDNode *E) override {
2729     // Some early-returns here to avoid the search if we deleted the node or
2730     // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2731     // do, so it's unnecessary to update matching state at that point).
2732     // Neither of these can occur currently because we only install this
2733     // update listener during matching a complex patterns.
2734     if (!E || E->isMachineOpcode())
2735       return;
2736     // Performing linear search here does not matter because we almost never
2737     // run this code.  You'd have to have a CSE during complex pattern
2738     // matching.
2739     for (auto &I : RecordedNodes)
2740       if (I.first.getNode() == N)
2741         I.first.setNode(E);
2742 
2743     for (auto &I : MatchScopes)
2744       for (auto &J : I.NodeStack)
2745         if (J.getNode() == N)
2746           J.setNode(E);
2747   }
2748 };
2749 } // end anonymous namespace
2750 
2751 SDNode *SelectionDAGISel::
2752 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2753                  unsigned TableSize) {
2754   // FIXME: Should these even be selected?  Handle these cases in the caller?
2755   switch (NodeToMatch->getOpcode()) {
2756   default:
2757     break;
2758   case ISD::EntryToken:       // These nodes remain the same.
2759   case ISD::BasicBlock:
2760   case ISD::Register:
2761   case ISD::RegisterMask:
2762   case ISD::HANDLENODE:
2763   case ISD::MDNODE_SDNODE:
2764   case ISD::TargetConstant:
2765   case ISD::TargetConstantFP:
2766   case ISD::TargetConstantPool:
2767   case ISD::TargetFrameIndex:
2768   case ISD::TargetExternalSymbol:
2769   case ISD::MCSymbol:
2770   case ISD::TargetBlockAddress:
2771   case ISD::TargetJumpTable:
2772   case ISD::TargetGlobalTLSAddress:
2773   case ISD::TargetGlobalAddress:
2774   case ISD::TokenFactor:
2775   case ISD::CopyFromReg:
2776   case ISD::CopyToReg:
2777   case ISD::EH_LABEL:
2778   case ISD::LIFETIME_START:
2779   case ISD::LIFETIME_END:
2780     NodeToMatch->setNodeId(-1); // Mark selected.
2781     return nullptr;
2782   case ISD::AssertSext:
2783   case ISD::AssertZext:
2784     CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2785                                       NodeToMatch->getOperand(0));
2786     return nullptr;
2787   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2788   case ISD::READ_REGISTER: return Select_READ_REGISTER(NodeToMatch);
2789   case ISD::WRITE_REGISTER: return Select_WRITE_REGISTER(NodeToMatch);
2790   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
2791   }
2792 
2793   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2794 
2795   // Set up the node stack with NodeToMatch as the only node on the stack.
2796   SmallVector<SDValue, 8> NodeStack;
2797   SDValue N = SDValue(NodeToMatch, 0);
2798   NodeStack.push_back(N);
2799 
2800   // MatchScopes - Scopes used when matching, if a match failure happens, this
2801   // indicates where to continue checking.
2802   SmallVector<MatchScope, 8> MatchScopes;
2803 
2804   // RecordedNodes - This is the set of nodes that have been recorded by the
2805   // state machine.  The second value is the parent of the node, or null if the
2806   // root is recorded.
2807   SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2808 
2809   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2810   // pattern.
2811   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2812 
2813   // These are the current input chain and glue for use when generating nodes.
2814   // Various Emit operations change these.  For example, emitting a copytoreg
2815   // uses and updates these.
2816   SDValue InputChain, InputGlue;
2817 
2818   // ChainNodesMatched - If a pattern matches nodes that have input/output
2819   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2820   // which ones they are.  The result is captured into this list so that we can
2821   // update the chain results when the pattern is complete.
2822   SmallVector<SDNode*, 3> ChainNodesMatched;
2823   SmallVector<SDNode*, 3> GlueResultNodesMatched;
2824 
2825   DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2826         NodeToMatch->dump(CurDAG);
2827         dbgs() << '\n');
2828 
2829   // Determine where to start the interpreter.  Normally we start at opcode #0,
2830   // but if the state machine starts with an OPC_SwitchOpcode, then we
2831   // accelerate the first lookup (which is guaranteed to be hot) with the
2832   // OpcodeOffset table.
2833   unsigned MatcherIndex = 0;
2834 
2835   if (!OpcodeOffset.empty()) {
2836     // Already computed the OpcodeOffset table, just index into it.
2837     if (N.getOpcode() < OpcodeOffset.size())
2838       MatcherIndex = OpcodeOffset[N.getOpcode()];
2839     DEBUG(dbgs() << "  Initial Opcode index to " << MatcherIndex << "\n");
2840 
2841   } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2842     // Otherwise, the table isn't computed, but the state machine does start
2843     // with an OPC_SwitchOpcode instruction.  Populate the table now, since this
2844     // is the first time we're selecting an instruction.
2845     unsigned Idx = 1;
2846     while (1) {
2847       // Get the size of this case.
2848       unsigned CaseSize = MatcherTable[Idx++];
2849       if (CaseSize & 128)
2850         CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2851       if (CaseSize == 0) break;
2852 
2853       // Get the opcode, add the index to the table.
2854       uint16_t Opc = MatcherTable[Idx++];
2855       Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2856       if (Opc >= OpcodeOffset.size())
2857         OpcodeOffset.resize((Opc+1)*2);
2858       OpcodeOffset[Opc] = Idx;
2859       Idx += CaseSize;
2860     }
2861 
2862     // Okay, do the lookup for the first opcode.
2863     if (N.getOpcode() < OpcodeOffset.size())
2864       MatcherIndex = OpcodeOffset[N.getOpcode()];
2865   }
2866 
2867   while (1) {
2868     assert(MatcherIndex < TableSize && "Invalid index");
2869 #ifndef NDEBUG
2870     unsigned CurrentOpcodeIndex = MatcherIndex;
2871 #endif
2872     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2873     switch (Opcode) {
2874     case OPC_Scope: {
2875       // Okay, the semantics of this operation are that we should push a scope
2876       // then evaluate the first child.  However, pushing a scope only to have
2877       // the first check fail (which then pops it) is inefficient.  If we can
2878       // determine immediately that the first check (or first several) will
2879       // immediately fail, don't even bother pushing a scope for them.
2880       unsigned FailIndex;
2881 
2882       while (1) {
2883         unsigned NumToSkip = MatcherTable[MatcherIndex++];
2884         if (NumToSkip & 128)
2885           NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2886         // Found the end of the scope with no match.
2887         if (NumToSkip == 0) {
2888           FailIndex = 0;
2889           break;
2890         }
2891 
2892         FailIndex = MatcherIndex+NumToSkip;
2893 
2894         unsigned MatcherIndexOfPredicate = MatcherIndex;
2895         (void)MatcherIndexOfPredicate; // silence warning.
2896 
2897         // If we can't evaluate this predicate without pushing a scope (e.g. if
2898         // it is a 'MoveParent') or if the predicate succeeds on this node, we
2899         // push the scope and evaluate the full predicate chain.
2900         bool Result;
2901         MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2902                                               Result, *this, RecordedNodes);
2903         if (!Result)
2904           break;
2905 
2906         DEBUG(dbgs() << "  Skipped scope entry (due to false predicate) at "
2907                      << "index " << MatcherIndexOfPredicate
2908                      << ", continuing at " << FailIndex << "\n");
2909         ++NumDAGIselRetries;
2910 
2911         // Otherwise, we know that this case of the Scope is guaranteed to fail,
2912         // move to the next case.
2913         MatcherIndex = FailIndex;
2914       }
2915 
2916       // If the whole scope failed to match, bail.
2917       if (FailIndex == 0) break;
2918 
2919       // Push a MatchScope which indicates where to go if the first child fails
2920       // to match.
2921       MatchScope NewEntry;
2922       NewEntry.FailIndex = FailIndex;
2923       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2924       NewEntry.NumRecordedNodes = RecordedNodes.size();
2925       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2926       NewEntry.InputChain = InputChain;
2927       NewEntry.InputGlue = InputGlue;
2928       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2929       NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2930       MatchScopes.push_back(NewEntry);
2931       continue;
2932     }
2933     case OPC_RecordNode: {
2934       // Remember this node, it may end up being an operand in the pattern.
2935       SDNode *Parent = nullptr;
2936       if (NodeStack.size() > 1)
2937         Parent = NodeStack[NodeStack.size()-2].getNode();
2938       RecordedNodes.push_back(std::make_pair(N, Parent));
2939       continue;
2940     }
2941 
2942     case OPC_RecordChild0: case OPC_RecordChild1:
2943     case OPC_RecordChild2: case OPC_RecordChild3:
2944     case OPC_RecordChild4: case OPC_RecordChild5:
2945     case OPC_RecordChild6: case OPC_RecordChild7: {
2946       unsigned ChildNo = Opcode-OPC_RecordChild0;
2947       if (ChildNo >= N.getNumOperands())
2948         break;  // Match fails if out of range child #.
2949 
2950       RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2951                                              N.getNode()));
2952       continue;
2953     }
2954     case OPC_RecordMemRef:
2955       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2956       continue;
2957 
2958     case OPC_CaptureGlueInput:
2959       // If the current node has an input glue, capture it in InputGlue.
2960       if (N->getNumOperands() != 0 &&
2961           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2962         InputGlue = N->getOperand(N->getNumOperands()-1);
2963       continue;
2964 
2965     case OPC_MoveChild: {
2966       unsigned ChildNo = MatcherTable[MatcherIndex++];
2967       if (ChildNo >= N.getNumOperands())
2968         break;  // Match fails if out of range child #.
2969       N = N.getOperand(ChildNo);
2970       NodeStack.push_back(N);
2971       continue;
2972     }
2973 
2974     case OPC_MoveParent:
2975       // Pop the current node off the NodeStack.
2976       NodeStack.pop_back();
2977       assert(!NodeStack.empty() && "Node stack imbalance!");
2978       N = NodeStack.back();
2979       continue;
2980 
2981     case OPC_CheckSame:
2982       if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2983       continue;
2984 
2985     case OPC_CheckChild0Same: case OPC_CheckChild1Same:
2986     case OPC_CheckChild2Same: case OPC_CheckChild3Same:
2987       if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
2988                             Opcode-OPC_CheckChild0Same))
2989         break;
2990       continue;
2991 
2992     case OPC_CheckPatternPredicate:
2993       if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2994       continue;
2995     case OPC_CheckPredicate:
2996       if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2997                                 N.getNode()))
2998         break;
2999       continue;
3000     case OPC_CheckComplexPat: {
3001       unsigned CPNum = MatcherTable[MatcherIndex++];
3002       unsigned RecNo = MatcherTable[MatcherIndex++];
3003       assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3004 
3005       // If target can modify DAG during matching, keep the matching state
3006       // consistent.
3007       std::unique_ptr<MatchStateUpdater> MSU;
3008       if (ComplexPatternFuncMutatesDAG())
3009         MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes,
3010                                         MatchScopes));
3011 
3012       if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3013                                RecordedNodes[RecNo].first, CPNum,
3014                                RecordedNodes))
3015         break;
3016       continue;
3017     }
3018     case OPC_CheckOpcode:
3019       if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3020       continue;
3021 
3022     case OPC_CheckType:
3023       if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3024                        CurDAG->getDataLayout()))
3025         break;
3026       continue;
3027 
3028     case OPC_SwitchOpcode: {
3029       unsigned CurNodeOpcode = N.getOpcode();
3030       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3031       unsigned CaseSize;
3032       while (1) {
3033         // Get the size of this case.
3034         CaseSize = MatcherTable[MatcherIndex++];
3035         if (CaseSize & 128)
3036           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3037         if (CaseSize == 0) break;
3038 
3039         uint16_t Opc = MatcherTable[MatcherIndex++];
3040         Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3041 
3042         // If the opcode matches, then we will execute this case.
3043         if (CurNodeOpcode == Opc)
3044           break;
3045 
3046         // Otherwise, skip over this case.
3047         MatcherIndex += CaseSize;
3048       }
3049 
3050       // If no cases matched, bail out.
3051       if (CaseSize == 0) break;
3052 
3053       // Otherwise, execute the case we found.
3054       DEBUG(dbgs() << "  OpcodeSwitch from " << SwitchStart
3055                    << " to " << MatcherIndex << "\n");
3056       continue;
3057     }
3058 
3059     case OPC_SwitchType: {
3060       MVT CurNodeVT = N.getSimpleValueType();
3061       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3062       unsigned CaseSize;
3063       while (1) {
3064         // Get the size of this case.
3065         CaseSize = MatcherTable[MatcherIndex++];
3066         if (CaseSize & 128)
3067           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3068         if (CaseSize == 0) break;
3069 
3070         MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3071         if (CaseVT == MVT::iPTR)
3072           CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3073 
3074         // If the VT matches, then we will execute this case.
3075         if (CurNodeVT == CaseVT)
3076           break;
3077 
3078         // Otherwise, skip over this case.
3079         MatcherIndex += CaseSize;
3080       }
3081 
3082       // If no cases matched, bail out.
3083       if (CaseSize == 0) break;
3084 
3085       // Otherwise, execute the case we found.
3086       DEBUG(dbgs() << "  TypeSwitch[" << EVT(CurNodeVT).getEVTString()
3087                    << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
3088       continue;
3089     }
3090     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
3091     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
3092     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
3093     case OPC_CheckChild6Type: case OPC_CheckChild7Type:
3094       if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3095                             CurDAG->getDataLayout(),
3096                             Opcode - OPC_CheckChild0Type))
3097         break;
3098       continue;
3099     case OPC_CheckCondCode:
3100       if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3101       continue;
3102     case OPC_CheckValueType:
3103       if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3104                             CurDAG->getDataLayout()))
3105         break;
3106       continue;
3107     case OPC_CheckInteger:
3108       if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3109       continue;
3110     case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
3111     case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
3112     case OPC_CheckChild4Integer:
3113       if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3114                                Opcode-OPC_CheckChild0Integer)) break;
3115       continue;
3116     case OPC_CheckAndImm:
3117       if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3118       continue;
3119     case OPC_CheckOrImm:
3120       if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3121       continue;
3122 
3123     case OPC_CheckFoldableChainNode: {
3124       assert(NodeStack.size() != 1 && "No parent node");
3125       // Verify that all intermediate nodes between the root and this one have
3126       // a single use.
3127       bool HasMultipleUses = false;
3128       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
3129         if (!NodeStack[i].hasOneUse()) {
3130           HasMultipleUses = true;
3131           break;
3132         }
3133       if (HasMultipleUses) break;
3134 
3135       // Check to see that the target thinks this is profitable to fold and that
3136       // we can fold it without inducing cycles in the graph.
3137       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3138                               NodeToMatch) ||
3139           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3140                          NodeToMatch, OptLevel,
3141                          true/*We validate our own chains*/))
3142         break;
3143 
3144       continue;
3145     }
3146     case OPC_EmitInteger: {
3147       MVT::SimpleValueType VT =
3148         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3149       int64_t Val = MatcherTable[MatcherIndex++];
3150       if (Val & 128)
3151         Val = GetVBR(Val, MatcherTable, MatcherIndex);
3152       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3153                               CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3154                                                         VT), nullptr));
3155       continue;
3156     }
3157     case OPC_EmitRegister: {
3158       MVT::SimpleValueType VT =
3159         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3160       unsigned RegNo = MatcherTable[MatcherIndex++];
3161       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3162                               CurDAG->getRegister(RegNo, VT), nullptr));
3163       continue;
3164     }
3165     case OPC_EmitRegister2: {
3166       // For targets w/ more than 256 register names, the register enum
3167       // values are stored in two bytes in the matcher table (just like
3168       // opcodes).
3169       MVT::SimpleValueType VT =
3170         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3171       unsigned RegNo = MatcherTable[MatcherIndex++];
3172       RegNo |= MatcherTable[MatcherIndex++] << 8;
3173       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3174                               CurDAG->getRegister(RegNo, VT), nullptr));
3175       continue;
3176     }
3177 
3178     case OPC_EmitConvertToTarget:  {
3179       // Convert from IMM/FPIMM to target version.
3180       unsigned RecNo = MatcherTable[MatcherIndex++];
3181       assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3182       SDValue Imm = RecordedNodes[RecNo].first;
3183 
3184       if (Imm->getOpcode() == ISD::Constant) {
3185         const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3186         Imm = CurDAG->getConstant(*Val, SDLoc(NodeToMatch), Imm.getValueType(),
3187                                   true);
3188       } else if (Imm->getOpcode() == ISD::ConstantFP) {
3189         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3190         Imm = CurDAG->getConstantFP(*Val, SDLoc(NodeToMatch),
3191                                     Imm.getValueType(), true);
3192       }
3193 
3194       RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3195       continue;
3196     }
3197 
3198     case OPC_EmitMergeInputChains1_0:    // OPC_EmitMergeInputChains, 1, 0
3199     case OPC_EmitMergeInputChains1_1:    // OPC_EmitMergeInputChains, 1, 1
3200     case OPC_EmitMergeInputChains1_2: {  // OPC_EmitMergeInputChains, 1, 2
3201       // These are space-optimized forms of OPC_EmitMergeInputChains.
3202       assert(!InputChain.getNode() &&
3203              "EmitMergeInputChains should be the first chain producing node");
3204       assert(ChainNodesMatched.empty() &&
3205              "Should only have one EmitMergeInputChains per match");
3206 
3207       // Read all of the chained nodes.
3208       unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3209       assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3210       ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3211 
3212       // FIXME: What if other value results of the node have uses not matched
3213       // by this pattern?
3214       if (ChainNodesMatched.back() != NodeToMatch &&
3215           !RecordedNodes[RecNo].first.hasOneUse()) {
3216         ChainNodesMatched.clear();
3217         break;
3218       }
3219 
3220       // Merge the input chains if they are not intra-pattern references.
3221       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3222 
3223       if (!InputChain.getNode())
3224         break;  // Failed to merge.
3225       continue;
3226     }
3227 
3228     case OPC_EmitMergeInputChains: {
3229       assert(!InputChain.getNode() &&
3230              "EmitMergeInputChains should be the first chain producing node");
3231       // This node gets a list of nodes we matched in the input that have
3232       // chains.  We want to token factor all of the input chains to these nodes
3233       // together.  However, if any of the input chains is actually one of the
3234       // nodes matched in this pattern, then we have an intra-match reference.
3235       // Ignore these because the newly token factored chain should not refer to
3236       // the old nodes.
3237       unsigned NumChains = MatcherTable[MatcherIndex++];
3238       assert(NumChains != 0 && "Can't TF zero chains");
3239 
3240       assert(ChainNodesMatched.empty() &&
3241              "Should only have one EmitMergeInputChains per match");
3242 
3243       // Read all of the chained nodes.
3244       for (unsigned i = 0; i != NumChains; ++i) {
3245         unsigned RecNo = MatcherTable[MatcherIndex++];
3246         assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3247         ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3248 
3249         // FIXME: What if other value results of the node have uses not matched
3250         // by this pattern?
3251         if (ChainNodesMatched.back() != NodeToMatch &&
3252             !RecordedNodes[RecNo].first.hasOneUse()) {
3253           ChainNodesMatched.clear();
3254           break;
3255         }
3256       }
3257 
3258       // If the inner loop broke out, the match fails.
3259       if (ChainNodesMatched.empty())
3260         break;
3261 
3262       // Merge the input chains if they are not intra-pattern references.
3263       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3264 
3265       if (!InputChain.getNode())
3266         break;  // Failed to merge.
3267 
3268       continue;
3269     }
3270 
3271     case OPC_EmitCopyToReg: {
3272       unsigned RecNo = MatcherTable[MatcherIndex++];
3273       assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3274       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3275 
3276       if (!InputChain.getNode())
3277         InputChain = CurDAG->getEntryNode();
3278 
3279       InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3280                                         DestPhysReg, RecordedNodes[RecNo].first,
3281                                         InputGlue);
3282 
3283       InputGlue = InputChain.getValue(1);
3284       continue;
3285     }
3286 
3287     case OPC_EmitNodeXForm: {
3288       unsigned XFormNo = MatcherTable[MatcherIndex++];
3289       unsigned RecNo = MatcherTable[MatcherIndex++];
3290       assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3291       SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3292       RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3293       continue;
3294     }
3295 
3296     case OPC_EmitNode:
3297     case OPC_MorphNodeTo: {
3298       uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3299       TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3300       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3301       // Get the result VT list.
3302       unsigned NumVTs = MatcherTable[MatcherIndex++];
3303       SmallVector<EVT, 4> VTs;
3304       for (unsigned i = 0; i != NumVTs; ++i) {
3305         MVT::SimpleValueType VT =
3306           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3307         if (VT == MVT::iPTR)
3308           VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3309         VTs.push_back(VT);
3310       }
3311 
3312       if (EmitNodeInfo & OPFL_Chain)
3313         VTs.push_back(MVT::Other);
3314       if (EmitNodeInfo & OPFL_GlueOutput)
3315         VTs.push_back(MVT::Glue);
3316 
3317       // This is hot code, so optimize the two most common cases of 1 and 2
3318       // results.
3319       SDVTList VTList;
3320       if (VTs.size() == 1)
3321         VTList = CurDAG->getVTList(VTs[0]);
3322       else if (VTs.size() == 2)
3323         VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3324       else
3325         VTList = CurDAG->getVTList(VTs);
3326 
3327       // Get the operand list.
3328       unsigned NumOps = MatcherTable[MatcherIndex++];
3329       SmallVector<SDValue, 8> Ops;
3330       for (unsigned i = 0; i != NumOps; ++i) {
3331         unsigned RecNo = MatcherTable[MatcherIndex++];
3332         if (RecNo & 128)
3333           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3334 
3335         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3336         Ops.push_back(RecordedNodes[RecNo].first);
3337       }
3338 
3339       // If there are variadic operands to add, handle them now.
3340       if (EmitNodeInfo & OPFL_VariadicInfo) {
3341         // Determine the start index to copy from.
3342         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3343         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3344         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3345                "Invalid variadic node");
3346         // Copy all of the variadic operands, not including a potential glue
3347         // input.
3348         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3349              i != e; ++i) {
3350           SDValue V = NodeToMatch->getOperand(i);
3351           if (V.getValueType() == MVT::Glue) break;
3352           Ops.push_back(V);
3353         }
3354       }
3355 
3356       // If this has chain/glue inputs, add them.
3357       if (EmitNodeInfo & OPFL_Chain)
3358         Ops.push_back(InputChain);
3359       if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3360         Ops.push_back(InputGlue);
3361 
3362       // Create the node.
3363       SDNode *Res = nullptr;
3364       if (Opcode != OPC_MorphNodeTo) {
3365         // If this is a normal EmitNode command, just create the new node and
3366         // add the results to the RecordedNodes list.
3367         Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3368                                      VTList, Ops);
3369 
3370         // Add all the non-glue/non-chain results to the RecordedNodes list.
3371         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3372           if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3373           RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3374                                                              nullptr));
3375         }
3376 
3377       } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
3378         Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
3379       } else {
3380         // NodeToMatch was eliminated by CSE when the target changed the DAG.
3381         // We will visit the equivalent node later.
3382         DEBUG(dbgs() << "Node was eliminated by CSE\n");
3383         return nullptr;
3384       }
3385 
3386       // If the node had chain/glue results, update our notion of the current
3387       // chain and glue.
3388       if (EmitNodeInfo & OPFL_GlueOutput) {
3389         InputGlue = SDValue(Res, VTs.size()-1);
3390         if (EmitNodeInfo & OPFL_Chain)
3391           InputChain = SDValue(Res, VTs.size()-2);
3392       } else if (EmitNodeInfo & OPFL_Chain)
3393         InputChain = SDValue(Res, VTs.size()-1);
3394 
3395       // If the OPFL_MemRefs glue is set on this node, slap all of the
3396       // accumulated memrefs onto it.
3397       //
3398       // FIXME: This is vastly incorrect for patterns with multiple outputs
3399       // instructions that access memory and for ComplexPatterns that match
3400       // loads.
3401       if (EmitNodeInfo & OPFL_MemRefs) {
3402         // Only attach load or store memory operands if the generated
3403         // instruction may load or store.
3404         const MCInstrDesc &MCID = TII->get(TargetOpc);
3405         bool mayLoad = MCID.mayLoad();
3406         bool mayStore = MCID.mayStore();
3407 
3408         unsigned NumMemRefs = 0;
3409         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3410                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3411           if ((*I)->isLoad()) {
3412             if (mayLoad)
3413               ++NumMemRefs;
3414           } else if ((*I)->isStore()) {
3415             if (mayStore)
3416               ++NumMemRefs;
3417           } else {
3418             ++NumMemRefs;
3419           }
3420         }
3421 
3422         MachineSDNode::mmo_iterator MemRefs =
3423           MF->allocateMemRefsArray(NumMemRefs);
3424 
3425         MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
3426         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3427                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3428           if ((*I)->isLoad()) {
3429             if (mayLoad)
3430               *MemRefsPos++ = *I;
3431           } else if ((*I)->isStore()) {
3432             if (mayStore)
3433               *MemRefsPos++ = *I;
3434           } else {
3435             *MemRefsPos++ = *I;
3436           }
3437         }
3438 
3439         cast<MachineSDNode>(Res)
3440           ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
3441       }
3442 
3443       DEBUG(dbgs() << "  "
3444                    << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
3445                    << " node: "; Res->dump(CurDAG); dbgs() << "\n");
3446 
3447       // If this was a MorphNodeTo then we're completely done!
3448       if (Opcode == OPC_MorphNodeTo) {
3449         // Update chain and glue uses.
3450         UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
3451                             InputGlue, GlueResultNodesMatched, true);
3452         return Res;
3453       }
3454       continue;
3455     }
3456 
3457     case OPC_MarkGlueResults: {
3458       unsigned NumNodes = MatcherTable[MatcherIndex++];
3459 
3460       // Read and remember all the glue-result nodes.
3461       for (unsigned i = 0; i != NumNodes; ++i) {
3462         unsigned RecNo = MatcherTable[MatcherIndex++];
3463         if (RecNo & 128)
3464           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3465 
3466         assert(RecNo < RecordedNodes.size() && "Invalid MarkGlueResults");
3467         GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3468       }
3469       continue;
3470     }
3471 
3472     case OPC_CompleteMatch: {
3473       // The match has been completed, and any new nodes (if any) have been
3474       // created.  Patch up references to the matched dag to use the newly
3475       // created nodes.
3476       unsigned NumResults = MatcherTable[MatcherIndex++];
3477 
3478       for (unsigned i = 0; i != NumResults; ++i) {
3479         unsigned ResSlot = MatcherTable[MatcherIndex++];
3480         if (ResSlot & 128)
3481           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3482 
3483         assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3484         SDValue Res = RecordedNodes[ResSlot].first;
3485 
3486         assert(i < NodeToMatch->getNumValues() &&
3487                NodeToMatch->getValueType(i) != MVT::Other &&
3488                NodeToMatch->getValueType(i) != MVT::Glue &&
3489                "Invalid number of results to complete!");
3490         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3491                 NodeToMatch->getValueType(i) == MVT::iPTR ||
3492                 Res.getValueType() == MVT::iPTR ||
3493                 NodeToMatch->getValueType(i).getSizeInBits() ==
3494                     Res.getValueType().getSizeInBits()) &&
3495                "invalid replacement");
3496         CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
3497       }
3498 
3499       // If the root node defines glue, add it to the glue nodes to update list.
3500       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
3501         GlueResultNodesMatched.push_back(NodeToMatch);
3502 
3503       // Update chain and glue uses.
3504       UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
3505                           InputGlue, GlueResultNodesMatched, false);
3506 
3507       assert(NodeToMatch->use_empty() &&
3508              "Didn't replace all uses of the node?");
3509 
3510       // FIXME: We just return here, which interacts correctly with SelectRoot
3511       // above.  We should fix this to not return an SDNode* anymore.
3512       return nullptr;
3513     }
3514     }
3515 
3516     // If the code reached this point, then the match failed.  See if there is
3517     // another child to try in the current 'Scope', otherwise pop it until we
3518     // find a case to check.
3519     DEBUG(dbgs() << "  Match failed at index " << CurrentOpcodeIndex << "\n");
3520     ++NumDAGIselRetries;
3521     while (1) {
3522       if (MatchScopes.empty()) {
3523         CannotYetSelect(NodeToMatch);
3524         return nullptr;
3525       }
3526 
3527       // Restore the interpreter state back to the point where the scope was
3528       // formed.
3529       MatchScope &LastScope = MatchScopes.back();
3530       RecordedNodes.resize(LastScope.NumRecordedNodes);
3531       NodeStack.clear();
3532       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3533       N = NodeStack.back();
3534 
3535       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3536         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3537       MatcherIndex = LastScope.FailIndex;
3538 
3539       DEBUG(dbgs() << "  Continuing at " << MatcherIndex << "\n");
3540 
3541       InputChain = LastScope.InputChain;
3542       InputGlue = LastScope.InputGlue;
3543       if (!LastScope.HasChainNodesMatched)
3544         ChainNodesMatched.clear();
3545       if (!LastScope.HasGlueResultNodesMatched)
3546         GlueResultNodesMatched.clear();
3547 
3548       // Check to see what the offset is at the new MatcherIndex.  If it is zero
3549       // we have reached the end of this scope, otherwise we have another child
3550       // in the current scope to try.
3551       unsigned NumToSkip = MatcherTable[MatcherIndex++];
3552       if (NumToSkip & 128)
3553         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3554 
3555       // If we have another child in this scope to match, update FailIndex and
3556       // try it.
3557       if (NumToSkip != 0) {
3558         LastScope.FailIndex = MatcherIndex+NumToSkip;
3559         break;
3560       }
3561 
3562       // End of this scope, pop it and try the next child in the containing
3563       // scope.
3564       MatchScopes.pop_back();
3565     }
3566   }
3567 }
3568 
3569 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3570   std::string msg;
3571   raw_string_ostream Msg(msg);
3572   Msg << "Cannot select: ";
3573 
3574   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3575       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3576       N->getOpcode() != ISD::INTRINSIC_VOID) {
3577     N->printrFull(Msg, CurDAG);
3578     Msg << "\nIn function: " << MF->getName();
3579   } else {
3580     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3581     unsigned iid =
3582       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3583     if (iid < Intrinsic::num_intrinsics)
3584       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
3585     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3586       Msg << "target intrinsic %" << TII->getName(iid);
3587     else
3588       Msg << "unknown intrinsic #" << iid;
3589   }
3590   report_fatal_error(Msg.str());
3591 }
3592 
3593 char SelectionDAGISel::ID = 0;
3594