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