Tidy up several unbeseeming casts from pointer to intptr_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 "llvm/CodeGen/SelectionDAGISel.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/ADT/BitVector.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/ParameterAttributes.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/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/ScheduleDAG.h"
39 #include "llvm/CodeGen/SchedulerRegistry.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetFrameInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/Timer.h"
52 #include <algorithm>
53 using namespace llvm;
54
55 static cl::opt<bool>
56 EnableValueProp("enable-value-prop", cl::Hidden);
57 static cl::opt<bool>
58 EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
59 static cl::opt<bool>
60 EnableFastISel("fast-isel", cl::Hidden,
61           cl::desc("Enable the experimental \"fast\" instruction selector"));
62 static cl::opt<bool>
63 DisableFastISelAbort("fast-isel-no-abort", cl::Hidden,
64           cl::desc("Use the SelectionDAGISel when \"fast\" instruction "
65                    "selection fails"));
66
67 #ifndef NDEBUG
68 static cl::opt<bool>
69 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
70           cl::desc("Pop up a window to show dags before the first "
71                    "dag combine pass"));
72 static cl::opt<bool>
73 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
74           cl::desc("Pop up a window to show dags before legalize types"));
75 static cl::opt<bool>
76 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
77           cl::desc("Pop up a window to show dags before legalize"));
78 static cl::opt<bool>
79 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
80           cl::desc("Pop up a window to show dags before the second "
81                    "dag combine pass"));
82 static cl::opt<bool>
83 ViewISelDAGs("view-isel-dags", cl::Hidden,
84           cl::desc("Pop up a window to show isel dags as they are selected"));
85 static cl::opt<bool>
86 ViewSchedDAGs("view-sched-dags", cl::Hidden,
87           cl::desc("Pop up a window to show sched dags as they are processed"));
88 static cl::opt<bool>
89 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
90       cl::desc("Pop up a window to show SUnit dags after they are processed"));
91 #else
92 static const bool ViewDAGCombine1 = false,
93                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
94                   ViewDAGCombine2 = false,
95                   ViewISelDAGs = false, ViewSchedDAGs = false,
96                   ViewSUnitDAGs = false;
97 #endif
98
99 //===---------------------------------------------------------------------===//
100 ///
101 /// RegisterScheduler class - Track the registration of instruction schedulers.
102 ///
103 //===---------------------------------------------------------------------===//
104 MachinePassRegistry RegisterScheduler::Registry;
105
106 //===---------------------------------------------------------------------===//
107 ///
108 /// ISHeuristic command line option for instruction schedulers.
109 ///
110 //===---------------------------------------------------------------------===//
111 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
112                RegisterPassParser<RegisterScheduler> >
113 ISHeuristic("pre-RA-sched",
114             cl::init(&createDefaultScheduler),
115             cl::desc("Instruction schedulers available (before register"
116                      " allocation):"));
117
118 static RegisterScheduler
119 defaultListDAGScheduler("default", "  Best scheduler for the target",
120                         createDefaultScheduler);
121
122 namespace llvm {
123   //===--------------------------------------------------------------------===//
124   /// createDefaultScheduler - This creates an instruction scheduler appropriate
125   /// for the target.
126   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
127                                       SelectionDAG *DAG,
128                                       MachineBasicBlock *BB,
129                                       bool Fast) {
130     TargetLowering &TLI = IS->getTargetLowering();
131     
132     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
133       return createTDListDAGScheduler(IS, DAG, BB, Fast);
134     } else {
135       assert(TLI.getSchedulingPreference() ==
136            TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
137       return createBURRListDAGScheduler(IS, DAG, BB, Fast);
138     }
139   }
140 }
141
142 // EmitInstrWithCustomInserter - This method should be implemented by targets
143 // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
144 // instructions are special in various ways, which require special support to
145 // insert.  The specified MachineInstr is created but not inserted into any
146 // basic blocks, and the scheduler passes ownership of it to this method.
147 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
148                                                        MachineBasicBlock *MBB) {
149   cerr << "If a target marks an instruction with "
150        << "'usesCustomDAGSchedInserter', it must implement "
151        << "TargetLowering::EmitInstrWithCustomInserter!\n";
152   abort();
153   return 0;  
154 }
155
156 //===----------------------------------------------------------------------===//
157 // SelectionDAGISel code
158 //===----------------------------------------------------------------------===//
159
160 SelectionDAGISel::SelectionDAGISel(TargetLowering &tli, bool fast) :
161   FunctionPass(&ID), TLI(tli),
162   FuncInfo(new FunctionLoweringInfo(TLI)),
163   CurDAG(new SelectionDAG(TLI, *FuncInfo)),
164   SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
165   GFI(),
166   Fast(fast),
167   DAGSize(0)
168 {}
169
170 SelectionDAGISel::~SelectionDAGISel() {
171   delete SDL;
172   delete CurDAG;
173   delete FuncInfo;
174 }
175
176 unsigned SelectionDAGISel::MakeReg(MVT VT) {
177   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
178 }
179
180 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
181   AU.addRequired<AliasAnalysis>();
182   AU.addRequired<GCModuleInfo>();
183   AU.setPreservesAll();
184 }
185
186 bool SelectionDAGISel::runOnFunction(Function &Fn) {
187   // Get alias analysis for load/store combining.
188   AA = &getAnalysis<AliasAnalysis>();
189
190   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
191   if (MF.getFunction()->hasGC())
192     GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
193   else
194     GFI = 0;
195   RegInfo = &MF.getRegInfo();
196   DOUT << "\n\n\n=== " << Fn.getName() << "\n";
197
198   FuncInfo->set(Fn, MF, EnableFastISel);
199   CurDAG->init(MF, getAnalysisToUpdate<MachineModuleInfo>());
200   SDL->init(GFI, *AA);
201
202   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
203     if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
204       // Mark landing pad.
205       FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
206
207   SelectAllBasicBlocks(Fn, MF);
208
209   // Add function live-ins to entry block live-in set.
210   BasicBlock *EntryBB = &Fn.getEntryBlock();
211   BB = FuncInfo->MBBMap[EntryBB];
212   if (!RegInfo->livein_empty())
213     for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
214            E = RegInfo->livein_end(); I != E; ++I)
215       BB->addLiveIn(I->first);
216
217 #ifndef NDEBUG
218   assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
219          "Not all catch info was assigned to a landing pad!");
220 #endif
221
222   FuncInfo->clear();
223
224   return true;
225 }
226
227 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
228                           MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
229   for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
230     if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
231       // Apply the catch info to DestBB.
232       AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
233 #ifndef NDEBUG
234       if (!FLI.MBBMap[SrcBB]->isLandingPad())
235         FLI.CatchInfoFound.insert(EHSel);
236 #endif
237     }
238 }
239
240 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
241 /// whether object offset >= 0.
242 static bool
243 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
244   if (!isa<FrameIndexSDNode>(Op)) return false;
245
246   FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
247   int FrameIdx =  FrameIdxNode->getIndex();
248   return MFI->isFixedObjectIndex(FrameIdx) &&
249     MFI->getObjectOffset(FrameIdx) >= 0;
250 }
251
252 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
253 /// possibly be overwritten when lowering the outgoing arguments in a tail
254 /// call. Currently the implementation of this call is very conservative and
255 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
256 /// virtual registers would be overwritten by direct lowering.
257 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
258                                                     MachineFrameInfo * MFI) {
259   RegisterSDNode * OpReg = NULL;
260   if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
261       (Op.getOpcode()== ISD::CopyFromReg &&
262        (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
263        (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
264       (Op.getOpcode() == ISD::LOAD &&
265        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
266       (Op.getOpcode() == ISD::MERGE_VALUES &&
267        Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
268        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
269                                        getOperand(1))))
270     return true;
271   return false;
272 }
273
274 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
275 /// DAG and fixes their tailcall attribute operand.
276 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 
277                                            TargetLowering& TLI) {
278   SDNode * Ret = NULL;
279   SDValue Terminator = DAG.getRoot();
280
281   // Find RET node.
282   if (Terminator.getOpcode() == ISD::RET) {
283     Ret = Terminator.getNode();
284   }
285  
286   // Fix tail call attribute of CALL nodes.
287   for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
288          BI = DAG.allnodes_end(); BI != BE; ) {
289     --BI;
290     if (BI->getOpcode() == ISD::CALL) {
291       SDValue OpRet(Ret, 0);
292       SDValue OpCall(BI, 0);
293       bool isMarkedTailCall = 
294         cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
295       // If CALL node has tail call attribute set to true and the call is not
296       // eligible (no RET or the target rejects) the attribute is fixed to
297       // false. The TargetLowering::IsEligibleForTailCallOptimization function
298       // must correctly identify tail call optimizable calls.
299       if (!isMarkedTailCall) continue;
300       if (Ret==NULL ||
301           !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
302         // Not eligible. Mark CALL node as non tail call.
303         SmallVector<SDValue, 32> Ops;
304         unsigned idx=0;
305         for(SDNode::op_iterator I =OpCall.getNode()->op_begin(),
306               E = OpCall.getNode()->op_end(); I != E; I++, idx++) {
307           if (idx!=3)
308             Ops.push_back(*I);
309           else
310             Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
311         }
312         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
313       } else {
314         // Look for tail call clobbered arguments. Emit a series of
315         // copyto/copyfrom virtual register nodes to protect them.
316         SmallVector<SDValue, 32> Ops;
317         SDValue Chain = OpCall.getOperand(0), InFlag;
318         unsigned idx=0;
319         for(SDNode::op_iterator I = OpCall.getNode()->op_begin(),
320               E = OpCall.getNode()->op_end(); I != E; I++, idx++) {
321           SDValue Arg = *I;
322           if (idx > 4 && (idx % 2)) {
323             bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
324               getArgFlags().isByVal();
325             MachineFunction &MF = DAG.getMachineFunction();
326             MachineFrameInfo *MFI = MF.getFrameInfo();
327             if (!isByVal &&
328                 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
329               MVT VT = Arg.getValueType();
330               unsigned VReg = MF.getRegInfo().
331                 createVirtualRegister(TLI.getRegClassFor(VT));
332               Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
333               InFlag = Chain.getValue(1);
334               Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
335               Chain = Arg.getValue(1);
336               InFlag = Arg.getValue(2);
337             }
338           }
339           Ops.push_back(Arg);
340         }
341         // Link in chain of CopyTo/CopyFromReg.
342         Ops[0] = Chain;
343         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
344       }
345     }
346   }
347 }
348
349 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
350                                         BasicBlock::iterator Begin,
351                                         BasicBlock::iterator End) {
352   SDL->setCurrentBasicBlock(BB);
353
354   MachineModuleInfo *MMI = CurDAG->getMachineModuleInfo();
355
356   if (MMI && BB->isLandingPad()) {
357     // Add a label to mark the beginning of the landing pad.  Deletion of the
358     // landing pad can thus be detected via the MachineModuleInfo.
359     unsigned LabelID = MMI->addLandingPad(BB);
360     CurDAG->setRoot(CurDAG->getLabel(ISD::EH_LABEL,
361                                      CurDAG->getEntryNode(), LabelID));
362
363     // Mark exception register as live in.
364     unsigned Reg = TLI.getExceptionAddressRegister();
365     if (Reg) BB->addLiveIn(Reg);
366
367     // Mark exception selector register as live in.
368     Reg = TLI.getExceptionSelectorRegister();
369     if (Reg) BB->addLiveIn(Reg);
370
371     // FIXME: Hack around an exception handling flaw (PR1508): the personality
372     // function and list of typeids logically belong to the invoke (or, if you
373     // like, the basic block containing the invoke), and need to be associated
374     // with it in the dwarf exception handling tables.  Currently however the
375     // information is provided by an intrinsic (eh.selector) that can be moved
376     // to unexpected places by the optimizers: if the unwind edge is critical,
377     // then breaking it can result in the intrinsics being in the successor of
378     // the landing pad, not the landing pad itself.  This results in exceptions
379     // not being caught because no typeids are associated with the invoke.
380     // This may not be the only way things can go wrong, but it is the only way
381     // we try to work around for the moment.
382     BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
383
384     if (Br && Br->isUnconditional()) { // Critical edge?
385       BasicBlock::iterator I, E;
386       for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
387         if (isa<EHSelectorInst>(I))
388           break;
389
390       if (I == E)
391         // No catch info found - try to extract some from the successor.
392         copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
393     }
394   }
395
396   // Lower all of the non-terminator instructions.
397   for (BasicBlock::iterator I = Begin; I != End; ++I)
398     if (!isa<TerminatorInst>(I))
399       SDL->visit(*I);
400
401   // Ensure that all instructions which are used outside of their defining
402   // blocks are available as virtual registers.  Invoke is handled elsewhere.
403   for (BasicBlock::iterator I = Begin; I != End; ++I)
404     if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
405       DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I);
406       if (VMI != FuncInfo->ValueMap.end())
407         SDL->CopyValueToVirtualRegister(I, VMI->second);
408     }
409
410   // Handle PHI nodes in successor blocks.
411   if (End == LLVMBB->end()) {
412     HandlePHINodesInSuccessorBlocks(LLVMBB);
413
414     // Lower the terminator after the copies are emitted.
415     SDL->visit(*LLVMBB->getTerminator());
416   }
417     
418   // Make sure the root of the DAG is up-to-date.
419   CurDAG->setRoot(SDL->getControlRoot());
420
421   // Check whether calls in this block are real tail calls. Fix up CALL nodes
422   // with correct tailcall attribute so that the target can rely on the tailcall
423   // attribute indicating whether the call is really eligible for tail call
424   // optimization.
425   CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
426
427   // Final step, emit the lowered DAG as machine code.
428   CodeGenAndEmitDAG();
429   SDL->clear();
430 }
431
432 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
433   SmallPtrSet<SDNode*, 128> VisitedNodes;
434   SmallVector<SDNode*, 128> Worklist;
435   
436   Worklist.push_back(CurDAG->getRoot().getNode());
437   
438   APInt Mask;
439   APInt KnownZero;
440   APInt KnownOne;
441   
442   while (!Worklist.empty()) {
443     SDNode *N = Worklist.back();
444     Worklist.pop_back();
445     
446     // If we've already seen this node, ignore it.
447     if (!VisitedNodes.insert(N))
448       continue;
449     
450     // Otherwise, add all chain operands to the worklist.
451     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
452       if (N->getOperand(i).getValueType() == MVT::Other)
453         Worklist.push_back(N->getOperand(i).getNode());
454     
455     // If this is a CopyToReg with a vreg dest, process it.
456     if (N->getOpcode() != ISD::CopyToReg)
457       continue;
458     
459     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
460     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
461       continue;
462     
463     // Ignore non-scalar or non-integer values.
464     SDValue Src = N->getOperand(2);
465     MVT SrcVT = Src.getValueType();
466     if (!SrcVT.isInteger() || SrcVT.isVector())
467       continue;
468     
469     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
470     Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
471     CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
472     
473     // Only install this information if it tells us something.
474     if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
475       DestReg -= TargetRegisterInfo::FirstVirtualRegister;
476       FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
477       if (DestReg >= FLI.LiveOutRegInfo.size())
478         FLI.LiveOutRegInfo.resize(DestReg+1);
479       FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
480       LOI.NumSignBits = NumSignBits;
481       LOI.KnownOne = NumSignBits;
482       LOI.KnownZero = NumSignBits;
483     }
484   }
485 }
486
487 void SelectionDAGISel::CodeGenAndEmitDAG() {
488   std::string GroupName;
489   if (TimePassesIsEnabled)
490     GroupName = "Instruction Selection and Scheduling";
491   std::string BlockName;
492   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
493       ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
494     BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
495                 BB->getBasicBlock()->getName();
496
497   DOUT << "Initial selection DAG:\n";
498   DEBUG(CurDAG->dump());
499
500   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
501
502   // Run the DAG combiner in pre-legalize mode.
503   if (TimePassesIsEnabled) {
504     NamedRegionTimer T("DAG Combining 1", GroupName);
505     CurDAG->Combine(false, *AA, Fast);
506   } else {
507     CurDAG->Combine(false, *AA, Fast);
508   }
509   
510   DOUT << "Optimized lowered selection DAG:\n";
511   DEBUG(CurDAG->dump());
512   
513   // Second step, hack on the DAG until it only uses operations and types that
514   // the target supports.
515   if (EnableLegalizeTypes) {// Enable this some day.
516     if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
517                                                  BlockName);
518
519     if (TimePassesIsEnabled) {
520       NamedRegionTimer T("Type Legalization", GroupName);
521       CurDAG->LegalizeTypes();
522     } else {
523       CurDAG->LegalizeTypes();
524     }
525
526     DOUT << "Type-legalized selection DAG:\n";
527     DEBUG(CurDAG->dump());
528
529     // TODO: enable a dag combine pass here.
530   }
531   
532   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
533
534   if (TimePassesIsEnabled) {
535     NamedRegionTimer T("DAG Legalization", GroupName);
536     CurDAG->Legalize();
537   } else {
538     CurDAG->Legalize();
539   }
540   
541   DOUT << "Legalized selection DAG:\n";
542   DEBUG(CurDAG->dump());
543   
544   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
545
546   // Run the DAG combiner in post-legalize mode.
547   if (TimePassesIsEnabled) {
548     NamedRegionTimer T("DAG Combining 2", GroupName);
549     CurDAG->Combine(true, *AA, Fast);
550   } else {
551     CurDAG->Combine(true, *AA, Fast);
552   }
553   
554   DOUT << "Optimized legalized selection DAG:\n";
555   DEBUG(CurDAG->dump());
556
557   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
558   
559   if (!Fast && EnableValueProp)
560     ComputeLiveOutVRegInfo();
561
562   // Third, instruction select all of the operations to machine code, adding the
563   // code to the MachineBasicBlock.
564   if (TimePassesIsEnabled) {
565     NamedRegionTimer T("Instruction Selection", GroupName);
566     InstructionSelect();
567   } else {
568     InstructionSelect();
569   }
570
571   DOUT << "Selected selection DAG:\n";
572   DEBUG(CurDAG->dump());
573
574   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
575
576   // Schedule machine code.
577   ScheduleDAG *Scheduler;
578   if (TimePassesIsEnabled) {
579     NamedRegionTimer T("Instruction Scheduling", GroupName);
580     Scheduler = Schedule();
581   } else {
582     Scheduler = Schedule();
583   }
584
585   if (ViewSUnitDAGs) Scheduler->viewGraph();
586
587   // Emit machine code to BB.  This can change 'BB' to the last block being 
588   // inserted into.
589   if (TimePassesIsEnabled) {
590     NamedRegionTimer T("Instruction Creation", GroupName);
591     BB = Scheduler->EmitSchedule();
592   } else {
593     BB = Scheduler->EmitSchedule();
594   }
595
596   // Free the scheduler state.
597   if (TimePassesIsEnabled) {
598     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
599     delete Scheduler;
600   } else {
601     delete Scheduler;
602   }
603
604   DOUT << "Selected machine code:\n";
605   DEBUG(BB->dump());
606 }  
607
608 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF) {
609   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
610     BasicBlock *LLVMBB = &*I;
611     BB = FuncInfo->MBBMap[LLVMBB];
612
613     BasicBlock::iterator const Begin = LLVMBB->begin();
614     BasicBlock::iterator const End = LLVMBB->end();
615     BasicBlock::iterator I = Begin;
616
617     // Lower any arguments needed in this block if this is the entry block.
618     if (LLVMBB == &Fn.getEntryBlock())
619       LowerArguments(LLVMBB);
620
621     // Before doing SelectionDAG ISel, see if FastISel has been requested.
622     // FastISel doesn't support EH landing pads, which require special handling.
623     if (EnableFastISel && !BB->isLandingPad()) {
624       if (FastISel *F = TLI.createFastISel(*FuncInfo->MF, FuncInfo->ValueMap,
625                                            FuncInfo->MBBMap)) {
626         // Emit code for any incoming arguments. This must happen before
627         // beginning FastISel on the entry block.
628         if (LLVMBB == &Fn.getEntryBlock()) {
629           CurDAG->setRoot(SDL->getControlRoot());
630           CodeGenAndEmitDAG();
631           SDL->clear();
632         }
633         F->setCurrentBlock(BB);
634         // Do FastISel on as many instructions as possible.
635         for (; I != End; ++I) {
636           // Just before the terminator instruction, insert instructions to
637           // feed PHI nodes in successor blocks.
638           if (isa<TerminatorInst>(I))
639             if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, F)) {
640               if (DisableFastISelAbort)
641                 break;
642 #ifndef NDEBUG
643               I->dump();
644 #endif  
645               assert(0 && "FastISel didn't handle a PHI in a successor");
646             }
647
648           // First try normal tablegen-generated "fast" selection.
649           if (F->SelectInstruction(I))
650             continue;
651
652           // Next, try calling the target to attempt to handle the instruction.
653           if (F->TargetSelectInstruction(I))
654             continue;
655
656           // Then handle certain instructions as single-LLVM-Instruction blocks.
657           if (isa<CallInst>(I) || isa<LoadInst>(I) ||
658               isa<StoreInst>(I)) {
659             if (I->getType() != Type::VoidTy) {
660               unsigned &R = FuncInfo->ValueMap[I];
661               if (!R)
662                 R = FuncInfo->CreateRegForValue(I);
663             }
664
665             SelectBasicBlock(LLVMBB, I, next(I));
666             continue;
667           }
668
669           if (!DisableFastISelAbort &&
670               // For now, don't abort on non-conditional-branch terminators.
671               (!isa<TerminatorInst>(I) ||
672                (isa<BranchInst>(I) &&
673                 cast<BranchInst>(I)->isUnconditional()))) {
674             // The "fast" selector couldn't handle something and bailed.
675             // For the purpose of debugging, just abort.
676 #ifndef NDEBUG
677             I->dump();
678 #endif
679             assert(0 && "FastISel didn't select the entire block");
680           }
681           break;
682         }
683         delete F;
684       }
685     }
686
687     // Run SelectionDAG instruction selection on the remainder of the block
688     // not handled by FastISel. If FastISel is not run, this is the entire
689     // block.
690     if (I != End)
691       SelectBasicBlock(LLVMBB, I, End);
692
693     FinishBasicBlock();
694   }
695 }
696
697 void
698 SelectionDAGISel::FinishBasicBlock() {
699
700   // Perform target specific isel post processing.
701   InstructionSelectPostProcessing();
702   
703   DOUT << "Target-post-processed machine code:\n";
704   DEBUG(BB->dump());
705
706   DOUT << "Total amount of phi nodes to update: "
707        << SDL->PHINodesToUpdate.size() << "\n";
708   DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
709           DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
710                << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
711   
712   // Next, now that we know what the last MBB the LLVM BB expanded is, update
713   // PHI nodes in successors.
714   if (SDL->SwitchCases.empty() &&
715       SDL->JTCases.empty() &&
716       SDL->BitTestCases.empty()) {
717     for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
718       MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
719       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
720              "This is not a machine PHI node that we are updating!");
721       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
722                                                 false));
723       PHI->addOperand(MachineOperand::CreateMBB(BB));
724     }
725     SDL->PHINodesToUpdate.clear();
726     return;
727   }
728
729   for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
730     // Lower header first, if it wasn't already lowered
731     if (!SDL->BitTestCases[i].Emitted) {
732       // Set the current basic block to the mbb we wish to insert the code into
733       BB = SDL->BitTestCases[i].Parent;
734       SDL->setCurrentBasicBlock(BB);
735       // Emit the code
736       SDL->visitBitTestHeader(SDL->BitTestCases[i]);
737       CurDAG->setRoot(SDL->getRoot());
738       CodeGenAndEmitDAG();
739       SDL->clear();
740     }    
741
742     for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
743       // Set the current basic block to the mbb we wish to insert the code into
744       BB = SDL->BitTestCases[i].Cases[j].ThisBB;
745       SDL->setCurrentBasicBlock(BB);
746       // Emit the code
747       if (j+1 != ej)
748         SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
749                               SDL->BitTestCases[i].Reg,
750                               SDL->BitTestCases[i].Cases[j]);
751       else
752         SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
753                               SDL->BitTestCases[i].Reg,
754                               SDL->BitTestCases[i].Cases[j]);
755         
756         
757       CurDAG->setRoot(SDL->getRoot());
758       CodeGenAndEmitDAG();
759       SDL->clear();
760     }
761
762     // Update PHI Nodes
763     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
764       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
765       MachineBasicBlock *PHIBB = PHI->getParent();
766       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
767              "This is not a machine PHI node that we are updating!");
768       // This is "default" BB. We have two jumps to it. From "header" BB and
769       // from last "case" BB.
770       if (PHIBB == SDL->BitTestCases[i].Default) {
771         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
772                                                   false));
773         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
774         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
775                                                   false));
776         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
777                                                   back().ThisBB));
778       }
779       // One of "cases" BB.
780       for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
781            j != ej; ++j) {
782         MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
783         if (cBB->succ_end() !=
784             std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
785           PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
786                                                     false));
787           PHI->addOperand(MachineOperand::CreateMBB(cBB));
788         }
789       }
790     }
791   }
792   SDL->BitTestCases.clear();
793
794   // If the JumpTable record is filled in, then we need to emit a jump table.
795   // Updating the PHI nodes is tricky in this case, since we need to determine
796   // whether the PHI is a successor of the range check MBB or the jump table MBB
797   for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
798     // Lower header first, if it wasn't already lowered
799     if (!SDL->JTCases[i].first.Emitted) {
800       // Set the current basic block to the mbb we wish to insert the code into
801       BB = SDL->JTCases[i].first.HeaderBB;
802       SDL->setCurrentBasicBlock(BB);
803       // Emit the code
804       SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
805       CurDAG->setRoot(SDL->getRoot());
806       CodeGenAndEmitDAG();
807       SDL->clear();
808     }
809     
810     // Set the current basic block to the mbb we wish to insert the code into
811     BB = SDL->JTCases[i].second.MBB;
812     SDL->setCurrentBasicBlock(BB);
813     // Emit the code
814     SDL->visitJumpTable(SDL->JTCases[i].second);
815     CurDAG->setRoot(SDL->getRoot());
816     CodeGenAndEmitDAG();
817     SDL->clear();
818     
819     // Update PHI Nodes
820     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
821       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
822       MachineBasicBlock *PHIBB = PHI->getParent();
823       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
824              "This is not a machine PHI node that we are updating!");
825       // "default" BB. We can go there only from header BB.
826       if (PHIBB == SDL->JTCases[i].second.Default) {
827         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
828                                                   false));
829         PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
830       }
831       // JT BB. Just iterate over successors here
832       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
833         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
834                                                   false));
835         PHI->addOperand(MachineOperand::CreateMBB(BB));
836       }
837     }
838   }
839   SDL->JTCases.clear();
840   
841   // If the switch block involved a branch to one of the actual successors, we
842   // need to update PHI nodes in that block.
843   for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
844     MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
845     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
846            "This is not a machine PHI node that we are updating!");
847     if (BB->isSuccessor(PHI->getParent())) {
848       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
849                                                 false));
850       PHI->addOperand(MachineOperand::CreateMBB(BB));
851     }
852   }
853   
854   // If we generated any switch lowering information, build and codegen any
855   // additional DAGs necessary.
856   for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
857     // Set the current basic block to the mbb we wish to insert the code into
858     BB = SDL->SwitchCases[i].ThisBB;
859     SDL->setCurrentBasicBlock(BB);
860     
861     // Emit the code
862     SDL->visitSwitchCase(SDL->SwitchCases[i]);
863     CurDAG->setRoot(SDL->getRoot());
864     CodeGenAndEmitDAG();
865     SDL->clear();
866     
867     // Handle any PHI nodes in successors of this chunk, as if we were coming
868     // from the original BB before switch expansion.  Note that PHI nodes can
869     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
870     // handle them the right number of times.
871     while ((BB = SDL->SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
872       for (MachineBasicBlock::iterator Phi = BB->begin();
873            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
874         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
875         for (unsigned pn = 0; ; ++pn) {
876           assert(pn != SDL->PHINodesToUpdate.size() &&
877                  "Didn't find PHI entry!");
878           if (SDL->PHINodesToUpdate[pn].first == Phi) {
879             Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
880                                                       second, false));
881             Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
882             break;
883           }
884         }
885       }
886       
887       // Don't process RHS if same block as LHS.
888       if (BB == SDL->SwitchCases[i].FalseBB)
889         SDL->SwitchCases[i].FalseBB = 0;
890       
891       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
892       SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
893       SDL->SwitchCases[i].FalseBB = 0;
894     }
895     assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
896   }
897   SDL->SwitchCases.clear();
898
899   SDL->PHINodesToUpdate.clear();
900 }
901
902
903 /// Schedule - Pick a safe ordering for instructions for each
904 /// target node in the graph.
905 ///
906 ScheduleDAG *SelectionDAGISel::Schedule() {
907   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
908   
909   if (!Ctor) {
910     Ctor = ISHeuristic;
911     RegisterScheduler::setDefault(Ctor);
912   }
913   
914   ScheduleDAG *Scheduler = Ctor(this, CurDAG, BB, Fast);
915   Scheduler->Run();
916
917   return Scheduler;
918 }
919
920
921 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
922   return new HazardRecognizer();
923 }
924
925 //===----------------------------------------------------------------------===//
926 // Helper functions used by the generated instruction selector.
927 //===----------------------------------------------------------------------===//
928 // Calls to these methods are generated by tblgen.
929
930 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
931 /// the dag combiner simplified the 255, we still want to match.  RHS is the
932 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
933 /// specified in the .td file (e.g. 255).
934 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 
935                                     int64_t DesiredMaskS) const {
936   const APInt &ActualMask = RHS->getAPIntValue();
937   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
938   
939   // If the actual mask exactly matches, success!
940   if (ActualMask == DesiredMask)
941     return true;
942   
943   // If the actual AND mask is allowing unallowed bits, this doesn't match.
944   if (ActualMask.intersects(~DesiredMask))
945     return false;
946   
947   // Otherwise, the DAG Combiner may have proven that the value coming in is
948   // either already zero or is not demanded.  Check for known zero input bits.
949   APInt NeededMask = DesiredMask & ~ActualMask;
950   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
951     return true;
952   
953   // TODO: check to see if missing bits are just not demanded.
954
955   // Otherwise, this pattern doesn't match.
956   return false;
957 }
958
959 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
960 /// the dag combiner simplified the 255, we still want to match.  RHS is the
961 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
962 /// specified in the .td file (e.g. 255).
963 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 
964                                    int64_t DesiredMaskS) const {
965   const APInt &ActualMask = RHS->getAPIntValue();
966   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
967   
968   // If the actual mask exactly matches, success!
969   if (ActualMask == DesiredMask)
970     return true;
971   
972   // If the actual AND mask is allowing unallowed bits, this doesn't match.
973   if (ActualMask.intersects(~DesiredMask))
974     return false;
975   
976   // Otherwise, the DAG Combiner may have proven that the value coming in is
977   // either already zero or is not demanded.  Check for known zero input bits.
978   APInt NeededMask = DesiredMask & ~ActualMask;
979   
980   APInt KnownZero, KnownOne;
981   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
982   
983   // If all the missing bits in the or are already known to be set, match!
984   if ((NeededMask & KnownOne) == NeededMask)
985     return true;
986   
987   // TODO: check to see if missing bits are just not demanded.
988   
989   // Otherwise, this pattern doesn't match.
990   return false;
991 }
992
993
994 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
995 /// by tblgen.  Others should not call it.
996 void SelectionDAGISel::
997 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
998   std::vector<SDValue> InOps;
999   std::swap(InOps, Ops);
1000
1001   Ops.push_back(InOps[0]);  // input chain.
1002   Ops.push_back(InOps[1]);  // input asm string.
1003
1004   unsigned i = 2, e = InOps.size();
1005   if (InOps[e-1].getValueType() == MVT::Flag)
1006     --e;  // Don't process a flag operand if it is here.
1007   
1008   while (i != e) {
1009     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
1010     if ((Flags & 7) != 4 /*MEM*/) {
1011       // Just skip over this operand, copying the operands verbatim.
1012       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
1013       i += (Flags >> 3) + 1;
1014     } else {
1015       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
1016       // Otherwise, this is a memory operand.  Ask the target to select it.
1017       std::vector<SDValue> SelOps;
1018       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1019         cerr << "Could not match memory address.  Inline asm failure!\n";
1020         exit(1);
1021       }
1022       
1023       // Add this to the output node.
1024       MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1025       Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
1026                                               IntPtrTy));
1027       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1028       i += 2;
1029     }
1030   }
1031   
1032   // Add the flag input back if present.
1033   if (e != InOps.size())
1034     Ops.push_back(InOps.back());
1035 }
1036
1037 char SelectionDAGISel::ID = 0;