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