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