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