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