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