s/class Metadata/class MetadataContext/g
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/DebugInfo.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineJumpTableInfo.h"
37 #include "llvm/CodeGen/MachineModuleInfo.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
40 #include "llvm/CodeGen/SchedulerRegistry.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/DwarfWriter.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Target/TargetFrameInfo.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/Timer.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 using namespace llvm;
58
59 static cl::opt<bool>
60 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
61 static cl::opt<bool>
62 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
63           cl::desc("Enable verbose messages in the \"fast\" "
64                    "instruction selector"));
65 static cl::opt<bool>
66 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
67           cl::desc("Enable abort calls when \"fast\" instruction fails"));
68 static cl::opt<bool>
69 SchedLiveInCopies("schedule-livein-copies",
70                   cl::desc("Schedule copies of livein registers"),
71                   cl::init(false));
72
73 #ifndef NDEBUG
74 static cl::opt<bool>
75 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
76           cl::desc("Pop up a window to show dags before the first "
77                    "dag combine pass"));
78 static cl::opt<bool>
79 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
80           cl::desc("Pop up a window to show dags before legalize types"));
81 static cl::opt<bool>
82 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
83           cl::desc("Pop up a window to show dags before legalize"));
84 static cl::opt<bool>
85 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
86           cl::desc("Pop up a window to show dags before the second "
87                    "dag combine pass"));
88 static cl::opt<bool>
89 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
90           cl::desc("Pop up a window to show dags before the post legalize types"
91                    " dag combine pass"));
92 static cl::opt<bool>
93 ViewISelDAGs("view-isel-dags", cl::Hidden,
94           cl::desc("Pop up a window to show isel dags as they are selected"));
95 static cl::opt<bool>
96 ViewSchedDAGs("view-sched-dags", cl::Hidden,
97           cl::desc("Pop up a window to show sched dags as they are processed"));
98 static cl::opt<bool>
99 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
100       cl::desc("Pop up a window to show SUnit dags after they are processed"));
101 #else
102 static const bool ViewDAGCombine1 = false,
103                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
104                   ViewDAGCombine2 = false,
105                   ViewDAGCombineLT = false,
106                   ViewISelDAGs = false, ViewSchedDAGs = false,
107                   ViewSUnitDAGs = false;
108 #endif
109
110 //===---------------------------------------------------------------------===//
111 ///
112 /// RegisterScheduler class - Track the registration of instruction schedulers.
113 ///
114 //===---------------------------------------------------------------------===//
115 MachinePassRegistry RegisterScheduler::Registry;
116
117 //===---------------------------------------------------------------------===//
118 ///
119 /// ISHeuristic command line option for instruction schedulers.
120 ///
121 //===---------------------------------------------------------------------===//
122 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
123                RegisterPassParser<RegisterScheduler> >
124 ISHeuristic("pre-RA-sched",
125             cl::init(&createDefaultScheduler),
126             cl::desc("Instruction schedulers available (before register"
127                      " allocation):"));
128
129 static RegisterScheduler
130 defaultListDAGScheduler("default", "Best scheduler for the target",
131                         createDefaultScheduler);
132
133 namespace llvm {
134   //===--------------------------------------------------------------------===//
135   /// createDefaultScheduler - This creates an instruction scheduler appropriate
136   /// for the target.
137   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
138                                              CodeGenOpt::Level OptLevel) {
139     const TargetLowering &TLI = IS->getTargetLowering();
140
141     if (OptLevel == CodeGenOpt::None)
142       return createFastDAGScheduler(IS, OptLevel);
143     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
144       return createTDListDAGScheduler(IS, OptLevel);
145     assert(TLI.getSchedulingPreference() ==
146          TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
147     return createBURRListDAGScheduler(IS, OptLevel);
148   }
149 }
150
151 // EmitInstrWithCustomInserter - This method should be implemented by targets
152 // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
153 // instructions are special in various ways, which require special support to
154 // insert.  The specified MachineInstr is created but not inserted into any
155 // basic blocks, and the scheduler passes ownership of it to this method.
156 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
157                                                          MachineBasicBlock *MBB,
158                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
159 #ifndef NDEBUG
160   errs() << "If a target marks an instruction with "
161           "'usesCustomDAGSchedInserter', it must implement "
162           "TargetLowering::EmitInstrWithCustomInserter!";
163 #endif
164   llvm_unreachable(0);
165   return 0;
166 }
167
168 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
169 /// physical register has only a single copy use, then coalesced the copy
170 /// if possible.
171 static void EmitLiveInCopy(MachineBasicBlock *MBB,
172                            MachineBasicBlock::iterator &InsertPos,
173                            unsigned VirtReg, unsigned PhysReg,
174                            const TargetRegisterClass *RC,
175                            DenseMap<MachineInstr*, unsigned> &CopyRegMap,
176                            const MachineRegisterInfo &MRI,
177                            const TargetRegisterInfo &TRI,
178                            const TargetInstrInfo &TII) {
179   unsigned NumUses = 0;
180   MachineInstr *UseMI = NULL;
181   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
182          UE = MRI.use_end(); UI != UE; ++UI) {
183     UseMI = &*UI;
184     if (++NumUses > 1)
185       break;
186   }
187
188   // If the number of uses is not one, or the use is not a move instruction,
189   // don't coalesce. Also, only coalesce away a virtual register to virtual
190   // register copy.
191   bool Coalesced = false;
192   unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
193   if (NumUses == 1 &&
194       TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
195       TargetRegisterInfo::isVirtualRegister(DstReg)) {
196     VirtReg = DstReg;
197     Coalesced = true;
198   }
199
200   // Now find an ideal location to insert the copy.
201   MachineBasicBlock::iterator Pos = InsertPos;
202   while (Pos != MBB->begin()) {
203     MachineInstr *PrevMI = prior(Pos);
204     DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
205     // copyRegToReg might emit multiple instructions to do a copy.
206     unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
207     if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
208       // This is what the BB looks like right now:
209       // r1024 = mov r0
210       // ...
211       // r1    = mov r1024
212       //
213       // We want to insert "r1025 = mov r1". Inserting this copy below the
214       // move to r1024 makes it impossible for that move to be coalesced.
215       //
216       // r1025 = mov r1
217       // r1024 = mov r0
218       // ...
219       // r1    = mov 1024
220       // r2    = mov 1025
221       break; // Woot! Found a good location.
222     --Pos;
223   }
224
225   bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
226   assert(Emitted && "Unable to issue a live-in copy instruction!\n");
227   (void) Emitted;
228
229 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
230   if (Coalesced) {
231     if (&*InsertPos == UseMI) ++InsertPos;
232     MBB->erase(UseMI);
233   }
234 }
235
236 /// EmitLiveInCopies - If this is the first basic block in the function,
237 /// and if it has live ins that need to be copied into vregs, emit the
238 /// copies into the block.
239 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
240                              const MachineRegisterInfo &MRI,
241                              const TargetRegisterInfo &TRI,
242                              const TargetInstrInfo &TII) {
243   if (SchedLiveInCopies) {
244     // Emit the copies at a heuristically-determined location in the block.
245     DenseMap<MachineInstr*, unsigned> CopyRegMap;
246     MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
247     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
248            E = MRI.livein_end(); LI != E; ++LI)
249       if (LI->second) {
250         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
251         EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
252                        RC, CopyRegMap, MRI, TRI, TII);
253       }
254   } else {
255     // Emit the copies into the top of the block.
256     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
257            E = MRI.livein_end(); LI != E; ++LI)
258       if (LI->second) {
259         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
260         bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
261                                         LI->second, LI->first, RC, RC);
262         assert(Emitted && "Unable to issue a live-in copy instruction!\n");
263         (void) Emitted;
264       }
265   }
266 }
267
268 //===----------------------------------------------------------------------===//
269 // SelectionDAGISel code
270 //===----------------------------------------------------------------------===//
271
272 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
273   MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
274   FuncInfo(new FunctionLoweringInfo(TLI)),
275   CurDAG(new SelectionDAG(TLI, *FuncInfo)),
276   SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
277   GFI(),
278   OptLevel(OL),
279   DAGSize(0)
280 {}
281
282 SelectionDAGISel::~SelectionDAGISel() {
283   delete SDL;
284   delete CurDAG;
285   delete FuncInfo;
286 }
287
288 unsigned SelectionDAGISel::MakeReg(EVT VT) {
289   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
290 }
291
292 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
293   AU.addRequired<AliasAnalysis>();
294   AU.addPreserved<AliasAnalysis>();
295   AU.addRequired<GCModuleInfo>();
296   AU.addPreserved<GCModuleInfo>();
297   AU.addRequired<DwarfWriter>();
298   AU.addPreserved<DwarfWriter>();
299   MachineFunctionPass::getAnalysisUsage(AU);
300 }
301
302 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
303   Function &Fn = *mf.getFunction();
304
305   // Do some sanity-checking on the command-line options.
306   assert((!EnableFastISelVerbose || EnableFastISel) &&
307          "-fast-isel-verbose requires -fast-isel");
308   assert((!EnableFastISelAbort || EnableFastISel) &&
309          "-fast-isel-abort requires -fast-isel");
310
311   // Get alias analysis for load/store combining.
312   AA = &getAnalysis<AliasAnalysis>();
313
314   MF = &mf;
315   const TargetInstrInfo &TII = *TM.getInstrInfo();
316   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
317
318   if (Fn.hasGC())
319     GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn);
320   else
321     GFI = 0;
322   RegInfo = &MF->getRegInfo();
323   DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n");
324
325   MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
326   DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
327   CurDAG->init(*MF, MMI, DW);
328   FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
329   SDL->init(GFI, *AA);
330
331   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
332     if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
333       // Mark landing pad.
334       FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
335
336   SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
337
338   // If the first basic block in the function has live ins that need to be
339   // copied into vregs, emit the copies into the top of the block before
340   // emitting the code for the block.
341   EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
342
343   // Add function live-ins to entry block live-in set.
344   for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
345          E = RegInfo->livein_end(); I != E; ++I)
346     MF->begin()->addLiveIn(I->first);
347
348 #ifndef NDEBUG
349   assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
350          "Not all catch info was assigned to a landing pad!");
351 #endif
352
353   FuncInfo->clear();
354
355   return true;
356 }
357
358 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
359                           MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
360   for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
361     if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
362       // Apply the catch info to DestBB.
363       AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
364 #ifndef NDEBUG
365       if (!FLI.MBBMap[SrcBB]->isLandingPad())
366         FLI.CatchInfoFound.insert(EHSel);
367 #endif
368     }
369 }
370
371 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
372                                         BasicBlock::iterator Begin,
373                                         BasicBlock::iterator End) {
374   SDL->setCurrentBasicBlock(BB);
375   MetadataContext &TheMetadata = LLVMBB->getParent()->getContext().getMetadata();
376   unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
377
378   // Lower all of the non-terminator instructions. If a call is emitted
379   // as a tail call, cease emitting nodes for this block.
380   for (BasicBlock::iterator I = Begin; I != End && !SDL->HasTailCall; ++I) {
381     if (MDDbgKind) {
382       // Update DebugLoc if debug information is attached with this
383       // instruction.
384       if (MDNode *Dbg =
385           dyn_cast_or_null<MDNode>(TheMetadata.getMD(MDDbgKind, I))) {
386         DILocation DILoc(Dbg);
387         DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo());
388         SDL->setCurDebugLoc(Loc);
389       }
390     }
391     if (!isa<TerminatorInst>(I))
392       SDL->visit(*I);
393   }
394
395   if (!SDL->HasTailCall) {
396     // Ensure that all instructions which are used outside of their defining
397     // blocks are available as virtual registers.  Invoke is handled elsewhere.
398     for (BasicBlock::iterator I = Begin; I != End; ++I)
399       if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
400         SDL->CopyToExportRegsIfNeeded(I);
401
402     // Handle PHI nodes in successor blocks.
403     if (End == LLVMBB->end()) {
404       HandlePHINodesInSuccessorBlocks(LLVMBB);
405
406       // Lower the terminator after the copies are emitted.
407       SDL->visit(*LLVMBB->getTerminator());
408     }
409   }
410
411   // Make sure the root of the DAG is up-to-date.
412   CurDAG->setRoot(SDL->getControlRoot());
413
414   // Final step, emit the lowered DAG as machine code.
415   CodeGenAndEmitDAG();
416   SDL->clear();
417 }
418
419 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
420   SmallPtrSet<SDNode*, 128> VisitedNodes;
421   SmallVector<SDNode*, 128> Worklist;
422
423   Worklist.push_back(CurDAG->getRoot().getNode());
424
425   APInt Mask;
426   APInt KnownZero;
427   APInt KnownOne;
428
429   while (!Worklist.empty()) {
430     SDNode *N = Worklist.back();
431     Worklist.pop_back();
432
433     // If we've already seen this node, ignore it.
434     if (!VisitedNodes.insert(N))
435       continue;
436
437     // Otherwise, add all chain operands to the worklist.
438     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
439       if (N->getOperand(i).getValueType() == MVT::Other)
440         Worklist.push_back(N->getOperand(i).getNode());
441
442     // If this is a CopyToReg with a vreg dest, process it.
443     if (N->getOpcode() != ISD::CopyToReg)
444       continue;
445
446     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
447     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
448       continue;
449
450     // Ignore non-scalar or non-integer values.
451     SDValue Src = N->getOperand(2);
452     EVT SrcVT = Src.getValueType();
453     if (!SrcVT.isInteger() || SrcVT.isVector())
454       continue;
455
456     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
457     Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
458     CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
459
460     // Only install this information if it tells us something.
461     if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
462       DestReg -= TargetRegisterInfo::FirstVirtualRegister;
463       if (DestReg >= FuncInfo->LiveOutRegInfo.size())
464         FuncInfo->LiveOutRegInfo.resize(DestReg+1);
465       FunctionLoweringInfo::LiveOutInfo &LOI =
466         FuncInfo->LiveOutRegInfo[DestReg];
467       LOI.NumSignBits = NumSignBits;
468       LOI.KnownOne = KnownOne;
469       LOI.KnownZero = KnownZero;
470     }
471   }
472 }
473
474 void SelectionDAGISel::CodeGenAndEmitDAG() {
475   std::string GroupName;
476   if (TimePassesIsEnabled)
477     GroupName = "Instruction Selection and Scheduling";
478   std::string BlockName;
479   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
480       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
481       ViewSUnitDAGs)
482     BlockName = MF->getFunction()->getNameStr() + ":" +
483                 BB->getBasicBlock()->getNameStr();
484
485   DEBUG(errs() << "Initial selection DAG:\n");
486   DEBUG(CurDAG->dump());
487
488   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
489
490   // Run the DAG combiner in pre-legalize mode.
491   if (TimePassesIsEnabled) {
492     NamedRegionTimer T("DAG Combining 1", GroupName);
493     CurDAG->Combine(Unrestricted, *AA, OptLevel);
494   } else {
495     CurDAG->Combine(Unrestricted, *AA, OptLevel);
496   }
497
498   DEBUG(errs() << "Optimized lowered selection DAG:\n");
499   DEBUG(CurDAG->dump());
500
501   // Second step, hack on the DAG until it only uses operations and types that
502   // the target supports.
503   if (!DisableLegalizeTypes) {
504     if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
505                                                  BlockName);
506
507     bool Changed;
508     if (TimePassesIsEnabled) {
509       NamedRegionTimer T("Type Legalization", GroupName);
510       Changed = CurDAG->LegalizeTypes();
511     } else {
512       Changed = CurDAG->LegalizeTypes();
513     }
514
515     DEBUG(errs() << "Type-legalized selection DAG:\n");
516     DEBUG(CurDAG->dump());
517
518     if (Changed) {
519       if (ViewDAGCombineLT)
520         CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
521
522       // Run the DAG combiner in post-type-legalize mode.
523       if (TimePassesIsEnabled) {
524         NamedRegionTimer T("DAG Combining after legalize types", GroupName);
525         CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
526       } else {
527         CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
528       }
529
530       DEBUG(errs() << "Optimized type-legalized selection DAG:\n");
531       DEBUG(CurDAG->dump());
532     }
533
534     if (TimePassesIsEnabled) {
535       NamedRegionTimer T("Vector Legalization", GroupName);
536       Changed = CurDAG->LegalizeVectors();
537     } else {
538       Changed = CurDAG->LegalizeVectors();
539     }
540
541     if (Changed) {
542       if (TimePassesIsEnabled) {
543         NamedRegionTimer T("Type Legalization 2", GroupName);
544         Changed = CurDAG->LegalizeTypes();
545       } else {
546         Changed = CurDAG->LegalizeTypes();
547       }
548
549       if (ViewDAGCombineLT)
550         CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
551
552       // Run the DAG combiner in post-type-legalize mode.
553       if (TimePassesIsEnabled) {
554         NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
555         CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
556       } else {
557         CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
558       }
559
560       DEBUG(errs() << "Optimized vector-legalized selection DAG:\n");
561       DEBUG(CurDAG->dump());
562     }
563   }
564
565   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
566
567   if (TimePassesIsEnabled) {
568     NamedRegionTimer T("DAG Legalization", GroupName);
569     CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
570   } else {
571     CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
572   }
573
574   DEBUG(errs() << "Legalized selection DAG:\n");
575   DEBUG(CurDAG->dump());
576
577   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
578
579   // Run the DAG combiner in post-legalize mode.
580   if (TimePassesIsEnabled) {
581     NamedRegionTimer T("DAG Combining 2", GroupName);
582     CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
583   } else {
584     CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
585   }
586
587   DEBUG(errs() << "Optimized legalized selection DAG:\n");
588   DEBUG(CurDAG->dump());
589
590   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
591
592   if (OptLevel != CodeGenOpt::None)
593     ComputeLiveOutVRegInfo();
594
595   // Third, instruction select all of the operations to machine code, adding the
596   // code to the MachineBasicBlock.
597   if (TimePassesIsEnabled) {
598     NamedRegionTimer T("Instruction Selection", GroupName);
599     InstructionSelect();
600   } else {
601     InstructionSelect();
602   }
603
604   DEBUG(errs() << "Selected selection DAG:\n");
605   DEBUG(CurDAG->dump());
606
607   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
608
609   // Schedule machine code.
610   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
611   if (TimePassesIsEnabled) {
612     NamedRegionTimer T("Instruction Scheduling", GroupName);
613     Scheduler->Run(CurDAG, BB, BB->end());
614   } else {
615     Scheduler->Run(CurDAG, BB, BB->end());
616   }
617
618   if (ViewSUnitDAGs) Scheduler->viewGraph();
619
620   // Emit machine code to BB.  This can change 'BB' to the last block being
621   // inserted into.
622   if (TimePassesIsEnabled) {
623     NamedRegionTimer T("Instruction Creation", GroupName);
624     BB = Scheduler->EmitSchedule(&SDL->EdgeMapping);
625   } else {
626     BB = Scheduler->EmitSchedule(&SDL->EdgeMapping);
627   }
628
629   // Free the scheduler state.
630   if (TimePassesIsEnabled) {
631     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
632     delete Scheduler;
633   } else {
634     delete Scheduler;
635   }
636
637   DEBUG(errs() << "Selected machine code:\n");
638   DEBUG(BB->dump());
639 }
640
641 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
642                                             MachineFunction &MF,
643                                             MachineModuleInfo *MMI,
644                                             DwarfWriter *DW,
645                                             const TargetInstrInfo &TII) {
646   // Initialize the Fast-ISel state, if needed.
647   FastISel *FastIS = 0;
648   if (EnableFastISel)
649     FastIS = TLI.createFastISel(MF, MMI, DW,
650                                 FuncInfo->ValueMap,
651                                 FuncInfo->MBBMap,
652                                 FuncInfo->StaticAllocaMap
653 #ifndef NDEBUG
654                                 , FuncInfo->CatchInfoLost
655 #endif
656                                 );
657
658   MetadataContext &TheMetadata = Fn.getContext().getMetadata();
659   unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
660
661   // Iterate over all basic blocks in the function.
662   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
663     BasicBlock *LLVMBB = &*I;
664     BB = FuncInfo->MBBMap[LLVMBB];
665
666     BasicBlock::iterator const Begin = LLVMBB->begin();
667     BasicBlock::iterator const End = LLVMBB->end();
668     BasicBlock::iterator BI = Begin;
669
670     // Lower any arguments needed in this block if this is the entry block.
671     bool SuppressFastISel = false;
672     if (LLVMBB == &Fn.getEntryBlock()) {
673       LowerArguments(LLVMBB);
674
675       // If any of the arguments has the byval attribute, forgo
676       // fast-isel in the entry block.
677       if (FastIS) {
678         unsigned j = 1;
679         for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
680              I != E; ++I, ++j)
681           if (Fn.paramHasAttr(j, Attribute::ByVal)) {
682             if (EnableFastISelVerbose || EnableFastISelAbort)
683               errs() << "FastISel skips entry block due to byval argument\n";
684             SuppressFastISel = true;
685             break;
686           }
687       }
688     }
689
690     if (MMI && BB->isLandingPad()) {
691       // Add a label to mark the beginning of the landing pad.  Deletion of the
692       // landing pad can thus be detected via the MachineModuleInfo.
693       unsigned LabelID = MMI->addLandingPad(BB);
694
695       const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
696       BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
697
698       // Mark exception register as live in.
699       unsigned Reg = TLI.getExceptionAddressRegister();
700       if (Reg) BB->addLiveIn(Reg);
701
702       // Mark exception selector register as live in.
703       Reg = TLI.getExceptionSelectorRegister();
704       if (Reg) BB->addLiveIn(Reg);
705
706       // FIXME: Hack around an exception handling flaw (PR1508): the personality
707       // function and list of typeids logically belong to the invoke (or, if you
708       // like, the basic block containing the invoke), and need to be associated
709       // with it in the dwarf exception handling tables.  Currently however the
710       // information is provided by an intrinsic (eh.selector) that can be moved
711       // to unexpected places by the optimizers: if the unwind edge is critical,
712       // then breaking it can result in the intrinsics being in the successor of
713       // the landing pad, not the landing pad itself.  This results in exceptions
714       // not being caught because no typeids are associated with the invoke.
715       // This may not be the only way things can go wrong, but it is the only way
716       // we try to work around for the moment.
717       BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
718
719       if (Br && Br->isUnconditional()) { // Critical edge?
720         BasicBlock::iterator I, E;
721         for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
722           if (isa<EHSelectorInst>(I))
723             break;
724
725         if (I == E)
726           // No catch info found - try to extract some from the successor.
727           copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
728       }
729     }
730
731     // Before doing SelectionDAG ISel, see if FastISel has been requested.
732     if (FastIS && !SuppressFastISel) {
733       // Emit code for any incoming arguments. This must happen before
734       // beginning FastISel on the entry block.
735       if (LLVMBB == &Fn.getEntryBlock()) {
736         CurDAG->setRoot(SDL->getControlRoot());
737         CodeGenAndEmitDAG();
738         SDL->clear();
739       }
740       FastIS->startNewBlock(BB);
741       // Do FastISel on as many instructions as possible.
742       for (; BI != End; ++BI) {
743         if (MDDbgKind) {
744           // Update DebugLoc if debug information is attached with this
745           // instruction.
746           if (MDNode *Dbg =
747               dyn_cast_or_null<MDNode>(TheMetadata.getMD(MDDbgKind, BI))) {
748             DILocation DILoc(Dbg);
749             DebugLoc Loc = ExtractDebugLocation(DILoc,
750                                                 MF.getDebugLocInfo());
751             FastIS->setCurDebugLoc(Loc);
752           }
753         }
754
755         // Just before the terminator instruction, insert instructions to
756         // feed PHI nodes in successor blocks.
757         if (isa<TerminatorInst>(BI))
758           if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
759             if (EnableFastISelVerbose || EnableFastISelAbort) {
760               errs() << "FastISel miss: ";
761               BI->dump();
762             }
763             assert(!EnableFastISelAbort &&
764                    "FastISel didn't handle a PHI in a successor");
765             break;
766           }
767
768         // First try normal tablegen-generated "fast" selection.
769         if (FastIS->SelectInstruction(BI))
770           continue;
771
772         // Next, try calling the target to attempt to handle the instruction.
773         if (FastIS->TargetSelectInstruction(BI))
774           continue;
775
776         // Then handle certain instructions as single-LLVM-Instruction blocks.
777         if (isa<CallInst>(BI)) {
778           if (EnableFastISelVerbose || EnableFastISelAbort) {
779             errs() << "FastISel missed call: ";
780             BI->dump();
781           }
782
783           if (BI->getType() != Type::getVoidTy(*CurDAG->getContext())) {
784             unsigned &R = FuncInfo->ValueMap[BI];
785             if (!R)
786               R = FuncInfo->CreateRegForValue(BI);
787           }
788
789           SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
790           SelectBasicBlock(LLVMBB, BI, next(BI));
791           // If the instruction was codegen'd with multiple blocks,
792           // inform the FastISel object where to resume inserting.
793           FastIS->setCurrentBlock(BB);
794           continue;
795         }
796
797         // Otherwise, give up on FastISel for the rest of the block.
798         // For now, be a little lenient about non-branch terminators.
799         if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
800           if (EnableFastISelVerbose || EnableFastISelAbort) {
801             errs() << "FastISel miss: ";
802             BI->dump();
803           }
804           if (EnableFastISelAbort)
805             // The "fast" selector couldn't handle something and bailed.
806             // For the purpose of debugging, just abort.
807             llvm_unreachable("FastISel didn't select the entire block");
808         }
809         break;
810       }
811     }
812
813     // Run SelectionDAG instruction selection on the remainder of the block
814     // not handled by FastISel. If FastISel is not run, this is the entire
815     // block.
816     if (BI != End) {
817       // If FastISel is run and it has known DebugLoc then use it.
818       if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
819         SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
820       SelectBasicBlock(LLVMBB, BI, End);
821     }
822
823     FinishBasicBlock();
824   }
825
826   delete FastIS;
827 }
828
829 void
830 SelectionDAGISel::FinishBasicBlock() {
831
832   DEBUG(errs() << "Target-post-processed machine code:\n");
833   DEBUG(BB->dump());
834
835   DEBUG(errs() << "Total amount of phi nodes to update: "
836                << SDL->PHINodesToUpdate.size() << "\n");
837   DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
838           errs() << "Node " << i << " : ("
839                  << SDL->PHINodesToUpdate[i].first
840                  << ", " << SDL->PHINodesToUpdate[i].second << ")\n");
841
842   // Next, now that we know what the last MBB the LLVM BB expanded is, update
843   // PHI nodes in successors.
844   if (SDL->SwitchCases.empty() &&
845       SDL->JTCases.empty() &&
846       SDL->BitTestCases.empty()) {
847     for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
848       MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
849       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
850              "This is not a machine PHI node that we are updating!");
851       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
852                                                 false));
853       PHI->addOperand(MachineOperand::CreateMBB(BB));
854     }
855     SDL->PHINodesToUpdate.clear();
856     return;
857   }
858
859   for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
860     // Lower header first, if it wasn't already lowered
861     if (!SDL->BitTestCases[i].Emitted) {
862       // Set the current basic block to the mbb we wish to insert the code into
863       BB = SDL->BitTestCases[i].Parent;
864       SDL->setCurrentBasicBlock(BB);
865       // Emit the code
866       SDL->visitBitTestHeader(SDL->BitTestCases[i]);
867       CurDAG->setRoot(SDL->getRoot());
868       CodeGenAndEmitDAG();
869       SDL->clear();
870     }
871
872     for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
873       // Set the current basic block to the mbb we wish to insert the code into
874       BB = SDL->BitTestCases[i].Cases[j].ThisBB;
875       SDL->setCurrentBasicBlock(BB);
876       // Emit the code
877       if (j+1 != ej)
878         SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
879                               SDL->BitTestCases[i].Reg,
880                               SDL->BitTestCases[i].Cases[j]);
881       else
882         SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
883                               SDL->BitTestCases[i].Reg,
884                               SDL->BitTestCases[i].Cases[j]);
885
886
887       CurDAG->setRoot(SDL->getRoot());
888       CodeGenAndEmitDAG();
889       SDL->clear();
890     }
891
892     // Update PHI Nodes
893     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
894       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
895       MachineBasicBlock *PHIBB = PHI->getParent();
896       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
897              "This is not a machine PHI node that we are updating!");
898       // This is "default" BB. We have two jumps to it. From "header" BB and
899       // from last "case" BB.
900       if (PHIBB == SDL->BitTestCases[i].Default) {
901         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
902                                                   false));
903         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
904         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
905                                                   false));
906         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
907                                                   back().ThisBB));
908       }
909       // One of "cases" BB.
910       for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
911            j != ej; ++j) {
912         MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
913         if (cBB->succ_end() !=
914             std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
915           PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
916                                                     false));
917           PHI->addOperand(MachineOperand::CreateMBB(cBB));
918         }
919       }
920     }
921   }
922   SDL->BitTestCases.clear();
923
924   // If the JumpTable record is filled in, then we need to emit a jump table.
925   // Updating the PHI nodes is tricky in this case, since we need to determine
926   // whether the PHI is a successor of the range check MBB or the jump table MBB
927   for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
928     // Lower header first, if it wasn't already lowered
929     if (!SDL->JTCases[i].first.Emitted) {
930       // Set the current basic block to the mbb we wish to insert the code into
931       BB = SDL->JTCases[i].first.HeaderBB;
932       SDL->setCurrentBasicBlock(BB);
933       // Emit the code
934       SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
935       CurDAG->setRoot(SDL->getRoot());
936       CodeGenAndEmitDAG();
937       SDL->clear();
938     }
939
940     // Set the current basic block to the mbb we wish to insert the code into
941     BB = SDL->JTCases[i].second.MBB;
942     SDL->setCurrentBasicBlock(BB);
943     // Emit the code
944     SDL->visitJumpTable(SDL->JTCases[i].second);
945     CurDAG->setRoot(SDL->getRoot());
946     CodeGenAndEmitDAG();
947     SDL->clear();
948
949     // Update PHI Nodes
950     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
951       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
952       MachineBasicBlock *PHIBB = PHI->getParent();
953       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
954              "This is not a machine PHI node that we are updating!");
955       // "default" BB. We can go there only from header BB.
956       if (PHIBB == SDL->JTCases[i].second.Default) {
957         PHI->addOperand
958           (MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, false));
959         PHI->addOperand
960           (MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
961       }
962       // JT BB. Just iterate over successors here
963       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
964         PHI->addOperand
965           (MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, false));
966         PHI->addOperand(MachineOperand::CreateMBB(BB));
967       }
968     }
969   }
970   SDL->JTCases.clear();
971
972   // If the switch block involved a branch to one of the actual successors, we
973   // need to update PHI nodes in that block.
974   for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
975     MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
976     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
977            "This is not a machine PHI node that we are updating!");
978     if (BB->isSuccessor(PHI->getParent())) {
979       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
980                                                 false));
981       PHI->addOperand(MachineOperand::CreateMBB(BB));
982     }
983   }
984
985   // If we generated any switch lowering information, build and codegen any
986   // additional DAGs necessary.
987   for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
988     // Set the current basic block to the mbb we wish to insert the code into
989     MachineBasicBlock *ThisBB = BB = SDL->SwitchCases[i].ThisBB;
990     SDL->setCurrentBasicBlock(BB);
991
992     // Emit the code
993     SDL->visitSwitchCase(SDL->SwitchCases[i]);
994     CurDAG->setRoot(SDL->getRoot());
995     CodeGenAndEmitDAG();
996
997     // Handle any PHI nodes in successors of this chunk, as if we were coming
998     // from the original BB before switch expansion.  Note that PHI nodes can
999     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1000     // handle them the right number of times.
1001     while ((BB = SDL->SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
1002       // If new BB's are created during scheduling, the edges may have been
1003       // updated. That is, the edge from ThisBB to BB may have been split and
1004       // BB's predecessor is now another block.
1005       DenseMap<MachineBasicBlock*, MachineBasicBlock*>::iterator EI =
1006         SDL->EdgeMapping.find(BB);
1007       if (EI != SDL->EdgeMapping.end())
1008         ThisBB = EI->second;
1009       for (MachineBasicBlock::iterator Phi = BB->begin();
1010            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1011         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1012         for (unsigned pn = 0; ; ++pn) {
1013           assert(pn != SDL->PHINodesToUpdate.size() &&
1014                  "Didn't find PHI entry!");
1015           if (SDL->PHINodesToUpdate[pn].first == Phi) {
1016             Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1017                                                       second, false));
1018             Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1019             break;
1020           }
1021         }
1022       }
1023
1024       // Don't process RHS if same block as LHS.
1025       if (BB == SDL->SwitchCases[i].FalseBB)
1026         SDL->SwitchCases[i].FalseBB = 0;
1027
1028       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
1029       SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1030       SDL->SwitchCases[i].FalseBB = 0;
1031     }
1032     assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1033     SDL->clear();
1034   }
1035   SDL->SwitchCases.clear();
1036
1037   SDL->PHINodesToUpdate.clear();
1038 }
1039
1040
1041 /// Create the scheduler. If a specific scheduler was specified
1042 /// via the SchedulerRegistry, use it, otherwise select the
1043 /// one preferred by the target.
1044 ///
1045 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1046   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1047
1048   if (!Ctor) {
1049     Ctor = ISHeuristic;
1050     RegisterScheduler::setDefault(Ctor);
1051   }
1052
1053   return Ctor(this, OptLevel);
1054 }
1055
1056 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1057   return new ScheduleHazardRecognizer();
1058 }
1059
1060 //===----------------------------------------------------------------------===//
1061 // Helper functions used by the generated instruction selector.
1062 //===----------------------------------------------------------------------===//
1063 // Calls to these methods are generated by tblgen.
1064
1065 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1066 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1067 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1068 /// specified in the .td file (e.g. 255).
1069 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1070                                     int64_t DesiredMaskS) const {
1071   const APInt &ActualMask = RHS->getAPIntValue();
1072   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1073
1074   // If the actual mask exactly matches, success!
1075   if (ActualMask == DesiredMask)
1076     return true;
1077
1078   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1079   if (ActualMask.intersects(~DesiredMask))
1080     return false;
1081
1082   // Otherwise, the DAG Combiner may have proven that the value coming in is
1083   // either already zero or is not demanded.  Check for known zero input bits.
1084   APInt NeededMask = DesiredMask & ~ActualMask;
1085   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1086     return true;
1087
1088   // TODO: check to see if missing bits are just not demanded.
1089
1090   // Otherwise, this pattern doesn't match.
1091   return false;
1092 }
1093
1094 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
1095 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1096 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1097 /// specified in the .td file (e.g. 255).
1098 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1099                                    int64_t DesiredMaskS) const {
1100   const APInt &ActualMask = RHS->getAPIntValue();
1101   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1102
1103   // If the actual mask exactly matches, success!
1104   if (ActualMask == DesiredMask)
1105     return true;
1106
1107   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1108   if (ActualMask.intersects(~DesiredMask))
1109     return false;
1110
1111   // Otherwise, the DAG Combiner may have proven that the value coming in is
1112   // either already zero or is not demanded.  Check for known zero input bits.
1113   APInt NeededMask = DesiredMask & ~ActualMask;
1114
1115   APInt KnownZero, KnownOne;
1116   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1117
1118   // If all the missing bits in the or are already known to be set, match!
1119   if ((NeededMask & KnownOne) == NeededMask)
1120     return true;
1121
1122   // TODO: check to see if missing bits are just not demanded.
1123
1124   // Otherwise, this pattern doesn't match.
1125   return false;
1126 }
1127
1128
1129 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1130 /// by tblgen.  Others should not call it.
1131 void SelectionDAGISel::
1132 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1133   std::vector<SDValue> InOps;
1134   std::swap(InOps, Ops);
1135
1136   Ops.push_back(InOps[0]);  // input chain.
1137   Ops.push_back(InOps[1]);  // input asm string.
1138
1139   unsigned i = 2, e = InOps.size();
1140   if (InOps[e-1].getValueType() == MVT::Flag)
1141     --e;  // Don't process a flag operand if it is here.
1142
1143   while (i != e) {
1144     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1145     if ((Flags & 7) != 4 /*MEM*/) {
1146       // Just skip over this operand, copying the operands verbatim.
1147       Ops.insert(Ops.end(), InOps.begin()+i,
1148                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1149       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1150     } else {
1151       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1152              "Memory operand with multiple values?");
1153       // Otherwise, this is a memory operand.  Ask the target to select it.
1154       std::vector<SDValue> SelOps;
1155       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1156         llvm_report_error("Could not match memory address.  Inline asm"
1157                           " failure!");
1158       }
1159
1160       // Add this to the output node.
1161       EVT IntPtrTy = TLI.getPointerTy();
1162       Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1163                                               IntPtrTy));
1164       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1165       i += 2;
1166     }
1167   }
1168
1169   // Add the flag input back if present.
1170   if (e != InOps.size())
1171     Ops.push_back(InOps.back());
1172 }
1173
1174 /// findFlagUse - Return use of EVT::Flag value produced by the specified
1175 /// SDNode.
1176 ///
1177 static SDNode *findFlagUse(SDNode *N) {
1178   unsigned FlagResNo = N->getNumValues()-1;
1179   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1180     SDUse &Use = I.getUse();
1181     if (Use.getResNo() == FlagResNo)
1182       return Use.getUser();
1183   }
1184   return NULL;
1185 }
1186
1187 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1188 /// This function recursively traverses up the operand chain, ignoring
1189 /// certain nodes.
1190 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1191                           SDNode *Root,
1192                           SmallPtrSet<SDNode*, 16> &Visited) {
1193   if (Use->getNodeId() < Def->getNodeId() ||
1194       !Visited.insert(Use))
1195     return false;
1196
1197   for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1198     SDNode *N = Use->getOperand(i).getNode();
1199     if (N == Def) {
1200       if (Use == ImmedUse || Use == Root)
1201         continue;  // We are not looking for immediate use.
1202       assert(N != Root);
1203       return true;
1204     }
1205
1206     // Traverse up the operand chain.
1207     if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1208       return true;
1209   }
1210   return false;
1211 }
1212
1213 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
1214 /// be reached. Return true if that's the case. However, ignore direct uses
1215 /// by ImmedUse (which would be U in the example illustrated in
1216 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1217 /// case).
1218 /// FIXME: to be really generic, we should allow direct use by any node
1219 /// that is being folded. But realisticly since we only fold loads which
1220 /// have one non-chain use, we only need to watch out for load/op/store
1221 /// and load/op/cmp case where the root (store / cmp) may reach the load via
1222 /// its chain operand.
1223 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1224   SmallPtrSet<SDNode*, 16> Visited;
1225   return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1226 }
1227
1228 /// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1229 /// U can be folded during instruction selection that starts at Root and
1230 /// folding N is profitable.
1231 bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1232                                                   SDNode *Root) const {
1233   if (OptLevel == CodeGenOpt::None) return false;
1234
1235   // If Root use can somehow reach N through a path that that doesn't contain
1236   // U then folding N would create a cycle. e.g. In the following
1237   // diagram, Root can reach N through X. If N is folded into into Root, then
1238   // X is both a predecessor and a successor of U.
1239   //
1240   //          [N*]           //
1241   //         ^   ^           //
1242   //        /     \          //
1243   //      [U*]    [X]?       //
1244   //        ^     ^          //
1245   //         \   /           //
1246   //          \ /            //
1247   //         [Root*]         //
1248   //
1249   // * indicates nodes to be folded together.
1250   //
1251   // If Root produces a flag, then it gets (even more) interesting. Since it
1252   // will be "glued" together with its flag use in the scheduler, we need to
1253   // check if it might reach N.
1254   //
1255   //          [N*]           //
1256   //         ^   ^           //
1257   //        /     \          //
1258   //      [U*]    [X]?       //
1259   //        ^       ^        //
1260   //         \       \       //
1261   //          \      |       //
1262   //         [Root*] |       //
1263   //          ^      |       //
1264   //          f      |       //
1265   //          |      /       //
1266   //         [Y]    /        //
1267   //           ^   /         //
1268   //           f  /          //
1269   //           | /           //
1270   //          [FU]           //
1271   //
1272   // If FU (flag use) indirectly reaches N (the load), and Root folds N
1273   // (call it Fold), then X is a predecessor of FU and a successor of
1274   // Fold. But since Fold and FU are flagged together, this will create
1275   // a cycle in the scheduling graph.
1276
1277   EVT VT = Root->getValueType(Root->getNumValues()-1);
1278   while (VT == MVT::Flag) {
1279     SDNode *FU = findFlagUse(Root);
1280     if (FU == NULL)
1281       break;
1282     Root = FU;
1283     VT = Root->getValueType(Root->getNumValues()-1);
1284   }
1285
1286   return !isNonImmUse(Root, N, U);
1287 }
1288
1289
1290 char SelectionDAGISel::ID = 0;