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