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