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