Add the necessary support to the ISel to allow targets to codegen the new
[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/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include <map>
37 #include <iostream>
38 using namespace llvm;
39
40 #ifndef NDEBUG
41 static cl::opt<bool>
42 ViewDAGs("view-isel-dags", cl::Hidden,
43          cl::desc("Pop up a window to show isel dags as they are selected"));
44 #else
45 static const bool ViewDAGs = 0;
46 #endif
47
48
49 namespace llvm {
50   //===--------------------------------------------------------------------===//
51   /// FunctionLoweringInfo - This contains information that is global to a
52   /// function that is used when lowering a region of the function.
53   class FunctionLoweringInfo {
54   public:
55     TargetLowering &TLI;
56     Function &Fn;
57     MachineFunction &MF;
58     SSARegMap *RegMap;
59
60     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
61
62     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
63     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
64
65     /// ValueMap - Since we emit code for the function a basic block at a time,
66     /// we must remember which virtual registers hold the values for
67     /// cross-basic-block values.
68     std::map<const Value*, unsigned> ValueMap;
69
70     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
71     /// the entry block.  This allows the allocas to be efficiently referenced
72     /// anywhere in the function.
73     std::map<const AllocaInst*, int> StaticAllocaMap;
74
75     unsigned MakeReg(MVT::ValueType VT) {
76       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
77     }
78
79     unsigned CreateRegForValue(const Value *V) {
80       MVT::ValueType VT = TLI.getValueType(V->getType());
81       // The common case is that we will only create one register for this
82       // value.  If we have that case, create and return the virtual register.
83       unsigned NV = TLI.getNumElements(VT);
84       if (NV == 1) {
85         // If we are promoting this value, pick the next largest supported type.
86         return MakeReg(TLI.getTypeToTransformTo(VT));
87       }
88
89       // If this value is represented with multiple target registers, make sure
90       // to create enough consequtive registers of the right (smaller) type.
91       unsigned NT = VT-1;  // Find the type to use.
92       while (TLI.getNumElements((MVT::ValueType)NT) != 1)
93         --NT;
94
95       unsigned R = MakeReg((MVT::ValueType)NT);
96       for (unsigned i = 1; i != NV; ++i)
97         MakeReg((MVT::ValueType)NT);
98       return R;
99     }
100
101     unsigned InitializeRegForValue(const Value *V) {
102       unsigned &R = ValueMap[V];
103       assert(R == 0 && "Already initialized this value register!");
104       return R = CreateRegForValue(V);
105     }
106   };
107 }
108
109 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
110 /// PHI nodes or outside of the basic block that defines it.
111 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
112   if (isa<PHINode>(I)) return true;
113   BasicBlock *BB = I->getParent();
114   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
115     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
116       return true;
117   return false;
118 }
119
120 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
121 /// entry block, return true.
122 static bool isOnlyUsedInEntryBlock(Argument *A) {
123   BasicBlock *Entry = A->getParent()->begin();
124   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
125     if (cast<Instruction>(*UI)->getParent() != Entry)
126       return false;  // Use not in entry block.
127   return true;
128 }
129
130 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
131                                            Function &fn, MachineFunction &mf)
132     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
133
134   // Create a vreg for each argument register that is not dead and is used
135   // outside of the entry block for the function.
136   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
137        AI != E; ++AI)
138     if (!isOnlyUsedInEntryBlock(AI))
139       InitializeRegForValue(AI);
140
141   // Initialize the mapping of values to registers.  This is only set up for
142   // instruction values that are used outside of the block that defines
143   // them.
144   Function::iterator BB = Fn.begin(), EB = Fn.end();
145   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
146     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
147       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
148         const Type *Ty = AI->getAllocatedType();
149         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
150         unsigned Align = 
151           std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
152                    AI->getAlignment());
153
154         // If the alignment of the value is smaller than the size of the value,
155         // and if the size of the value is particularly small (<= 8 bytes),
156         // round up to the size of the value for potentially better performance.
157         //
158         // FIXME: This could be made better with a preferred alignment hook in
159         // TargetData.  It serves primarily to 8-byte align doubles for X86.
160         if (Align < TySize && TySize <= 8) Align = TySize;
161         TySize *= CUI->getValue();   // Get total allocated size.
162         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
163         StaticAllocaMap[AI] =
164           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
165       }
166
167   for (; BB != EB; ++BB)
168     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
169       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
170         if (!isa<AllocaInst>(I) ||
171             !StaticAllocaMap.count(cast<AllocaInst>(I)))
172           InitializeRegForValue(I);
173
174   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
175   // also creates the initial PHI MachineInstrs, though none of the input
176   // operands are populated.
177   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
178     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
179     MBBMap[BB] = MBB;
180     MF.getBasicBlockList().push_back(MBB);
181
182     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
183     // appropriate.
184     PHINode *PN;
185     for (BasicBlock::iterator I = BB->begin();
186          (PN = dyn_cast<PHINode>(I)); ++I)
187       if (!PN->use_empty()) {
188         unsigned NumElements =
189           TLI.getNumElements(TLI.getValueType(PN->getType()));
190         unsigned PHIReg = ValueMap[PN];
191         assert(PHIReg &&"PHI node does not have an assigned virtual register!");
192         for (unsigned i = 0; i != NumElements; ++i)
193           BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
194       }
195   }
196 }
197
198
199
200 //===----------------------------------------------------------------------===//
201 /// SelectionDAGLowering - This is the common target-independent lowering
202 /// implementation that is parameterized by a TargetLowering object.
203 /// Also, targets can overload any lowering method.
204 ///
205 namespace llvm {
206 class SelectionDAGLowering {
207   MachineBasicBlock *CurMBB;
208
209   std::map<const Value*, SDOperand> NodeMap;
210
211   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
212   /// them up and then emit token factor nodes when possible.  This allows us to
213   /// get simple disambiguation between loads without worrying about alias
214   /// analysis.
215   std::vector<SDOperand> PendingLoads;
216
217 public:
218   // TLI - This is information that describes the available target features we
219   // need for lowering.  This indicates when operations are unavailable,
220   // implemented with a libcall, etc.
221   TargetLowering &TLI;
222   SelectionDAG &DAG;
223   const TargetData &TD;
224
225   /// FuncInfo - Information about the function as a whole.
226   ///
227   FunctionLoweringInfo &FuncInfo;
228
229   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
230                        FunctionLoweringInfo &funcinfo)
231     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
232       FuncInfo(funcinfo) {
233   }
234
235   /// getRoot - Return the current virtual root of the Selection DAG.
236   ///
237   SDOperand getRoot() {
238     if (PendingLoads.empty())
239       return DAG.getRoot();
240
241     if (PendingLoads.size() == 1) {
242       SDOperand Root = PendingLoads[0];
243       DAG.setRoot(Root);
244       PendingLoads.clear();
245       return Root;
246     }
247
248     // Otherwise, we have to make a token factor node.
249     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
250     PendingLoads.clear();
251     DAG.setRoot(Root);
252     return Root;
253   }
254
255   void visit(Instruction &I) { visit(I.getOpcode(), I); }
256
257   void visit(unsigned Opcode, User &I) {
258     switch (Opcode) {
259     default: assert(0 && "Unknown instruction type encountered!");
260              abort();
261       // Build the switch statement using the Instruction.def file.
262 #define HANDLE_INST(NUM, OPCODE, CLASS) \
263     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
264 #include "llvm/Instruction.def"
265     }
266   }
267
268   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
269
270
271   SDOperand getIntPtrConstant(uint64_t Val) {
272     return DAG.getConstant(Val, TLI.getPointerTy());
273   }
274
275   SDOperand getValue(const Value *V) {
276     SDOperand &N = NodeMap[V];
277     if (N.Val) return N;
278
279     MVT::ValueType VT = TLI.getValueType(V->getType());
280     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
281       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
282         visit(CE->getOpcode(), *CE);
283         assert(N.Val && "visit didn't populate the ValueMap!");
284         return N;
285       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
286         return N = DAG.getGlobalAddress(GV, VT);
287       } else if (isa<ConstantPointerNull>(C)) {
288         return N = DAG.getConstant(0, TLI.getPointerTy());
289       } else if (isa<UndefValue>(C)) {
290         return N = DAG.getNode(ISD::UNDEF, VT);
291       } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
292         return N = DAG.getConstantFP(CFP->getValue(), VT);
293       } else {
294         // Canonicalize all constant ints to be unsigned.
295         return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
296       }
297
298     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
299       std::map<const AllocaInst*, int>::iterator SI =
300         FuncInfo.StaticAllocaMap.find(AI);
301       if (SI != FuncInfo.StaticAllocaMap.end())
302         return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
303     }
304
305     std::map<const Value*, unsigned>::const_iterator VMI =
306       FuncInfo.ValueMap.find(V);
307     assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
308
309     unsigned InReg = VMI->second;
310    
311     // If this type is not legal, make it so now.
312     MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
313     
314     N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
315     if (DestVT < VT) {
316       // Source must be expanded.  This input value is actually coming from the
317       // register pair VMI->second and VMI->second+1.
318       N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
319                       DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
320     } else {
321       if (DestVT > VT) { // Promotion case
322         if (MVT::isFloatingPoint(VT))
323           N = DAG.getNode(ISD::FP_ROUND, VT, N);
324         else
325           N = DAG.getNode(ISD::TRUNCATE, VT, N);
326       }
327     }
328     
329     return N;
330   }
331
332   const SDOperand &setValue(const Value *V, SDOperand NewN) {
333     SDOperand &N = NodeMap[V];
334     assert(N.Val == 0 && "Already set a value for this node!");
335     return N = NewN;
336   }
337
338   // Terminator instructions.
339   void visitRet(ReturnInst &I);
340   void visitBr(BranchInst &I);
341   void visitUnreachable(UnreachableInst &I) { /* noop */ }
342
343   // These all get lowered before this pass.
344   void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
345   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
346   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
347
348   //
349   void visitBinary(User &I, unsigned Opcode, bool isShift = false);
350   void visitAdd(User &I) {
351     visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
352   }
353   void visitSub(User &I);
354   void visitMul(User &I) {
355     visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
356   }
357   void visitDiv(User &I) {
358     unsigned Opc;
359     const Type *Ty = I.getType();
360     if (Ty->isFloatingPoint())
361       Opc = ISD::FDIV;
362     else if (Ty->isUnsigned())
363       Opc = ISD::UDIV;
364     else
365       Opc = ISD::SDIV;
366     visitBinary(I, Opc);
367   }
368   void visitRem(User &I) {
369     unsigned Opc;
370     const Type *Ty = I.getType();
371     if (Ty->isFloatingPoint())
372       Opc = ISD::FREM;
373     else if (Ty->isUnsigned())
374       Opc = ISD::UREM;
375     else
376       Opc = ISD::SREM;
377     visitBinary(I, Opc);
378   }
379   void visitAnd(User &I) { visitBinary(I, ISD::AND); }
380   void visitOr (User &I) { visitBinary(I, ISD::OR); }
381   void visitXor(User &I) { visitBinary(I, ISD::XOR); }
382   void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
383   void visitShr(User &I) {
384     visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
385   }
386
387   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
388   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
389   void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
390   void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
391   void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
392   void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
393   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
394
395   void visitGetElementPtr(User &I);
396   void visitCast(User &I);
397   void visitSelect(User &I);
398   //
399
400   void visitMalloc(MallocInst &I);
401   void visitFree(FreeInst &I);
402   void visitAlloca(AllocaInst &I);
403   void visitLoad(LoadInst &I);
404   void visitStore(StoreInst &I);
405   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
406   void visitCall(CallInst &I);
407
408   void visitVAStart(CallInst &I);
409   void visitVAArg(VAArgInst &I);
410   void visitVAEnd(CallInst &I);
411   void visitVACopy(CallInst &I);
412   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
413
414   void visitMemIntrinsic(CallInst &I, unsigned Op);
415
416   void visitUserOp1(Instruction &I) {
417     assert(0 && "UserOp1 should not exist at instruction selection time!");
418     abort();
419   }
420   void visitUserOp2(Instruction &I) {
421     assert(0 && "UserOp2 should not exist at instruction selection time!");
422     abort();
423   }
424 };
425 } // end namespace llvm
426
427 void SelectionDAGLowering::visitRet(ReturnInst &I) {
428   if (I.getNumOperands() == 0) {
429     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
430     return;
431   }
432
433   SDOperand Op1 = getValue(I.getOperand(0));
434   MVT::ValueType TmpVT;
435
436   switch (Op1.getValueType()) {
437   default: assert(0 && "Unknown value type!");
438   case MVT::i1:
439   case MVT::i8:
440   case MVT::i16:
441   case MVT::i32:
442     // If this is a machine where 32-bits is legal or expanded, promote to
443     // 32-bits, otherwise, promote to 64-bits.
444     if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
445       TmpVT = TLI.getTypeToTransformTo(MVT::i32);
446     else
447       TmpVT = MVT::i32;
448
449     // Extend integer types to result type.
450     if (I.getOperand(0)->getType()->isSigned())
451       Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
452     else
453       Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
454     break;
455   case MVT::f32:
456   case MVT::i64:
457   case MVT::f64:
458     break; // No extension needed!
459   }
460   // Allow targets to lower this further to meet ABI requirements
461   DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
462 }
463
464 void SelectionDAGLowering::visitBr(BranchInst &I) {
465   // Update machine-CFG edges.
466   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
467
468   // Figure out which block is immediately after the current one.
469   MachineBasicBlock *NextBlock = 0;
470   MachineFunction::iterator BBI = CurMBB;
471   if (++BBI != CurMBB->getParent()->end())
472     NextBlock = BBI;
473
474   if (I.isUnconditional()) {
475     // If this is not a fall-through branch, emit the branch.
476     if (Succ0MBB != NextBlock)
477       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
478                               DAG.getBasicBlock(Succ0MBB)));
479   } else {
480     MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
481
482     SDOperand Cond = getValue(I.getCondition());
483     if (Succ1MBB == NextBlock) {
484       // If the condition is false, fall through.  This means we should branch
485       // if the condition is true to Succ #0.
486       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
487                               Cond, DAG.getBasicBlock(Succ0MBB)));
488     } else if (Succ0MBB == NextBlock) {
489       // If the condition is true, fall through.  This means we should branch if
490       // the condition is false to Succ #1.  Invert the condition first.
491       SDOperand True = DAG.getConstant(1, Cond.getValueType());
492       Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
493       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
494                               Cond, DAG.getBasicBlock(Succ1MBB)));
495     } else {
496       std::vector<SDOperand> Ops;
497       Ops.push_back(getRoot());
498       Ops.push_back(Cond);
499       Ops.push_back(DAG.getBasicBlock(Succ0MBB));
500       Ops.push_back(DAG.getBasicBlock(Succ1MBB));
501       DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
502     }
503   }
504 }
505
506 void SelectionDAGLowering::visitSub(User &I) {
507   // -0.0 - X --> fneg
508   if (I.getType()->isFloatingPoint()) {
509     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
510       if (CFP->isExactlyValue(-0.0)) {
511         SDOperand Op2 = getValue(I.getOperand(1));
512         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
513         return;
514       }
515     visitBinary(I, ISD::FSUB);
516   } else {
517     visitBinary(I, ISD::SUB);
518   }
519 }
520
521 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
522   SDOperand Op1 = getValue(I.getOperand(0));
523   SDOperand Op2 = getValue(I.getOperand(1));
524
525   if (isShift)
526     Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
527
528   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
529 }
530
531 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
532                                       ISD::CondCode UnsignedOpcode) {
533   SDOperand Op1 = getValue(I.getOperand(0));
534   SDOperand Op2 = getValue(I.getOperand(1));
535   ISD::CondCode Opcode = SignedOpcode;
536   if (I.getOperand(0)->getType()->isUnsigned())
537     Opcode = UnsignedOpcode;
538   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
539 }
540
541 void SelectionDAGLowering::visitSelect(User &I) {
542   SDOperand Cond     = getValue(I.getOperand(0));
543   SDOperand TrueVal  = getValue(I.getOperand(1));
544   SDOperand FalseVal = getValue(I.getOperand(2));
545   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
546                            TrueVal, FalseVal));
547 }
548
549 void SelectionDAGLowering::visitCast(User &I) {
550   SDOperand N = getValue(I.getOperand(0));
551   MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
552   MVT::ValueType DestTy = TLI.getValueType(I.getType());
553
554   if (N.getValueType() == DestTy) {
555     setValue(&I, N);  // noop cast.
556   } else if (DestTy == MVT::i1) {
557     // Cast to bool is a comparison against zero, not truncation to zero.
558     SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
559                                        DAG.getConstantFP(0.0, N.getValueType());
560     setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
561   } else if (isInteger(SrcTy)) {
562     if (isInteger(DestTy)) {        // Int -> Int cast
563       if (DestTy < SrcTy)   // Truncating cast?
564         setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
565       else if (I.getOperand(0)->getType()->isSigned())
566         setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
567       else
568         setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
569     } else {                        // Int -> FP cast
570       if (I.getOperand(0)->getType()->isSigned())
571         setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
572       else
573         setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
574     }
575   } else {
576     assert(isFloatingPoint(SrcTy) && "Unknown value type!");
577     if (isFloatingPoint(DestTy)) {  // FP -> FP cast
578       if (DestTy < SrcTy)   // Rounding cast?
579         setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
580       else
581         setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
582     } else {                        // FP -> Int cast.
583       if (I.getType()->isSigned())
584         setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
585       else
586         setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
587     }
588   }
589 }
590
591 void SelectionDAGLowering::visitGetElementPtr(User &I) {
592   SDOperand N = getValue(I.getOperand(0));
593   const Type *Ty = I.getOperand(0)->getType();
594   const Type *UIntPtrTy = TD.getIntPtrType();
595
596   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
597        OI != E; ++OI) {
598     Value *Idx = *OI;
599     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
600       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
601       if (Field) {
602         // N = N + Offset
603         uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
604         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
605                         getIntPtrConstant(Offset));
606       }
607       Ty = StTy->getElementType(Field);
608     } else {
609       Ty = cast<SequentialType>(Ty)->getElementType();
610       if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
611         // N = N + Idx * ElementSize;
612         uint64_t ElementSize = TD.getTypeSize(Ty);
613         SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
614
615         // If the index is smaller or larger than intptr_t, truncate or extend
616         // it.
617         if (IdxN.getValueType() < Scale.getValueType()) {
618           if (Idx->getType()->isSigned())
619             IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
620           else
621             IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
622         } else if (IdxN.getValueType() > Scale.getValueType())
623           IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
624
625         IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
626         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
627       }
628     }
629   }
630   setValue(&I, N);
631 }
632
633 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
634   // If this is a fixed sized alloca in the entry block of the function,
635   // allocate it statically on the stack.
636   if (FuncInfo.StaticAllocaMap.count(&I))
637     return;   // getValue will auto-populate this.
638
639   const Type *Ty = I.getAllocatedType();
640   uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
641   unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
642                             I.getAlignment());
643
644   SDOperand AllocSize = getValue(I.getArraySize());
645   MVT::ValueType IntPtr = TLI.getPointerTy();
646   if (IntPtr < AllocSize.getValueType())
647     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
648   else if (IntPtr > AllocSize.getValueType())
649     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
650
651   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
652                           getIntPtrConstant(TySize));
653
654   // Handle alignment.  If the requested alignment is less than or equal to the
655   // stack alignment, ignore it and round the size of the allocation up to the
656   // stack alignment size.  If the size is greater than the stack alignment, we
657   // note this in the DYNAMIC_STACKALLOC node.
658   unsigned StackAlign =
659     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
660   if (Align <= StackAlign) {
661     Align = 0;
662     // Add SA-1 to the size.
663     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
664                             getIntPtrConstant(StackAlign-1));
665     // Mask out the low bits for alignment purposes.
666     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
667                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
668   }
669
670   std::vector<MVT::ValueType> VTs;
671   VTs.push_back(AllocSize.getValueType());
672   VTs.push_back(MVT::Other);
673   std::vector<SDOperand> Ops;
674   Ops.push_back(getRoot());
675   Ops.push_back(AllocSize);
676   Ops.push_back(getIntPtrConstant(Align));
677   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
678   DAG.setRoot(setValue(&I, DSA).getValue(1));
679
680   // Inform the Frame Information that we have just allocated a variable-sized
681   // object.
682   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
683 }
684
685
686 void SelectionDAGLowering::visitLoad(LoadInst &I) {
687   SDOperand Ptr = getValue(I.getOperand(0));
688
689   SDOperand Root;
690   if (I.isVolatile())
691     Root = getRoot();
692   else {
693     // Do not serialize non-volatile loads against each other.
694     Root = DAG.getRoot();
695   }
696
697   SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
698                             DAG.getSrcValue(I.getOperand(0)));
699   setValue(&I, L);
700
701   if (I.isVolatile())
702     DAG.setRoot(L.getValue(1));
703   else
704     PendingLoads.push_back(L.getValue(1));
705 }
706
707
708 void SelectionDAGLowering::visitStore(StoreInst &I) {
709   Value *SrcV = I.getOperand(0);
710   SDOperand Src = getValue(SrcV);
711   SDOperand Ptr = getValue(I.getOperand(1));
712   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
713                           DAG.getSrcValue(I.getOperand(1))));
714 }
715
716 void SelectionDAGLowering::visitCall(CallInst &I) {
717   const char *RenameFn = 0;
718   SDOperand Tmp;
719   if (Function *F = I.getCalledFunction())
720     if (F->isExternal())
721       switch (F->getIntrinsicID()) {
722       case 0:     // Not an LLVM intrinsic.
723         if (F->getName() == "fabs" || F->getName() == "fabsf") {
724           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
725               I.getOperand(1)->getType()->isFloatingPoint() &&
726               I.getType() == I.getOperand(1)->getType()) {
727             Tmp = getValue(I.getOperand(1));
728             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
729             return;
730           }
731         }
732         else if (F->getName() == "sin" || F->getName() == "sinf") {
733           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
734               I.getOperand(1)->getType()->isFloatingPoint() &&
735               I.getType() == I.getOperand(1)->getType()) {
736             Tmp = getValue(I.getOperand(1));
737             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
738             return;
739           }
740         }
741         else if (F->getName() == "cos" || F->getName() == "cosf") {
742           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
743               I.getOperand(1)->getType()->isFloatingPoint() &&
744               I.getType() == I.getOperand(1)->getType()) {
745             Tmp = getValue(I.getOperand(1));
746             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
747             return;
748           }
749         }
750         break;
751       case Intrinsic::vastart:  visitVAStart(I); return;
752       case Intrinsic::vaend:    visitVAEnd(I); return;
753       case Intrinsic::vacopy:   visitVACopy(I); return;
754       case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
755       case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return;
756
757       case Intrinsic::setjmp:
758         RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
759         break;
760       case Intrinsic::longjmp:
761         RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
762         break;
763       case Intrinsic::memcpy:  visitMemIntrinsic(I, ISD::MEMCPY); return;
764       case Intrinsic::memset:  visitMemIntrinsic(I, ISD::MEMSET); return;
765       case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
766
767       case Intrinsic::readport:
768       case Intrinsic::readio: {
769         std::vector<MVT::ValueType> VTs;
770         VTs.push_back(TLI.getValueType(I.getType()));
771         VTs.push_back(MVT::Other);
772         std::vector<SDOperand> Ops;
773         Ops.push_back(getRoot());
774         Ops.push_back(getValue(I.getOperand(1)));
775         Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
776                           ISD::READPORT : ISD::READIO, VTs, Ops);
777
778         setValue(&I, Tmp);
779         DAG.setRoot(Tmp.getValue(1));
780         return;
781       }
782       case Intrinsic::writeport:
783       case Intrinsic::writeio:
784         DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
785                                 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
786                                 getRoot(), getValue(I.getOperand(1)),
787                                 getValue(I.getOperand(2))));
788         return;
789       case Intrinsic::dbg_stoppoint:
790       case Intrinsic::dbg_region_start:
791       case Intrinsic::dbg_region_end:
792       case Intrinsic::dbg_func_start:
793       case Intrinsic::dbg_declare:
794         if (I.getType() != Type::VoidTy)
795           setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
796         return;
797
798       case Intrinsic::isunordered:
799         setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
800                                   getValue(I.getOperand(2)), ISD::SETUO));
801         return;
802
803       case Intrinsic::sqrt:
804         setValue(&I, DAG.getNode(ISD::FSQRT,
805                                  getValue(I.getOperand(1)).getValueType(),
806                                  getValue(I.getOperand(1))));
807         return;
808
809       case Intrinsic::pcmarker:
810         Tmp = getValue(I.getOperand(1));
811         DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
812         return;
813       case Intrinsic::cttz:
814         setValue(&I, DAG.getNode(ISD::CTTZ,
815                                  getValue(I.getOperand(1)).getValueType(),
816                                  getValue(I.getOperand(1))));
817         return;
818       case Intrinsic::ctlz:
819         setValue(&I, DAG.getNode(ISD::CTLZ,
820                                  getValue(I.getOperand(1)).getValueType(),
821                                  getValue(I.getOperand(1))));
822         return;
823       case Intrinsic::ctpop:
824         setValue(&I, DAG.getNode(ISD::CTPOP,
825                                  getValue(I.getOperand(1)).getValueType(),
826                                  getValue(I.getOperand(1))));
827         return;
828       default:
829         std::cerr << I;
830         assert(0 && "This intrinsic is not implemented yet!");
831         return;
832       }
833
834   SDOperand Callee;
835   if (!RenameFn)
836     Callee = getValue(I.getOperand(0));
837   else
838     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
839   std::vector<std::pair<SDOperand, const Type*> > Args;
840
841   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
842     Value *Arg = I.getOperand(i);
843     SDOperand ArgNode = getValue(Arg);
844     Args.push_back(std::make_pair(ArgNode, Arg->getType()));
845   }
846
847   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
848   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
849
850   std::pair<SDOperand,SDOperand> Result =
851     TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
852                     I.isTailCall(), Callee, Args, DAG);
853   if (I.getType() != Type::VoidTy)
854     setValue(&I, Result.first);
855   DAG.setRoot(Result.second);
856 }
857
858 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
859   SDOperand Src = getValue(I.getOperand(0));
860
861   MVT::ValueType IntPtr = TLI.getPointerTy();
862
863   if (IntPtr < Src.getValueType())
864     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
865   else if (IntPtr > Src.getValueType())
866     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
867
868   // Scale the source by the type size.
869   uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
870   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
871                     Src, getIntPtrConstant(ElementSize));
872
873   std::vector<std::pair<SDOperand, const Type*> > Args;
874   Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
875
876   std::pair<SDOperand,SDOperand> Result =
877     TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
878                     DAG.getExternalSymbol("malloc", IntPtr),
879                     Args, DAG);
880   setValue(&I, Result.first);  // Pointers always fit in registers
881   DAG.setRoot(Result.second);
882 }
883
884 void SelectionDAGLowering::visitFree(FreeInst &I) {
885   std::vector<std::pair<SDOperand, const Type*> > Args;
886   Args.push_back(std::make_pair(getValue(I.getOperand(0)),
887                                 TLI.getTargetData().getIntPtrType()));
888   MVT::ValueType IntPtr = TLI.getPointerTy();
889   std::pair<SDOperand,SDOperand> Result =
890     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
891                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
892   DAG.setRoot(Result.second);
893 }
894
895 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
896 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
897 // instructions are special in various ways, which require special support to
898 // insert.  The specified MachineInstr is created but not inserted into any
899 // basic blocks, and the scheduler passes ownership of it to this method.
900 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
901                                                        MachineBasicBlock *MBB) {
902   std::cerr << "If a target marks an instruction with "
903                "'usesCustomDAGSchedInserter', it must implement "
904                "TargetLowering::InsertAtEndOfBasicBlock!\n";
905   abort();
906   return 0;  
907 }
908
909 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
910                                         SelectionDAG &DAG) {
911   return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
912 }
913
914 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
915                                        SDOperand VAListP, Value *VAListV,
916                                        SelectionDAG &DAG) {
917   // We have no sane default behavior, just emit a useful error message and bail
918   // out.
919   std::cerr << "Variable arguments handling not implemented on this target!\n";
920   abort();
921   return SDOperand();
922 }
923
924 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
925                                      SelectionDAG &DAG) {
926   // Default to a noop.
927   return Chain;
928 }
929
930 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
931                                       SDOperand SrcP, Value *SrcV,
932                                       SDOperand DestP, Value *DestV,
933                                       SelectionDAG &DAG) {
934   // Default to copying the input list.
935   SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
936                               SrcP, DAG.getSrcValue(SrcV));
937   SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
938                                  Val, DestP, DAG.getSrcValue(DestV));
939   return Result;
940 }
941
942 std::pair<SDOperand,SDOperand>
943 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
944                            const Type *ArgTy, SelectionDAG &DAG) {
945   // We have no sane default behavior, just emit a useful error message and bail
946   // out.
947   std::cerr << "Variable arguments handling not implemented on this target!\n";
948   abort();
949   return std::make_pair(SDOperand(), SDOperand());
950 }
951
952
953 void SelectionDAGLowering::visitVAStart(CallInst &I) {
954   DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
955                                I.getOperand(1), DAG));
956 }
957
958 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
959   std::pair<SDOperand,SDOperand> Result =
960     TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
961                    I.getType(), DAG);
962   setValue(&I, Result.first);
963   DAG.setRoot(Result.second);
964 }
965
966 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
967   DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
968                              I.getOperand(1), DAG));
969 }
970
971 void SelectionDAGLowering::visitVACopy(CallInst &I) {
972   SDOperand Result =
973     TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
974                     getValue(I.getOperand(1)), I.getOperand(1), DAG);
975   DAG.setRoot(Result);
976 }
977
978
979 // It is always conservatively correct for llvm.returnaddress and
980 // llvm.frameaddress to return 0.
981 std::pair<SDOperand, SDOperand>
982 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
983                                         unsigned Depth, SelectionDAG &DAG) {
984   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
985 }
986
987 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
988   assert(0 && "LowerOperation not implemented for this target!");
989   abort();
990   return SDOperand();
991 }
992
993 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
994   unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
995   std::pair<SDOperand,SDOperand> Result =
996     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
997   setValue(&I, Result.first);
998   DAG.setRoot(Result.second);
999 }
1000
1001 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1002   std::vector<SDOperand> Ops;
1003   Ops.push_back(getRoot());
1004   Ops.push_back(getValue(I.getOperand(1)));
1005   Ops.push_back(getValue(I.getOperand(2)));
1006   Ops.push_back(getValue(I.getOperand(3)));
1007   Ops.push_back(getValue(I.getOperand(4)));
1008   DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1009 }
1010
1011 //===----------------------------------------------------------------------===//
1012 // SelectionDAGISel code
1013 //===----------------------------------------------------------------------===//
1014
1015 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1016   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1017 }
1018
1019 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1020   // FIXME: we only modify the CFG to split critical edges.  This
1021   // updates dom and loop info.
1022 }
1023
1024
1025 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1026   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1027   RegMap = MF.getSSARegMap();
1028   DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1029
1030   // First pass, split all critical edges for PHI nodes with incoming values
1031   // that are constants, this way the load of the constant into a vreg will not
1032   // be placed into MBBs that are used some other way.
1033   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1034     PHINode *PN;
1035     for (BasicBlock::iterator BBI = BB->begin();
1036          (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1037       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1038         if (isa<Constant>(PN->getIncomingValue(i)))
1039           SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1040   }
1041
1042   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1043
1044   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1045     SelectBasicBlock(I, MF, FuncInfo);
1046
1047   return true;
1048 }
1049
1050
1051 SDOperand SelectionDAGISel::
1052 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1053   SDOperand Op = SDL.getValue(V);
1054   assert((Op.getOpcode() != ISD::CopyFromReg ||
1055           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1056          "Copy from a reg to the same reg!");
1057   
1058   // If this type is not legal, we must make sure to not create an invalid
1059   // register use.
1060   MVT::ValueType SrcVT = Op.getValueType();
1061   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1062   SelectionDAG &DAG = SDL.DAG;
1063   if (SrcVT == DestVT) {
1064     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1065   } else if (SrcVT < DestVT) {
1066     // The src value is promoted to the register.
1067     if (MVT::isFloatingPoint(SrcVT))
1068       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1069     else
1070       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1071     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1072   } else  {
1073     // The src value is expanded into multiple registers.
1074     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1075                                Op, DAG.getConstant(0, MVT::i32));
1076     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1077                                Op, DAG.getConstant(1, MVT::i32));
1078     Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1079     return DAG.getCopyToReg(Op, Reg+1, Hi);
1080   }
1081 }
1082
1083 void SelectionDAGISel::
1084 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1085                std::vector<SDOperand> &UnorderedChains) {
1086   // If this is the entry block, emit arguments.
1087   Function &F = *BB->getParent();
1088   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1089   SDOperand OldRoot = SDL.DAG.getRoot();
1090   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1091
1092   unsigned a = 0;
1093   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1094        AI != E; ++AI, ++a)
1095     if (!AI->use_empty()) {
1096       SDL.setValue(AI, Args[a]);
1097       
1098       // If this argument is live outside of the entry block, insert a copy from
1099       // whereever we got it to the vreg that other BB's will reference it as.
1100       if (FuncInfo.ValueMap.count(AI)) {
1101         SDOperand Copy =
1102           CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1103         UnorderedChains.push_back(Copy);
1104       }
1105     }
1106
1107   // Next, if the function has live ins that need to be copied into vregs,
1108   // emit the copies now, into the top of the block.
1109   MachineFunction &MF = SDL.DAG.getMachineFunction();
1110   if (MF.livein_begin() != MF.livein_end()) {
1111     SSARegMap *RegMap = MF.getSSARegMap();
1112     const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1113     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1114          E = MF.livein_end(); LI != E; ++LI)
1115       if (LI->second)
1116         MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1117                          LI->first, RegMap->getRegClass(LI->second));
1118   }
1119     
1120   // Finally, if the target has anything special to do, allow it to do so.
1121   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1122 }
1123
1124
1125 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1126        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1127                                     FunctionLoweringInfo &FuncInfo) {
1128   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1129
1130   std::vector<SDOperand> UnorderedChains;
1131
1132   // Lower any arguments needed in this block if this is the entry block.
1133   if (LLVMBB == &LLVMBB->getParent()->front())
1134     LowerArguments(LLVMBB, SDL, UnorderedChains);
1135
1136   BB = FuncInfo.MBBMap[LLVMBB];
1137   SDL.setCurrentBasicBlock(BB);
1138
1139   // Lower all of the non-terminator instructions.
1140   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1141        I != E; ++I)
1142     SDL.visit(*I);
1143
1144   // Ensure that all instructions which are used outside of their defining
1145   // blocks are available as virtual registers.
1146   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1147     if (!I->use_empty() && !isa<PHINode>(I)) {
1148       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1149       if (VMI != FuncInfo.ValueMap.end())
1150         UnorderedChains.push_back(
1151                            CopyValueToVirtualRegister(SDL, I, VMI->second));
1152     }
1153
1154   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
1155   // ensure constants are generated when needed.  Remember the virtual registers
1156   // that need to be added to the Machine PHI nodes as input.  We cannot just
1157   // directly add them, because expansion might result in multiple MBB's for one
1158   // BB.  As such, the start of the BB might correspond to a different MBB than
1159   // the end.
1160   //
1161
1162   // Emit constants only once even if used by multiple PHI nodes.
1163   std::map<Constant*, unsigned> ConstantsOut;
1164
1165   // Check successor nodes PHI nodes that expect a constant to be available from
1166   // this block.
1167   TerminatorInst *TI = LLVMBB->getTerminator();
1168   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1169     BasicBlock *SuccBB = TI->getSuccessor(succ);
1170     MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1171     PHINode *PN;
1172
1173     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1174     // nodes and Machine PHI nodes, but the incoming operands have not been
1175     // emitted yet.
1176     for (BasicBlock::iterator I = SuccBB->begin();
1177          (PN = dyn_cast<PHINode>(I)); ++I)
1178       if (!PN->use_empty()) {
1179         unsigned Reg;
1180         Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1181         if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1182           unsigned &RegOut = ConstantsOut[C];
1183           if (RegOut == 0) {
1184             RegOut = FuncInfo.CreateRegForValue(C);
1185             UnorderedChains.push_back(
1186                              CopyValueToVirtualRegister(SDL, C, RegOut));
1187           }
1188           Reg = RegOut;
1189         } else {
1190           Reg = FuncInfo.ValueMap[PHIOp];
1191           if (Reg == 0) {
1192             assert(isa<AllocaInst>(PHIOp) &&
1193                    FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1194                    "Didn't codegen value into a register!??");
1195             Reg = FuncInfo.CreateRegForValue(PHIOp);
1196             UnorderedChains.push_back(
1197                              CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1198           }
1199         }
1200
1201         // Remember that this register needs to added to the machine PHI node as
1202         // the input for this MBB.
1203         unsigned NumElements =
1204           TLI.getNumElements(TLI.getValueType(PN->getType()));
1205         for (unsigned i = 0, e = NumElements; i != e; ++i)
1206           PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1207       }
1208   }
1209   ConstantsOut.clear();
1210
1211   // Turn all of the unordered chains into one factored node.
1212   if (!UnorderedChains.empty()) {
1213     UnorderedChains.push_back(SDL.getRoot());
1214     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1215   }
1216
1217   // Lower the terminator after the copies are emitted.
1218   SDL.visit(*LLVMBB->getTerminator());
1219
1220   // Make sure the root of the DAG is up-to-date.
1221   DAG.setRoot(SDL.getRoot());
1222 }
1223
1224 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1225                                         FunctionLoweringInfo &FuncInfo) {
1226   SelectionDAG DAG(TLI, MF);
1227   CurDAG = &DAG;
1228   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1229
1230   // First step, lower LLVM code to some DAG.  This DAG may use operations and
1231   // types that are not supported by the target.
1232   BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1233
1234   // Run the DAG combiner in pre-legalize mode.
1235   DAG.Combine(false);
1236   
1237   DEBUG(std::cerr << "Lowered selection DAG:\n");
1238   DEBUG(DAG.dump());
1239
1240   // Second step, hack on the DAG until it only uses operations and types that
1241   // the target supports.
1242   DAG.Legalize();
1243
1244   DEBUG(std::cerr << "Legalized selection DAG:\n");
1245   DEBUG(DAG.dump());
1246
1247   // Run the DAG combiner in post-legalize mode.
1248   DAG.Combine(true);
1249   
1250   if (ViewDAGs) DAG.viewGraph();
1251   
1252   // Third, instruction select all of the operations to machine code, adding the
1253   // code to the MachineBasicBlock.
1254   InstructionSelectBasicBlock(DAG);
1255
1256   DEBUG(std::cerr << "Selected machine code:\n");
1257   DEBUG(BB->dump());
1258
1259   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1260   // PHI nodes in successors.
1261   for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1262     MachineInstr *PHI = PHINodesToUpdate[i].first;
1263     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1264            "This is not a machine PHI node that we are updating!");
1265     PHI->addRegOperand(PHINodesToUpdate[i].second);
1266     PHI->addMachineBasicBlockOperand(BB);
1267   }
1268
1269   // Finally, add the CFG edges from the last selected MBB to the successor
1270   // MBBs.
1271   TerminatorInst *TI = LLVMBB->getTerminator();
1272   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1273     MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1274     BB->addSuccessor(Succ0MBB);
1275   }
1276 }