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