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