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