Do some code refactoring on Jim's scheduler in preparation of the new list
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CodeGen/IntrinsicLowering.h"
25 #include "llvm/CodeGen/MachineDebugInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/SSARegMap.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Debug.h"
41 #include <map>
42 #include <iostream>
43 using namespace llvm;
44
45 #ifndef NDEBUG
46 static cl::opt<bool>
47 ViewISelDAGs("view-isel-dags", cl::Hidden,
48           cl::desc("Pop up a window to show isel dags as they are selected"));
49 static cl::opt<bool>
50 ViewSchedDAGs("view-sched-dags", cl::Hidden,
51           cl::desc("Pop up a window to show sched dags as they are processed"));
52 #else
53 static const bool ViewISelDAGs = 0;
54 static const bool ViewSchedDAGs = 0;
55 #endif
56
57 namespace llvm {
58   //===--------------------------------------------------------------------===//
59   /// FunctionLoweringInfo - This contains information that is global to a
60   /// function that is used when lowering a region of the function.
61   class FunctionLoweringInfo {
62   public:
63     TargetLowering &TLI;
64     Function &Fn;
65     MachineFunction &MF;
66     SSARegMap *RegMap;
67
68     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
69
70     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
71     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
72
73     /// ValueMap - Since we emit code for the function a basic block at a time,
74     /// we must remember which virtual registers hold the values for
75     /// cross-basic-block values.
76     std::map<const Value*, unsigned> ValueMap;
77
78     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
79     /// the entry block.  This allows the allocas to be efficiently referenced
80     /// anywhere in the function.
81     std::map<const AllocaInst*, int> StaticAllocaMap;
82
83     unsigned MakeReg(MVT::ValueType VT) {
84       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
85     }
86
87     unsigned CreateRegForValue(const Value *V) {
88       MVT::ValueType VT = TLI.getValueType(V->getType());
89       // The common case is that we will only create one register for this
90       // value.  If we have that case, create and return the virtual register.
91       unsigned NV = TLI.getNumElements(VT);
92       if (NV == 1) {
93         // If we are promoting this value, pick the next largest supported type.
94         return MakeReg(TLI.getTypeToTransformTo(VT));
95       }
96
97       // If this value is represented with multiple target registers, make sure
98       // to create enough consequtive registers of the right (smaller) type.
99       unsigned NT = VT-1;  // Find the type to use.
100       while (TLI.getNumElements((MVT::ValueType)NT) != 1)
101         --NT;
102
103       unsigned R = MakeReg((MVT::ValueType)NT);
104       for (unsigned i = 1; i != NV; ++i)
105         MakeReg((MVT::ValueType)NT);
106       return R;
107     }
108
109     unsigned InitializeRegForValue(const Value *V) {
110       unsigned &R = ValueMap[V];
111       assert(R == 0 && "Already initialized this value register!");
112       return R = CreateRegForValue(V);
113     }
114   };
115 }
116
117 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
118 /// PHI nodes or outside of the basic block that defines it.
119 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
120   if (isa<PHINode>(I)) return true;
121   BasicBlock *BB = I->getParent();
122   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
123     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
124       return true;
125   return false;
126 }
127
128 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
129 /// entry block, return true.
130 static bool isOnlyUsedInEntryBlock(Argument *A) {
131   BasicBlock *Entry = A->getParent()->begin();
132   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
133     if (cast<Instruction>(*UI)->getParent() != Entry)
134       return false;  // Use not in entry block.
135   return true;
136 }
137
138 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
139                                            Function &fn, MachineFunction &mf)
140     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
141
142   // Create a vreg for each argument register that is not dead and is used
143   // outside of the entry block for the function.
144   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
145        AI != E; ++AI)
146     if (!isOnlyUsedInEntryBlock(AI))
147       InitializeRegForValue(AI);
148
149   // Initialize the mapping of values to registers.  This is only set up for
150   // instruction values that are used outside of the block that defines
151   // them.
152   Function::iterator BB = Fn.begin(), EB = Fn.end();
153   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
154     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
155       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
156         const Type *Ty = AI->getAllocatedType();
157         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
158         unsigned Align = 
159           std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
160                    AI->getAlignment());
161
162         // If the alignment of the value is smaller than the size of the value,
163         // and if the size of the value is particularly small (<= 8 bytes),
164         // round up to the size of the value for potentially better performance.
165         //
166         // FIXME: This could be made better with a preferred alignment hook in
167         // TargetData.  It serves primarily to 8-byte align doubles for X86.
168         if (Align < TySize && TySize <= 8) Align = TySize;
169         TySize *= CUI->getValue();   // Get total allocated size.
170         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
171         StaticAllocaMap[AI] =
172           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
173       }
174
175   for (; BB != EB; ++BB)
176     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
177       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
178         if (!isa<AllocaInst>(I) ||
179             !StaticAllocaMap.count(cast<AllocaInst>(I)))
180           InitializeRegForValue(I);
181
182   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
183   // also creates the initial PHI MachineInstrs, though none of the input
184   // operands are populated.
185   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
186     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
187     MBBMap[BB] = MBB;
188     MF.getBasicBlockList().push_back(MBB);
189
190     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
191     // appropriate.
192     PHINode *PN;
193     for (BasicBlock::iterator I = BB->begin();
194          (PN = dyn_cast<PHINode>(I)); ++I)
195       if (!PN->use_empty()) {
196         unsigned NumElements =
197           TLI.getNumElements(TLI.getValueType(PN->getType()));
198         unsigned PHIReg = ValueMap[PN];
199         assert(PHIReg &&"PHI node does not have an assigned virtual register!");
200         for (unsigned i = 0; i != NumElements; ++i)
201           BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
202       }
203   }
204 }
205
206
207
208 //===----------------------------------------------------------------------===//
209 /// SelectionDAGLowering - This is the common target-independent lowering
210 /// implementation that is parameterized by a TargetLowering object.
211 /// Also, targets can overload any lowering method.
212 ///
213 namespace llvm {
214 class SelectionDAGLowering {
215   MachineBasicBlock *CurMBB;
216
217   std::map<const Value*, SDOperand> NodeMap;
218
219   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
220   /// them up and then emit token factor nodes when possible.  This allows us to
221   /// get simple disambiguation between loads without worrying about alias
222   /// analysis.
223   std::vector<SDOperand> PendingLoads;
224
225 public:
226   // TLI - This is information that describes the available target features we
227   // need for lowering.  This indicates when operations are unavailable,
228   // implemented with a libcall, etc.
229   TargetLowering &TLI;
230   SelectionDAG &DAG;
231   const TargetData &TD;
232
233   /// FuncInfo - Information about the function as a whole.
234   ///
235   FunctionLoweringInfo &FuncInfo;
236
237   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
238                        FunctionLoweringInfo &funcinfo)
239     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
240       FuncInfo(funcinfo) {
241   }
242
243   /// getRoot - Return the current virtual root of the Selection DAG.
244   ///
245   SDOperand getRoot() {
246     if (PendingLoads.empty())
247       return DAG.getRoot();
248
249     if (PendingLoads.size() == 1) {
250       SDOperand Root = PendingLoads[0];
251       DAG.setRoot(Root);
252       PendingLoads.clear();
253       return Root;
254     }
255
256     // Otherwise, we have to make a token factor node.
257     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
258     PendingLoads.clear();
259     DAG.setRoot(Root);
260     return Root;
261   }
262
263   void visit(Instruction &I) { visit(I.getOpcode(), I); }
264
265   void visit(unsigned Opcode, User &I) {
266     switch (Opcode) {
267     default: assert(0 && "Unknown instruction type encountered!");
268              abort();
269       // Build the switch statement using the Instruction.def file.
270 #define HANDLE_INST(NUM, OPCODE, CLASS) \
271     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
272 #include "llvm/Instruction.def"
273     }
274   }
275
276   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
277
278
279   SDOperand getIntPtrConstant(uint64_t Val) {
280     return DAG.getConstant(Val, TLI.getPointerTy());
281   }
282
283   SDOperand getValue(const Value *V) {
284     SDOperand &N = NodeMap[V];
285     if (N.Val) return N;
286
287     const Type *VTy = V->getType();
288     MVT::ValueType VT = TLI.getValueType(VTy);
289     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
290       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
291         visit(CE->getOpcode(), *CE);
292         assert(N.Val && "visit didn't populate the ValueMap!");
293         return N;
294       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
295         return N = DAG.getGlobalAddress(GV, VT);
296       } else if (isa<ConstantPointerNull>(C)) {
297         return N = DAG.getConstant(0, TLI.getPointerTy());
298       } else if (isa<UndefValue>(C)) {
299         return N = DAG.getNode(ISD::UNDEF, VT);
300       } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
301         return N = DAG.getConstantFP(CFP->getValue(), VT);
302       } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
303         unsigned NumElements = PTy->getNumElements();
304         MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
305         MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
306         
307         // Now that we know the number and type of the elements, push a
308         // Constant or ConstantFP node onto the ops list for each element of
309         // the packed constant.
310         std::vector<SDOperand> Ops;
311         if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
312           if (MVT::isFloatingPoint(PVT)) {
313             for (unsigned i = 0; i != NumElements; ++i) {
314               const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
315               Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
316             }
317           } else {
318             for (unsigned i = 0; i != NumElements; ++i) {
319               const ConstantIntegral *El = 
320                 cast<ConstantIntegral>(CP->getOperand(i));
321               Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
322             }
323           }
324         } else {
325           assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
326           SDOperand Op;
327           if (MVT::isFloatingPoint(PVT))
328             Op = DAG.getConstantFP(0, PVT);
329           else
330             Op = DAG.getConstant(0, PVT);
331           Ops.assign(NumElements, Op);
332         }
333         
334         // Handle the case where we have a 1-element vector, in which
335         // case we want to immediately turn it into a scalar constant.
336         if (Ops.size() == 1) {
337           return N = Ops[0];
338         } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
339           return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
340         } else {
341           // If the packed type isn't legal, then create a ConstantVec node with
342           // generic Vector type instead.
343           return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
344         }
345       } else {
346         // Canonicalize all constant ints to be unsigned.
347         return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
348       }
349
350     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
351       std::map<const AllocaInst*, int>::iterator SI =
352         FuncInfo.StaticAllocaMap.find(AI);
353       if (SI != FuncInfo.StaticAllocaMap.end())
354         return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
355     }
356
357     std::map<const Value*, unsigned>::const_iterator VMI =
358       FuncInfo.ValueMap.find(V);
359     assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
360
361     unsigned InReg = VMI->second;
362    
363     // If this type is not legal, make it so now.
364     MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
365     
366     N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
367     if (DestVT < VT) {
368       // Source must be expanded.  This input value is actually coming from the
369       // register pair VMI->second and VMI->second+1.
370       N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
371                       DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
372     } else {
373       if (DestVT > VT) { // Promotion case
374         if (MVT::isFloatingPoint(VT))
375           N = DAG.getNode(ISD::FP_ROUND, VT, N);
376         else
377           N = DAG.getNode(ISD::TRUNCATE, VT, N);
378       }
379     }
380     
381     return N;
382   }
383
384   const SDOperand &setValue(const Value *V, SDOperand NewN) {
385     SDOperand &N = NodeMap[V];
386     assert(N.Val == 0 && "Already set a value for this node!");
387     return N = NewN;
388   }
389
390   // Terminator instructions.
391   void visitRet(ReturnInst &I);
392   void visitBr(BranchInst &I);
393   void visitUnreachable(UnreachableInst &I) { /* noop */ }
394
395   // These all get lowered before this pass.
396   void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
397   void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
398   void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
399   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
400   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
401
402   //
403   void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
404   void visitShift(User &I, unsigned Opcode);
405   void visitAdd(User &I) { 
406     visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD); 
407   }
408   void visitSub(User &I);
409   void visitMul(User &I) { 
410     visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL); 
411   }
412   void visitDiv(User &I) {
413     const Type *Ty = I.getType();
414     visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
415   }
416   void visitRem(User &I) {
417     const Type *Ty = I.getType();
418     visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
419   }
420   void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
421   void visitOr (User &I) { visitBinary(I, ISD::OR,  0, 0); }
422   void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
423   void visitShl(User &I) { visitShift(I, ISD::SHL); }
424   void visitShr(User &I) { 
425     visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
426   }
427
428   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
429   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
430   void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
431   void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
432   void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
433   void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
434   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
435
436   void visitGetElementPtr(User &I);
437   void visitCast(User &I);
438   void visitSelect(User &I);
439   //
440
441   void visitMalloc(MallocInst &I);
442   void visitFree(FreeInst &I);
443   void visitAlloca(AllocaInst &I);
444   void visitLoad(LoadInst &I);
445   void visitStore(StoreInst &I);
446   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
447   void visitCall(CallInst &I);
448   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
449
450   void visitVAStart(CallInst &I);
451   void visitVAArg(VAArgInst &I);
452   void visitVAEnd(CallInst &I);
453   void visitVACopy(CallInst &I);
454   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
455
456   void visitMemIntrinsic(CallInst &I, unsigned Op);
457
458   void visitUserOp1(Instruction &I) {
459     assert(0 && "UserOp1 should not exist at instruction selection time!");
460     abort();
461   }
462   void visitUserOp2(Instruction &I) {
463     assert(0 && "UserOp2 should not exist at instruction selection time!");
464     abort();
465   }
466 };
467 } // end namespace llvm
468
469 void SelectionDAGLowering::visitRet(ReturnInst &I) {
470   if (I.getNumOperands() == 0) {
471     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
472     return;
473   }
474
475   SDOperand Op1 = getValue(I.getOperand(0));
476   MVT::ValueType TmpVT;
477
478   switch (Op1.getValueType()) {
479   default: assert(0 && "Unknown value type!");
480   case MVT::i1:
481   case MVT::i8:
482   case MVT::i16:
483   case MVT::i32:
484     // If this is a machine where 32-bits is legal or expanded, promote to
485     // 32-bits, otherwise, promote to 64-bits.
486     if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
487       TmpVT = TLI.getTypeToTransformTo(MVT::i32);
488     else
489       TmpVT = MVT::i32;
490
491     // Extend integer types to result type.
492     if (I.getOperand(0)->getType()->isSigned())
493       Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
494     else
495       Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
496     break;
497   case MVT::f32:
498     // If this is a machine where f32 is promoted to f64, do so now.
499     if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
500       Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
501     break;
502   case MVT::i64:
503   case MVT::f64:
504     break; // No extension needed!
505   }
506   // Allow targets to lower this further to meet ABI requirements
507   DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
508 }
509
510 void SelectionDAGLowering::visitBr(BranchInst &I) {
511   // Update machine-CFG edges.
512   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
513
514   // Figure out which block is immediately after the current one.
515   MachineBasicBlock *NextBlock = 0;
516   MachineFunction::iterator BBI = CurMBB;
517   if (++BBI != CurMBB->getParent()->end())
518     NextBlock = BBI;
519
520   if (I.isUnconditional()) {
521     // If this is not a fall-through branch, emit the branch.
522     if (Succ0MBB != NextBlock)
523       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
524                               DAG.getBasicBlock(Succ0MBB)));
525   } else {
526     MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
527
528     SDOperand Cond = getValue(I.getCondition());
529     if (Succ1MBB == NextBlock) {
530       // If the condition is false, fall through.  This means we should branch
531       // if the condition is true to Succ #0.
532       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
533                               Cond, DAG.getBasicBlock(Succ0MBB)));
534     } else if (Succ0MBB == NextBlock) {
535       // If the condition is true, fall through.  This means we should branch if
536       // the condition is false to Succ #1.  Invert the condition first.
537       SDOperand True = DAG.getConstant(1, Cond.getValueType());
538       Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
539       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
540                               Cond, DAG.getBasicBlock(Succ1MBB)));
541     } else {
542       std::vector<SDOperand> Ops;
543       Ops.push_back(getRoot());
544       Ops.push_back(Cond);
545       Ops.push_back(DAG.getBasicBlock(Succ0MBB));
546       Ops.push_back(DAG.getBasicBlock(Succ1MBB));
547       DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
548     }
549   }
550 }
551
552 void SelectionDAGLowering::visitSub(User &I) {
553   // -0.0 - X --> fneg
554   if (I.getType()->isFloatingPoint()) {
555     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
556       if (CFP->isExactlyValue(-0.0)) {
557         SDOperand Op2 = getValue(I.getOperand(1));
558         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
559         return;
560       }
561   }
562   visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
563 }
564
565 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp, 
566                                        unsigned VecOp) {
567   const Type *Ty = I.getType();
568   SDOperand Op1 = getValue(I.getOperand(0));
569   SDOperand Op2 = getValue(I.getOperand(1));
570
571   if (Ty->isIntegral()) {
572     setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
573   } else if (Ty->isFloatingPoint()) {
574     setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
575   } else {
576     const PackedType *PTy = cast<PackedType>(Ty);
577     unsigned NumElements = PTy->getNumElements();
578     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
579     MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
580     
581     // Immediately scalarize packed types containing only one element, so that
582     // the Legalize pass does not have to deal with them.  Similarly, if the
583     // abstract vector is going to turn into one that the target natively
584     // supports, generate that type now so that Legalize doesn't have to deal
585     // with that either.  These steps ensure that Legalize only has to handle
586     // vector types in its Expand case.
587     unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
588     if (NumElements == 1) {
589       setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
590     } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
591       setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
592     } else {
593       SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
594       SDOperand Typ = DAG.getValueType(PVT);
595       setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
596     }
597   }
598 }
599
600 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
601   SDOperand Op1 = getValue(I.getOperand(0));
602   SDOperand Op2 = getValue(I.getOperand(1));
603   
604   Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
605   
606   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
607 }
608
609 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
610                                       ISD::CondCode UnsignedOpcode) {
611   SDOperand Op1 = getValue(I.getOperand(0));
612   SDOperand Op2 = getValue(I.getOperand(1));
613   ISD::CondCode Opcode = SignedOpcode;
614   if (I.getOperand(0)->getType()->isUnsigned())
615     Opcode = UnsignedOpcode;
616   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
617 }
618
619 void SelectionDAGLowering::visitSelect(User &I) {
620   SDOperand Cond     = getValue(I.getOperand(0));
621   SDOperand TrueVal  = getValue(I.getOperand(1));
622   SDOperand FalseVal = getValue(I.getOperand(2));
623   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
624                            TrueVal, FalseVal));
625 }
626
627 void SelectionDAGLowering::visitCast(User &I) {
628   SDOperand N = getValue(I.getOperand(0));
629   MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
630   MVT::ValueType DestTy = TLI.getValueType(I.getType());
631
632   if (N.getValueType() == DestTy) {
633     setValue(&I, N);  // noop cast.
634   } else if (DestTy == MVT::i1) {
635     // Cast to bool is a comparison against zero, not truncation to zero.
636     SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
637                                        DAG.getConstantFP(0.0, N.getValueType());
638     setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
639   } else if (isInteger(SrcTy)) {
640     if (isInteger(DestTy)) {        // Int -> Int cast
641       if (DestTy < SrcTy)   // Truncating cast?
642         setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
643       else if (I.getOperand(0)->getType()->isSigned())
644         setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
645       else
646         setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
647     } else {                        // Int -> FP cast
648       if (I.getOperand(0)->getType()->isSigned())
649         setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
650       else
651         setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
652     }
653   } else {
654     assert(isFloatingPoint(SrcTy) && "Unknown value type!");
655     if (isFloatingPoint(DestTy)) {  // FP -> FP cast
656       if (DestTy < SrcTy)   // Rounding cast?
657         setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
658       else
659         setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
660     } else {                        // FP -> Int cast.
661       if (I.getType()->isSigned())
662         setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
663       else
664         setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
665     }
666   }
667 }
668
669 void SelectionDAGLowering::visitGetElementPtr(User &I) {
670   SDOperand N = getValue(I.getOperand(0));
671   const Type *Ty = I.getOperand(0)->getType();
672   const Type *UIntPtrTy = TD.getIntPtrType();
673
674   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
675        OI != E; ++OI) {
676     Value *Idx = *OI;
677     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
678       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
679       if (Field) {
680         // N = N + Offset
681         uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
682         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
683                         getIntPtrConstant(Offset));
684       }
685       Ty = StTy->getElementType(Field);
686     } else {
687       Ty = cast<SequentialType>(Ty)->getElementType();
688
689       // If this is a constant subscript, handle it quickly.
690       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
691         if (CI->getRawValue() == 0) continue;
692
693         uint64_t Offs;
694         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
695           Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
696         else
697           Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
698         N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
699         continue;
700       }
701       
702       // N = N + Idx * ElementSize;
703       uint64_t ElementSize = TD.getTypeSize(Ty);
704       SDOperand IdxN = getValue(Idx);
705
706       // If the index is smaller or larger than intptr_t, truncate or extend
707       // it.
708       if (IdxN.getValueType() < N.getValueType()) {
709         if (Idx->getType()->isSigned())
710           IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
711         else
712           IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
713       } else if (IdxN.getValueType() > N.getValueType())
714         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
715
716       // If this is a multiply by a power of two, turn it into a shl
717       // immediately.  This is a very common case.
718       if (isPowerOf2_64(ElementSize)) {
719         unsigned Amt = Log2_64(ElementSize);
720         IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
721                            DAG.getConstant(Amt, TLI.getShiftAmountTy()));
722         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
723         continue;
724       }
725       
726       SDOperand Scale = getIntPtrConstant(ElementSize);
727       IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
728       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
729     }
730   }
731   setValue(&I, N);
732 }
733
734 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
735   // If this is a fixed sized alloca in the entry block of the function,
736   // allocate it statically on the stack.
737   if (FuncInfo.StaticAllocaMap.count(&I))
738     return;   // getValue will auto-populate this.
739
740   const Type *Ty = I.getAllocatedType();
741   uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
742   unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
743                             I.getAlignment());
744
745   SDOperand AllocSize = getValue(I.getArraySize());
746   MVT::ValueType IntPtr = TLI.getPointerTy();
747   if (IntPtr < AllocSize.getValueType())
748     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
749   else if (IntPtr > AllocSize.getValueType())
750     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
751
752   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
753                           getIntPtrConstant(TySize));
754
755   // Handle alignment.  If the requested alignment is less than or equal to the
756   // stack alignment, ignore it and round the size of the allocation up to the
757   // stack alignment size.  If the size is greater than the stack alignment, we
758   // note this in the DYNAMIC_STACKALLOC node.
759   unsigned StackAlign =
760     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
761   if (Align <= StackAlign) {
762     Align = 0;
763     // Add SA-1 to the size.
764     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
765                             getIntPtrConstant(StackAlign-1));
766     // Mask out the low bits for alignment purposes.
767     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
768                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
769   }
770
771   std::vector<MVT::ValueType> VTs;
772   VTs.push_back(AllocSize.getValueType());
773   VTs.push_back(MVT::Other);
774   std::vector<SDOperand> Ops;
775   Ops.push_back(getRoot());
776   Ops.push_back(AllocSize);
777   Ops.push_back(getIntPtrConstant(Align));
778   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
779   DAG.setRoot(setValue(&I, DSA).getValue(1));
780
781   // Inform the Frame Information that we have just allocated a variable-sized
782   // object.
783   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
784 }
785
786 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
787 /// global into a string value.  Return an empty string if we can't do it.
788 ///
789 static std::string getStringValue(Value *V, unsigned Offset = 0) {
790   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
791     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
792       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
793       if (Init->isString()) {
794         std::string Result = Init->getAsString();
795         if (Offset < Result.size()) {
796           // If we are pointing INTO The string, erase the beginning...
797           Result.erase(Result.begin(), Result.begin()+Offset);
798
799           // Take off the null terminator, and any string fragments after it.
800           std::string::size_type NullPos = Result.find_first_of((char)0);
801           if (NullPos != std::string::npos)
802             Result.erase(Result.begin()+NullPos, Result.end());
803           return Result;
804         }
805       }
806     }
807   } else if (Constant *C = dyn_cast<Constant>(V)) {
808     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
809       return getStringValue(GV, Offset);
810     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
811       if (CE->getOpcode() == Instruction::GetElementPtr) {
812         // Turn a gep into the specified offset.
813         if (CE->getNumOperands() == 3 &&
814             cast<Constant>(CE->getOperand(1))->isNullValue() &&
815             isa<ConstantInt>(CE->getOperand(2))) {
816           return getStringValue(CE->getOperand(0),
817                    Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
818         }
819       }
820     }
821   }
822   return "";
823 }
824
825 void SelectionDAGLowering::visitLoad(LoadInst &I) {
826   SDOperand Ptr = getValue(I.getOperand(0));
827
828   SDOperand Root;
829   if (I.isVolatile())
830     Root = getRoot();
831   else {
832     // Do not serialize non-volatile loads against each other.
833     Root = DAG.getRoot();
834   }
835   
836   const Type *Ty = I.getType();
837   SDOperand L;
838   
839   if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
840     unsigned NumElements = PTy->getNumElements();
841     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
842     MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
843     
844     // Immediately scalarize packed types containing only one element, so that
845     // the Legalize pass does not have to deal with them.
846     if (NumElements == 1) {
847       L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
848     } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
849       L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
850     } else {
851       L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, 
852                          DAG.getSrcValue(I.getOperand(0)));
853     }
854   } else {
855     L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, 
856                     DAG.getSrcValue(I.getOperand(0)));
857   }
858   setValue(&I, L);
859
860   if (I.isVolatile())
861     DAG.setRoot(L.getValue(1));
862   else
863     PendingLoads.push_back(L.getValue(1));
864 }
865
866
867 void SelectionDAGLowering::visitStore(StoreInst &I) {
868   Value *SrcV = I.getOperand(0);
869   SDOperand Src = getValue(SrcV);
870   SDOperand Ptr = getValue(I.getOperand(1));
871   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
872                           DAG.getSrcValue(I.getOperand(1))));
873 }
874
875 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
876 /// we want to emit this as a call to a named external function, return the name
877 /// otherwise lower it and return null.
878 const char *
879 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
880   switch (Intrinsic) {
881   case Intrinsic::vastart:  visitVAStart(I); return 0;
882   case Intrinsic::vaend:    visitVAEnd(I); return 0;
883   case Intrinsic::vacopy:   visitVACopy(I); return 0;
884   case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
885   case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
886   case Intrinsic::setjmp:
887     return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
888     break;
889   case Intrinsic::longjmp:
890     return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
891     break;
892   case Intrinsic::memcpy:  visitMemIntrinsic(I, ISD::MEMCPY); return 0;
893   case Intrinsic::memset:  visitMemIntrinsic(I, ISD::MEMSET); return 0;
894   case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
895     
896   case Intrinsic::readport:
897   case Intrinsic::readio: {
898     std::vector<MVT::ValueType> VTs;
899     VTs.push_back(TLI.getValueType(I.getType()));
900     VTs.push_back(MVT::Other);
901     std::vector<SDOperand> Ops;
902     Ops.push_back(getRoot());
903     Ops.push_back(getValue(I.getOperand(1)));
904     SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
905                                 ISD::READPORT : ISD::READIO, VTs, Ops);
906     
907     setValue(&I, Tmp);
908     DAG.setRoot(Tmp.getValue(1));
909     return 0;
910   }
911   case Intrinsic::writeport:
912   case Intrinsic::writeio:
913     DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
914                             ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
915                             getRoot(), getValue(I.getOperand(1)),
916                             getValue(I.getOperand(2))));
917     return 0;
918     
919   case Intrinsic::dbg_stoppoint: {
920     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
921       return "llvm_debugger_stop";
922     
923     std::string fname = "<unknown>";
924     std::vector<SDOperand> Ops;
925
926     // Input Chain
927     Ops.push_back(getRoot());
928     
929     // line number
930     Ops.push_back(getValue(I.getOperand(2)));
931    
932     // column
933     Ops.push_back(getValue(I.getOperand(3)));
934
935     // filename/working dir
936     // Pull the filename out of the the compilation unit.
937     const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
938     if (cunit && cunit->hasInitializer()) {
939       if (ConstantStruct *CS = 
940             dyn_cast<ConstantStruct>(cunit->getInitializer())) {
941         if (CS->getNumOperands() > 0) {
942           Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
943           Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
944         }
945       }
946     }
947     
948     if (Ops.size() == 5)  // Found filename/workingdir.
949       DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
950     setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
951     return 0;
952   }
953   case Intrinsic::dbg_region_start:
954     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
955       return "llvm_dbg_region_start";
956     if (I.getType() != Type::VoidTy)
957       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
958     return 0;
959   case Intrinsic::dbg_region_end:
960     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
961       return "llvm_dbg_region_end";
962     if (I.getType() != Type::VoidTy)
963       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
964     return 0;
965   case Intrinsic::dbg_func_start:
966     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
967       return "llvm_dbg_subprogram";
968     if (I.getType() != Type::VoidTy)
969       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
970     return 0;
971   case Intrinsic::dbg_declare:
972     if (I.getType() != Type::VoidTy)
973       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
974     return 0;
975     
976   case Intrinsic::isunordered_f32:
977   case Intrinsic::isunordered_f64:
978     setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
979                               getValue(I.getOperand(2)), ISD::SETUO));
980     return 0;
981     
982   case Intrinsic::sqrt_f32:
983   case Intrinsic::sqrt_f64:
984     setValue(&I, DAG.getNode(ISD::FSQRT,
985                              getValue(I.getOperand(1)).getValueType(),
986                              getValue(I.getOperand(1))));
987     return 0;
988   case Intrinsic::pcmarker: {
989     SDOperand Tmp = getValue(I.getOperand(1));
990     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
991     return 0;
992   }
993   case Intrinsic::readcyclecounter: {
994     std::vector<MVT::ValueType> VTs;
995     VTs.push_back(MVT::i64);
996     VTs.push_back(MVT::Other);
997     std::vector<SDOperand> Ops;
998     Ops.push_back(getRoot());
999     SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1000     setValue(&I, Tmp);
1001     DAG.setRoot(Tmp.getValue(1));
1002     return 0;
1003   }
1004   case Intrinsic::bswap_i16:
1005   case Intrinsic::bswap_i32:
1006   case Intrinsic::bswap_i64:
1007     setValue(&I, DAG.getNode(ISD::BSWAP,
1008                              getValue(I.getOperand(1)).getValueType(),
1009                              getValue(I.getOperand(1))));
1010     return 0;
1011   case Intrinsic::cttz_i8:
1012   case Intrinsic::cttz_i16:
1013   case Intrinsic::cttz_i32:
1014   case Intrinsic::cttz_i64:
1015     setValue(&I, DAG.getNode(ISD::CTTZ,
1016                              getValue(I.getOperand(1)).getValueType(),
1017                              getValue(I.getOperand(1))));
1018     return 0;
1019   case Intrinsic::ctlz_i8:
1020   case Intrinsic::ctlz_i16:
1021   case Intrinsic::ctlz_i32:
1022   case Intrinsic::ctlz_i64:
1023     setValue(&I, DAG.getNode(ISD::CTLZ,
1024                              getValue(I.getOperand(1)).getValueType(),
1025                              getValue(I.getOperand(1))));
1026     return 0;
1027   case Intrinsic::ctpop_i8:
1028   case Intrinsic::ctpop_i16:
1029   case Intrinsic::ctpop_i32:
1030   case Intrinsic::ctpop_i64:
1031     setValue(&I, DAG.getNode(ISD::CTPOP,
1032                              getValue(I.getOperand(1)).getValueType(),
1033                              getValue(I.getOperand(1))));
1034     return 0;
1035   case Intrinsic::stacksave: {
1036     std::vector<MVT::ValueType> VTs;
1037     VTs.push_back(TLI.getPointerTy());
1038     VTs.push_back(MVT::Other);
1039     std::vector<SDOperand> Ops;
1040     Ops.push_back(getRoot());
1041     SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1042     setValue(&I, Tmp);
1043     DAG.setRoot(Tmp.getValue(1));
1044     return 0;
1045   }
1046   case Intrinsic::stackrestore:
1047     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, DAG.getRoot(),
1048                             getValue(I.getOperand(1))));
1049     return 0;
1050   case Intrinsic::prefetch:
1051     // FIXME: Currently discarding prefetches.
1052     return 0;
1053   default:
1054     std::cerr << I;
1055     assert(0 && "This intrinsic is not implemented yet!");
1056     return 0;
1057   }
1058 }
1059
1060
1061 void SelectionDAGLowering::visitCall(CallInst &I) {
1062   const char *RenameFn = 0;
1063   if (Function *F = I.getCalledFunction()) {
1064     if (F->isExternal())
1065       if (unsigned IID = F->getIntrinsicID()) {
1066         RenameFn = visitIntrinsicCall(I, IID);
1067         if (!RenameFn)
1068           return;
1069       } else {    // Not an LLVM intrinsic.
1070         const std::string &Name = F->getName();
1071         if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1072           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1073               I.getOperand(1)->getType()->isFloatingPoint() &&
1074               I.getType() == I.getOperand(1)->getType()) {
1075             SDOperand Tmp = getValue(I.getOperand(1));
1076             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1077             return;
1078           }
1079         } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1080           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1081               I.getOperand(1)->getType()->isFloatingPoint() &&
1082               I.getType() == I.getOperand(1)->getType() &&
1083               TLI.isOperationLegal(ISD::FSIN,
1084                                  TLI.getValueType(I.getOperand(1)->getType()))) {
1085             SDOperand Tmp = getValue(I.getOperand(1));
1086             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1087             return;
1088           }
1089         } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1090           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1091               I.getOperand(1)->getType()->isFloatingPoint() &&
1092               I.getType() == I.getOperand(1)->getType() &&
1093               TLI.isOperationLegal(ISD::FCOS,
1094                               TLI.getValueType(I.getOperand(1)->getType()))) {
1095             SDOperand Tmp = getValue(I.getOperand(1));
1096             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1097             return;
1098           }
1099         }
1100       }
1101   }
1102
1103   SDOperand Callee;
1104   if (!RenameFn)
1105     Callee = getValue(I.getOperand(0));
1106   else
1107     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1108   std::vector<std::pair<SDOperand, const Type*> > Args;
1109   Args.reserve(I.getNumOperands());
1110   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1111     Value *Arg = I.getOperand(i);
1112     SDOperand ArgNode = getValue(Arg);
1113     Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1114   }
1115
1116   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1117   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1118
1119   std::pair<SDOperand,SDOperand> Result =
1120     TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1121                     I.isTailCall(), Callee, Args, DAG);
1122   if (I.getType() != Type::VoidTy)
1123     setValue(&I, Result.first);
1124   DAG.setRoot(Result.second);
1125 }
1126
1127 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1128   SDOperand Src = getValue(I.getOperand(0));
1129
1130   MVT::ValueType IntPtr = TLI.getPointerTy();
1131
1132   if (IntPtr < Src.getValueType())
1133     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1134   else if (IntPtr > Src.getValueType())
1135     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1136
1137   // Scale the source by the type size.
1138   uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1139   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1140                     Src, getIntPtrConstant(ElementSize));
1141
1142   std::vector<std::pair<SDOperand, const Type*> > Args;
1143   Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1144
1145   std::pair<SDOperand,SDOperand> Result =
1146     TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1147                     DAG.getExternalSymbol("malloc", IntPtr),
1148                     Args, DAG);
1149   setValue(&I, Result.first);  // Pointers always fit in registers
1150   DAG.setRoot(Result.second);
1151 }
1152
1153 void SelectionDAGLowering::visitFree(FreeInst &I) {
1154   std::vector<std::pair<SDOperand, const Type*> > Args;
1155   Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1156                                 TLI.getTargetData().getIntPtrType()));
1157   MVT::ValueType IntPtr = TLI.getPointerTy();
1158   std::pair<SDOperand,SDOperand> Result =
1159     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1160                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1161   DAG.setRoot(Result.second);
1162 }
1163
1164 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
1165 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1166 // instructions are special in various ways, which require special support to
1167 // insert.  The specified MachineInstr is created but not inserted into any
1168 // basic blocks, and the scheduler passes ownership of it to this method.
1169 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1170                                                        MachineBasicBlock *MBB) {
1171   std::cerr << "If a target marks an instruction with "
1172                "'usesCustomDAGSchedInserter', it must implement "
1173                "TargetLowering::InsertAtEndOfBasicBlock!\n";
1174   abort();
1175   return 0;  
1176 }
1177
1178 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1179                                         SelectionDAG &DAG) {
1180   return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1181 }
1182
1183 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1184                                        SDOperand VAListP, Value *VAListV,
1185                                        SelectionDAG &DAG) {
1186   // We have no sane default behavior, just emit a useful error message and bail
1187   // out.
1188   std::cerr << "Variable arguments handling not implemented on this target!\n";
1189   abort();
1190   return SDOperand();
1191 }
1192
1193 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
1194                                      SelectionDAG &DAG) {
1195   // Default to a noop.
1196   return Chain;
1197 }
1198
1199 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1200                                       SDOperand SrcP, Value *SrcV,
1201                                       SDOperand DestP, Value *DestV,
1202                                       SelectionDAG &DAG) {
1203   // Default to copying the input list.
1204   SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1205                               SrcP, DAG.getSrcValue(SrcV));
1206   SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
1207                                  Val, DestP, DAG.getSrcValue(DestV));
1208   return Result;
1209 }
1210
1211 std::pair<SDOperand,SDOperand>
1212 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1213                            const Type *ArgTy, SelectionDAG &DAG) {
1214   // We have no sane default behavior, just emit a useful error message and bail
1215   // out.
1216   std::cerr << "Variable arguments handling not implemented on this target!\n";
1217   abort();
1218   return std::make_pair(SDOperand(), SDOperand());
1219 }
1220
1221
1222 void SelectionDAGLowering::visitVAStart(CallInst &I) {
1223   DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1224                                I.getOperand(1), DAG));
1225 }
1226
1227 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1228   std::pair<SDOperand,SDOperand> Result =
1229     TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
1230                    I.getType(), DAG);
1231   setValue(&I, Result.first);
1232   DAG.setRoot(Result.second);
1233 }
1234
1235 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1236   DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
1237                              I.getOperand(1), DAG));
1238 }
1239
1240 void SelectionDAGLowering::visitVACopy(CallInst &I) {
1241   SDOperand Result =
1242     TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1243                     getValue(I.getOperand(1)), I.getOperand(1), DAG);
1244   DAG.setRoot(Result);
1245 }
1246
1247
1248 // It is always conservatively correct for llvm.returnaddress and
1249 // llvm.frameaddress to return 0.
1250 std::pair<SDOperand, SDOperand>
1251 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1252                                         unsigned Depth, SelectionDAG &DAG) {
1253   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1254 }
1255
1256 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1257   assert(0 && "LowerOperation not implemented for this target!");
1258   abort();
1259   return SDOperand();
1260 }
1261
1262 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1263   unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1264   std::pair<SDOperand,SDOperand> Result =
1265     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1266   setValue(&I, Result.first);
1267   DAG.setRoot(Result.second);
1268 }
1269
1270 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1271 #if 0
1272   // If the size of the cpy/move/set is constant (known)
1273   if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1274     uint64_t size = op3->getValue();
1275     switch (Op) {
1276       case ISD::MEMSET: 
1277         if (size <= TLI.getMaxStoresPerMemSet()) {
1278           if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1279         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1280             uint64_t align = op4.getValue();
1281             while (size > align) {
1282               size -=align;
1283             }
1284   Value *SrcV = I.getOperand(0);
1285   SDOperand Src = getValue(SrcV);
1286   SDOperand Ptr = getValue(I.getOperand(1));
1287   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1288                           DAG.getSrcValue(I.getOperand(1))));
1289           }
1290           break;
1291         }
1292         break; // don't do this optimization, use a normal memset
1293       case ISD::MEMMOVE: 
1294       case ISD::MEMCPY:
1295         break; // FIXME: not implemented yet
1296     }
1297   }
1298 #endif
1299
1300   // Non-optimized version
1301   std::vector<SDOperand> Ops;
1302   Ops.push_back(getRoot());
1303   Ops.push_back(getValue(I.getOperand(1)));
1304   Ops.push_back(getValue(I.getOperand(2)));
1305   Ops.push_back(getValue(I.getOperand(3)));
1306   Ops.push_back(getValue(I.getOperand(4)));
1307   DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1308 }
1309
1310 //===----------------------------------------------------------------------===//
1311 // SelectionDAGISel code
1312 //===----------------------------------------------------------------------===//
1313
1314 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1315   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1316 }
1317
1318 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1319   // FIXME: we only modify the CFG to split critical edges.  This
1320   // updates dom and loop info.
1321 }
1322
1323
1324 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1325 /// casting to the type of GEPI.
1326 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1327                                    Value *Ptr, Value *PtrOffset) {
1328   if (V) return V;   // Already computed.
1329   
1330   BasicBlock::iterator InsertPt;
1331   if (BB == GEPI->getParent()) {
1332     // If insert into the GEP's block, insert right after the GEP.
1333     InsertPt = GEPI;
1334     ++InsertPt;
1335   } else {
1336     // Otherwise, insert at the top of BB, after any PHI nodes
1337     InsertPt = BB->begin();
1338     while (isa<PHINode>(InsertPt)) ++InsertPt;
1339   }
1340   
1341   // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1342   // BB so that there is only one value live across basic blocks (the cast 
1343   // operand).
1344   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1345     if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1346       Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1347   
1348   // Add the offset, cast it to the right type.
1349   Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1350   Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1351   return V = Ptr;
1352 }
1353
1354
1355 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1356 /// selection, we want to be a bit careful about some things.  In particular, if
1357 /// we have a GEP instruction that is used in a different block than it is
1358 /// defined, the addressing expression of the GEP cannot be folded into loads or
1359 /// stores that use it.  In this case, decompose the GEP and move constant
1360 /// indices into blocks that use it.
1361 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1362                                   const TargetData &TD) {
1363   // If this GEP is only used inside the block it is defined in, there is no
1364   // need to rewrite it.
1365   bool isUsedOutsideDefBB = false;
1366   BasicBlock *DefBB = GEPI->getParent();
1367   for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end(); 
1368        UI != E; ++UI) {
1369     if (cast<Instruction>(*UI)->getParent() != DefBB) {
1370       isUsedOutsideDefBB = true;
1371       break;
1372     }
1373   }
1374   if (!isUsedOutsideDefBB) return;
1375
1376   // If this GEP has no non-zero constant indices, there is nothing we can do,
1377   // ignore it.
1378   bool hasConstantIndex = false;
1379   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1380        E = GEPI->op_end(); OI != E; ++OI) {
1381     if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1382       if (CI->getRawValue()) {
1383         hasConstantIndex = true;
1384         break;
1385       }
1386   }
1387   // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1388   if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
1389   
1390   // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
1391   // constant offset (which we now know is non-zero) and deal with it later.
1392   uint64_t ConstantOffset = 0;
1393   const Type *UIntPtrTy = TD.getIntPtrType();
1394   Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1395   const Type *Ty = GEPI->getOperand(0)->getType();
1396
1397   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1398        E = GEPI->op_end(); OI != E; ++OI) {
1399     Value *Idx = *OI;
1400     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1401       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1402       if (Field)
1403         ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1404       Ty = StTy->getElementType(Field);
1405     } else {
1406       Ty = cast<SequentialType>(Ty)->getElementType();
1407
1408       // Handle constant subscripts.
1409       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1410         if (CI->getRawValue() == 0) continue;
1411         
1412         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1413           ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1414         else
1415           ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1416         continue;
1417       }
1418       
1419       // Ptr = Ptr + Idx * ElementSize;
1420       
1421       // Cast Idx to UIntPtrTy if needed.
1422       Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1423       
1424       uint64_t ElementSize = TD.getTypeSize(Ty);
1425       // Mask off bits that should not be set.
1426       ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1427       Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1428
1429       // Multiply by the element size and add to the base.
1430       Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1431       Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1432     }
1433   }
1434   
1435   // Make sure that the offset fits in uintptr_t.
1436   ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1437   Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1438   
1439   // Okay, we have now emitted all of the variable index parts to the BB that
1440   // the GEP is defined in.  Loop over all of the using instructions, inserting
1441   // an "add Ptr, ConstantOffset" into each block that uses it and update the
1442   // instruction to use the newly computed value, making GEPI dead.  When the
1443   // user is a load or store instruction address, we emit the add into the user
1444   // block, otherwise we use a canonical version right next to the gep (these 
1445   // won't be foldable as addresses, so we might as well share the computation).
1446   
1447   std::map<BasicBlock*,Value*> InsertedExprs;
1448   while (!GEPI->use_empty()) {
1449     Instruction *User = cast<Instruction>(GEPI->use_back());
1450
1451     // If this use is not foldable into the addressing mode, use a version 
1452     // emitted in the GEP block.
1453     Value *NewVal;
1454     if (!isa<LoadInst>(User) &&
1455         (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1456       NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI, 
1457                                     Ptr, PtrOffset);
1458     } else {
1459       // Otherwise, insert the code in the User's block so it can be folded into
1460       // any users in that block.
1461       NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()], 
1462                                     User->getParent(), GEPI, 
1463                                     Ptr, PtrOffset);
1464     }
1465     User->replaceUsesOfWith(GEPI, NewVal);
1466   }
1467   
1468   // Finally, the GEP is dead, remove it.
1469   GEPI->eraseFromParent();
1470 }
1471
1472 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1473   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1474   RegMap = MF.getSSARegMap();
1475   DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1476
1477   // First, split all critical edges for PHI nodes with incoming values that are
1478   // constants, this way the load of the constant into a vreg will not be placed
1479   // into MBBs that are used some other way.
1480   //
1481   // In this pass we also look for GEP instructions that are used across basic
1482   // blocks and rewrites them to improve basic-block-at-a-time selection.
1483   // 
1484   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1485     PHINode *PN;
1486     BasicBlock::iterator BBI;
1487     for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1488       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1489         if (isa<Constant>(PN->getIncomingValue(i)))
1490           SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1491     
1492     for (BasicBlock::iterator E = BB->end(); BBI != E; )
1493       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1494         OptimizeGEPExpression(GEPI, TLI.getTargetData());
1495   }
1496   
1497   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1498
1499   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1500     SelectBasicBlock(I, MF, FuncInfo);
1501
1502   return true;
1503 }
1504
1505
1506 SDOperand SelectionDAGISel::
1507 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1508   SDOperand Op = SDL.getValue(V);
1509   assert((Op.getOpcode() != ISD::CopyFromReg ||
1510           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1511          "Copy from a reg to the same reg!");
1512   
1513   // If this type is not legal, we must make sure to not create an invalid
1514   // register use.
1515   MVT::ValueType SrcVT = Op.getValueType();
1516   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1517   SelectionDAG &DAG = SDL.DAG;
1518   if (SrcVT == DestVT) {
1519     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1520   } else if (SrcVT < DestVT) {
1521     // The src value is promoted to the register.
1522     if (MVT::isFloatingPoint(SrcVT))
1523       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1524     else
1525       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1526     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1527   } else  {
1528     // The src value is expanded into multiple registers.
1529     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1530                                Op, DAG.getConstant(0, MVT::i32));
1531     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1532                                Op, DAG.getConstant(1, MVT::i32));
1533     Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1534     return DAG.getCopyToReg(Op, Reg+1, Hi);
1535   }
1536 }
1537
1538 void SelectionDAGISel::
1539 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1540                std::vector<SDOperand> &UnorderedChains) {
1541   // If this is the entry block, emit arguments.
1542   Function &F = *BB->getParent();
1543   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1544   SDOperand OldRoot = SDL.DAG.getRoot();
1545   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1546
1547   unsigned a = 0;
1548   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1549        AI != E; ++AI, ++a)
1550     if (!AI->use_empty()) {
1551       SDL.setValue(AI, Args[a]);
1552       
1553       // If this argument is live outside of the entry block, insert a copy from
1554       // whereever we got it to the vreg that other BB's will reference it as.
1555       if (FuncInfo.ValueMap.count(AI)) {
1556         SDOperand Copy =
1557           CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1558         UnorderedChains.push_back(Copy);
1559       }
1560     }
1561
1562   // Next, if the function has live ins that need to be copied into vregs,
1563   // emit the copies now, into the top of the block.
1564   MachineFunction &MF = SDL.DAG.getMachineFunction();
1565   if (MF.livein_begin() != MF.livein_end()) {
1566     SSARegMap *RegMap = MF.getSSARegMap();
1567     const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1568     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1569          E = MF.livein_end(); LI != E; ++LI)
1570       if (LI->second)
1571         MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1572                          LI->first, RegMap->getRegClass(LI->second));
1573   }
1574     
1575   // Finally, if the target has anything special to do, allow it to do so.
1576   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1577 }
1578
1579
1580 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1581        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1582                                     FunctionLoweringInfo &FuncInfo) {
1583   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1584
1585   std::vector<SDOperand> UnorderedChains;
1586
1587   // Lower any arguments needed in this block if this is the entry block.
1588   if (LLVMBB == &LLVMBB->getParent()->front())
1589     LowerArguments(LLVMBB, SDL, UnorderedChains);
1590
1591   BB = FuncInfo.MBBMap[LLVMBB];
1592   SDL.setCurrentBasicBlock(BB);
1593
1594   // Lower all of the non-terminator instructions.
1595   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1596        I != E; ++I)
1597     SDL.visit(*I);
1598
1599   // Ensure that all instructions which are used outside of their defining
1600   // blocks are available as virtual registers.
1601   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1602     if (!I->use_empty() && !isa<PHINode>(I)) {
1603       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1604       if (VMI != FuncInfo.ValueMap.end())
1605         UnorderedChains.push_back(
1606                            CopyValueToVirtualRegister(SDL, I, VMI->second));
1607     }
1608
1609   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
1610   // ensure constants are generated when needed.  Remember the virtual registers
1611   // that need to be added to the Machine PHI nodes as input.  We cannot just
1612   // directly add them, because expansion might result in multiple MBB's for one
1613   // BB.  As such, the start of the BB might correspond to a different MBB than
1614   // the end.
1615   //
1616
1617   // Emit constants only once even if used by multiple PHI nodes.
1618   std::map<Constant*, unsigned> ConstantsOut;
1619
1620   // Check successor nodes PHI nodes that expect a constant to be available from
1621   // this block.
1622   TerminatorInst *TI = LLVMBB->getTerminator();
1623   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1624     BasicBlock *SuccBB = TI->getSuccessor(succ);
1625     MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1626     PHINode *PN;
1627
1628     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1629     // nodes and Machine PHI nodes, but the incoming operands have not been
1630     // emitted yet.
1631     for (BasicBlock::iterator I = SuccBB->begin();
1632          (PN = dyn_cast<PHINode>(I)); ++I)
1633       if (!PN->use_empty()) {
1634         unsigned Reg;
1635         Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1636         if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1637           unsigned &RegOut = ConstantsOut[C];
1638           if (RegOut == 0) {
1639             RegOut = FuncInfo.CreateRegForValue(C);
1640             UnorderedChains.push_back(
1641                              CopyValueToVirtualRegister(SDL, C, RegOut));
1642           }
1643           Reg = RegOut;
1644         } else {
1645           Reg = FuncInfo.ValueMap[PHIOp];
1646           if (Reg == 0) {
1647             assert(isa<AllocaInst>(PHIOp) &&
1648                    FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1649                    "Didn't codegen value into a register!??");
1650             Reg = FuncInfo.CreateRegForValue(PHIOp);
1651             UnorderedChains.push_back(
1652                              CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1653           }
1654         }
1655
1656         // Remember that this register needs to added to the machine PHI node as
1657         // the input for this MBB.
1658         unsigned NumElements =
1659           TLI.getNumElements(TLI.getValueType(PN->getType()));
1660         for (unsigned i = 0, e = NumElements; i != e; ++i)
1661           PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1662       }
1663   }
1664   ConstantsOut.clear();
1665
1666   // Turn all of the unordered chains into one factored node.
1667   if (!UnorderedChains.empty()) {
1668     SDOperand Root = SDL.getRoot();
1669     if (Root.getOpcode() != ISD::EntryToken) {
1670       unsigned i = 0, e = UnorderedChains.size();
1671       for (; i != e; ++i) {
1672         assert(UnorderedChains[i].Val->getNumOperands() > 1);
1673         if (UnorderedChains[i].Val->getOperand(0) == Root)
1674           break;  // Don't add the root if we already indirectly depend on it.
1675       }
1676         
1677       if (i == e)
1678         UnorderedChains.push_back(Root);
1679     }
1680     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1681   }
1682
1683   // Lower the terminator after the copies are emitted.
1684   SDL.visit(*LLVMBB->getTerminator());
1685
1686   // Make sure the root of the DAG is up-to-date.
1687   DAG.setRoot(SDL.getRoot());
1688 }
1689
1690 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1691                                         FunctionLoweringInfo &FuncInfo) {
1692   SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
1693   CurDAG = &DAG;
1694   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1695
1696   // First step, lower LLVM code to some DAG.  This DAG may use operations and
1697   // types that are not supported by the target.
1698   BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1699
1700   // Run the DAG combiner in pre-legalize mode.
1701   DAG.Combine(false);
1702   
1703   DEBUG(std::cerr << "Lowered selection DAG:\n");
1704   DEBUG(DAG.dump());
1705
1706   // Second step, hack on the DAG until it only uses operations and types that
1707   // the target supports.
1708   DAG.Legalize();
1709
1710   DEBUG(std::cerr << "Legalized selection DAG:\n");
1711   DEBUG(DAG.dump());
1712
1713   // Run the DAG combiner in post-legalize mode.
1714   DAG.Combine(true);
1715   
1716   if (ViewISelDAGs) DAG.viewGraph();
1717   
1718   // Third, instruction select all of the operations to machine code, adding the
1719   // code to the MachineBasicBlock.
1720   InstructionSelectBasicBlock(DAG);
1721
1722   DEBUG(std::cerr << "Selected machine code:\n");
1723   DEBUG(BB->dump());
1724
1725   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1726   // PHI nodes in successors.
1727   for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1728     MachineInstr *PHI = PHINodesToUpdate[i].first;
1729     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1730            "This is not a machine PHI node that we are updating!");
1731     PHI->addRegOperand(PHINodesToUpdate[i].second);
1732     PHI->addMachineBasicBlockOperand(BB);
1733   }
1734
1735   // Finally, add the CFG edges from the last selected MBB to the successor
1736   // MBBs.
1737   TerminatorInst *TI = LLVMBB->getTerminator();
1738   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1739     MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1740     BB->addSuccessor(Succ0MBB);
1741   }
1742 }
1743
1744 //===----------------------------------------------------------------------===//
1745 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1746 /// target node in the graph.
1747 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1748   if (ViewSchedDAGs) DAG.viewGraph();
1749   ScheduleDAG *SL = createSimpleDAGScheduler(DAG, BB);
1750   SL->Run();
1751 }