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