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