Remove dead vars
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Target/MRegisterInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetFrameInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Debug.h"
44 #include <map>
45 #include <set>
46 #include <iostream>
47 #include <algorithm>
48 using namespace llvm;
49
50 #ifndef NDEBUG
51 static cl::opt<bool>
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53           cl::desc("Pop up a window to show isel dags as they are selected"));
54 static cl::opt<bool>
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56           cl::desc("Pop up a window to show sched dags as they are processed"));
57 #else
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
59 #endif
60
61 namespace {
62   cl::opt<ScheduleDAG::SchedHeuristics>
63   ISHeuristic(
64     "sched",
65     cl::desc("Choose scheduling style"),
66     cl::init(ScheduleDAG::defaultScheduling),
67     cl::values(
68       clEnumValN(ScheduleDAG::defaultScheduling, "default",
69                  "Target preferred scheduling style"),
70       clEnumValN(ScheduleDAG::noScheduling, "none",
71                  "No scheduling: breadth first sequencing"),
72       clEnumValN(ScheduleDAG::simpleScheduling, "simple",
73                  "Simple two pass scheduling: minimize critical path "
74                  "and maximize processor utilization"),
75       clEnumValN(ScheduleDAG::simpleNoItinScheduling, "simple-noitin",
76                  "Simple two pass scheduling: Same as simple "
77                  "except using generic latency"),
78       clEnumValN(ScheduleDAG::listSchedulingBURR, "list-burr",
79                  "Bottom-up register reduction list scheduling"),
80       clEnumValN(ScheduleDAG::listSchedulingTDRR, "list-tdrr",
81                  "Top-down register reduction list scheduling"),
82       clEnumValN(ScheduleDAG::listSchedulingTD, "list-td",
83                  "Top-down list scheduler"),
84       clEnumValEnd));
85 } // namespace
86
87 namespace {
88   /// RegsForValue - This struct represents the physical registers that a
89   /// particular value is assigned and the type information about the value.
90   /// This is needed because values can be promoted into larger registers and
91   /// expanded into multiple smaller registers than the value.
92   struct RegsForValue {
93     /// Regs - This list hold the register (for legal and promoted values)
94     /// or register set (for expanded values) that the value should be assigned
95     /// to.
96     std::vector<unsigned> Regs;
97     
98     /// RegVT - The value type of each register.
99     ///
100     MVT::ValueType RegVT;
101     
102     /// ValueVT - The value type of the LLVM value, which may be promoted from
103     /// RegVT or made from merging the two expanded parts.
104     MVT::ValueType ValueVT;
105     
106     RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107     
108     RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109       : RegVT(regvt), ValueVT(valuevt) {
110         Regs.push_back(Reg);
111     }
112     RegsForValue(const std::vector<unsigned> &regs, 
113                  MVT::ValueType regvt, MVT::ValueType valuevt)
114       : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115     }
116     
117     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118     /// this value and returns the result as a ValueVT value.  This uses 
119     /// Chain/Flag as the input and updates them for the output Chain/Flag.
120     SDOperand getCopyFromRegs(SelectionDAG &DAG,
121                               SDOperand &Chain, SDOperand &Flag) const;
122
123     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124     /// specified value into the registers specified by this object.  This uses 
125     /// Chain/Flag as the input and updates them for the output Chain/Flag.
126     void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
127                        SDOperand &Chain, SDOperand &Flag) const;
128     
129     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130     /// operand list.  This adds the code marker and includes the number of 
131     /// values added into it.
132     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
133                               std::vector<SDOperand> &Ops) const;
134   };
135 }
136
137 namespace llvm {
138   //===--------------------------------------------------------------------===//
139   /// FunctionLoweringInfo - This contains information that is global to a
140   /// function that is used when lowering a region of the function.
141   class FunctionLoweringInfo {
142   public:
143     TargetLowering &TLI;
144     Function &Fn;
145     MachineFunction &MF;
146     SSARegMap *RegMap;
147
148     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
149
150     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
151     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
152
153     /// ValueMap - Since we emit code for the function a basic block at a time,
154     /// we must remember which virtual registers hold the values for
155     /// cross-basic-block values.
156     std::map<const Value*, unsigned> ValueMap;
157
158     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
159     /// the entry block.  This allows the allocas to be efficiently referenced
160     /// anywhere in the function.
161     std::map<const AllocaInst*, int> StaticAllocaMap;
162
163     unsigned MakeReg(MVT::ValueType VT) {
164       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
165     }
166
167     unsigned CreateRegForValue(const Value *V);
168     
169     unsigned InitializeRegForValue(const Value *V) {
170       unsigned &R = ValueMap[V];
171       assert(R == 0 && "Already initialized this value register!");
172       return R = CreateRegForValue(V);
173     }
174   };
175 }
176
177 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
178 /// PHI nodes or outside of the basic block that defines it, or used by a 
179 /// switch instruction, which may expand to multiple basic blocks.
180 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
181   if (isa<PHINode>(I)) return true;
182   BasicBlock *BB = I->getParent();
183   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
184     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
185         isa<SwitchInst>(*UI))
186       return true;
187   return false;
188 }
189
190 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
191 /// entry block, return true.  This includes arguments used by switches, since
192 /// the switch may expand into multiple basic blocks.
193 static bool isOnlyUsedInEntryBlock(Argument *A) {
194   BasicBlock *Entry = A->getParent()->begin();
195   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
196     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
197       return false;  // Use not in entry block.
198   return true;
199 }
200
201 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
202                                            Function &fn, MachineFunction &mf)
203     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
204
205   // Create a vreg for each argument register that is not dead and is used
206   // outside of the entry block for the function.
207   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
208        AI != E; ++AI)
209     if (!isOnlyUsedInEntryBlock(AI))
210       InitializeRegForValue(AI);
211
212   // Initialize the mapping of values to registers.  This is only set up for
213   // instruction values that are used outside of the block that defines
214   // them.
215   Function::iterator BB = Fn.begin(), EB = Fn.end();
216   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
217     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
218       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
219         const Type *Ty = AI->getAllocatedType();
220         uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
221         unsigned Align = 
222           std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
223                    AI->getAlignment());
224
225         // If the alignment of the value is smaller than the size of the value,
226         // and if the size of the value is particularly small (<= 8 bytes),
227         // round up to the size of the value for potentially better performance.
228         //
229         // FIXME: This could be made better with a preferred alignment hook in
230         // TargetData.  It serves primarily to 8-byte align doubles for X86.
231         if (Align < TySize && TySize <= 8) Align = TySize;
232         TySize *= CUI->getValue();   // Get total allocated size.
233         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
234         StaticAllocaMap[AI] =
235           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
236       }
237
238   for (; BB != EB; ++BB)
239     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
240       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
241         if (!isa<AllocaInst>(I) ||
242             !StaticAllocaMap.count(cast<AllocaInst>(I)))
243           InitializeRegForValue(I);
244
245   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
246   // also creates the initial PHI MachineInstrs, though none of the input
247   // operands are populated.
248   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
249     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
250     MBBMap[BB] = MBB;
251     MF.getBasicBlockList().push_back(MBB);
252
253     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
254     // appropriate.
255     PHINode *PN;
256     for (BasicBlock::iterator I = BB->begin();
257          (PN = dyn_cast<PHINode>(I)); ++I)
258       if (!PN->use_empty()) {
259         MVT::ValueType VT = TLI.getValueType(PN->getType());
260         unsigned NumElements;
261         if (VT != MVT::Vector)
262           NumElements = TLI.getNumElements(VT);
263         else {
264           MVT::ValueType VT1,VT2;
265           NumElements = 
266             TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
267                                        VT1, VT2);
268         }
269         unsigned PHIReg = ValueMap[PN];
270         assert(PHIReg &&"PHI node does not have an assigned virtual register!");
271         for (unsigned i = 0; i != NumElements; ++i)
272           BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
273       }
274   }
275 }
276
277 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
278 /// the correctly promoted or expanded types.  Assign these registers
279 /// consecutive vreg numbers and return the first assigned number.
280 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
281   MVT::ValueType VT = TLI.getValueType(V->getType());
282   
283   // The number of multiples of registers that we need, to, e.g., split up
284   // a <2 x int64> -> 4 x i32 registers.
285   unsigned NumVectorRegs = 1;
286   
287   // If this is a packed type, figure out what type it will decompose into
288   // and how many of the elements it will use.
289   if (VT == MVT::Vector) {
290     const PackedType *PTy = cast<PackedType>(V->getType());
291     unsigned NumElts = PTy->getNumElements();
292     MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
293     
294     // Divide the input until we get to a supported size.  This will always
295     // end with a scalar if the target doesn't support vectors.
296     while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
297       NumElts >>= 1;
298       NumVectorRegs <<= 1;
299     }
300     if (NumElts == 1)
301       VT = EltTy;
302     else
303       VT = getVectorType(EltTy, NumElts);
304   }
305   
306   // The common case is that we will only create one register for this
307   // value.  If we have that case, create and return the virtual register.
308   unsigned NV = TLI.getNumElements(VT);
309   if (NV == 1) {
310     // If we are promoting this value, pick the next largest supported type.
311     MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
312     unsigned Reg = MakeReg(PromotedType);
313     // If this is a vector of supported or promoted types (e.g. 4 x i16),
314     // create all of the registers.
315     for (unsigned i = 1; i != NumVectorRegs; ++i)
316       MakeReg(PromotedType);
317     return Reg;
318   }
319   
320   // If this value is represented with multiple target registers, make sure
321   // to create enough consecutive registers of the right (smaller) type.
322   unsigned NT = VT-1;  // Find the type to use.
323   while (TLI.getNumElements((MVT::ValueType)NT) != 1)
324     --NT;
325   
326   unsigned R = MakeReg((MVT::ValueType)NT);
327   for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
328     MakeReg((MVT::ValueType)NT);
329   return R;
330 }
331
332 //===----------------------------------------------------------------------===//
333 /// SelectionDAGLowering - This is the common target-independent lowering
334 /// implementation that is parameterized by a TargetLowering object.
335 /// Also, targets can overload any lowering method.
336 ///
337 namespace llvm {
338 class SelectionDAGLowering {
339   MachineBasicBlock *CurMBB;
340
341   std::map<const Value*, SDOperand> NodeMap;
342
343   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
344   /// them up and then emit token factor nodes when possible.  This allows us to
345   /// get simple disambiguation between loads without worrying about alias
346   /// analysis.
347   std::vector<SDOperand> PendingLoads;
348
349   /// Case - A pair of values to record the Value for a switch case, and the
350   /// case's target basic block.  
351   typedef std::pair<Constant*, MachineBasicBlock*> Case;
352   typedef std::vector<Case>::iterator              CaseItr;
353   typedef std::pair<CaseItr, CaseItr>              CaseRange;
354
355   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
356   /// of conditional branches.
357   struct CaseRec {
358     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
359     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
360
361     /// CaseBB - The MBB in which to emit the compare and branch
362     MachineBasicBlock *CaseBB;
363     /// LT, GE - If nonzero, we know the current case value must be less-than or
364     /// greater-than-or-equal-to these Constants.
365     Constant *LT;
366     Constant *GE;
367     /// Range - A pair of iterators representing the range of case values to be
368     /// processed at this point in the binary search tree.
369     CaseRange Range;
370   };
371   
372   /// The comparison function for sorting Case values.
373   struct CaseCmp {
374     bool operator () (const Case& C1, const Case& C2) {
375       if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
376         return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
377       
378       const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
379       return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
380     }
381   };
382   
383 public:
384   // TLI - This is information that describes the available target features we
385   // need for lowering.  This indicates when operations are unavailable,
386   // implemented with a libcall, etc.
387   TargetLowering &TLI;
388   SelectionDAG &DAG;
389   const TargetData *TD;
390
391   /// SwitchCases - Vector of CaseBlock structures used to communicate
392   /// SwitchInst code generation information.
393   std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
394   SelectionDAGISel::JumpTable JT;
395   
396   /// FuncInfo - Information about the function as a whole.
397   ///
398   FunctionLoweringInfo &FuncInfo;
399
400   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
401                        FunctionLoweringInfo &funcinfo)
402     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
403       JT(0,0,0,0), FuncInfo(funcinfo) {
404   }
405
406   /// getRoot - Return the current virtual root of the Selection DAG.
407   ///
408   SDOperand getRoot() {
409     if (PendingLoads.empty())
410       return DAG.getRoot();
411
412     if (PendingLoads.size() == 1) {
413       SDOperand Root = PendingLoads[0];
414       DAG.setRoot(Root);
415       PendingLoads.clear();
416       return Root;
417     }
418
419     // Otherwise, we have to make a token factor node.
420     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
421     PendingLoads.clear();
422     DAG.setRoot(Root);
423     return Root;
424   }
425
426   void visit(Instruction &I) { visit(I.getOpcode(), I); }
427
428   void visit(unsigned Opcode, User &I) {
429     switch (Opcode) {
430     default: assert(0 && "Unknown instruction type encountered!");
431              abort();
432       // Build the switch statement using the Instruction.def file.
433 #define HANDLE_INST(NUM, OPCODE, CLASS) \
434     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
435 #include "llvm/Instruction.def"
436     }
437   }
438
439   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
440
441   SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
442                         SDOperand SrcValue, SDOperand Root,
443                         bool isVolatile);
444
445   SDOperand getIntPtrConstant(uint64_t Val) {
446     return DAG.getConstant(Val, TLI.getPointerTy());
447   }
448
449   SDOperand getValue(const Value *V);
450
451   const SDOperand &setValue(const Value *V, SDOperand NewN) {
452     SDOperand &N = NodeMap[V];
453     assert(N.Val == 0 && "Already set a value for this node!");
454     return N = NewN;
455   }
456   
457   RegsForValue GetRegistersForValue(const std::string &ConstrCode,
458                                     MVT::ValueType VT,
459                                     bool OutReg, bool InReg,
460                                     std::set<unsigned> &OutputRegs, 
461                                     std::set<unsigned> &InputRegs);
462
463   // Terminator instructions.
464   void visitRet(ReturnInst &I);
465   void visitBr(BranchInst &I);
466   void visitSwitch(SwitchInst &I);
467   void visitUnreachable(UnreachableInst &I) { /* noop */ }
468
469   // Helper for visitSwitch
470   void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
471   void visitJumpTable(SelectionDAGISel::JumpTable &JT);
472   
473   // These all get lowered before this pass.
474   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
475   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
476
477   void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
478   void visitShift(User &I, unsigned Opcode);
479   void visitAdd(User &I) { 
480     visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD); 
481   }
482   void visitSub(User &I);
483   void visitMul(User &I) { 
484     visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL); 
485   }
486   void visitDiv(User &I) {
487     const Type *Ty = I.getType();
488     visitBinary(I,
489                 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
490                 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
491   }
492   void visitRem(User &I) {
493     const Type *Ty = I.getType();
494     visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
495   }
496   void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
497   void visitOr (User &I) { visitBinary(I, ISD::OR,  0, ISD::VOR); }
498   void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
499   void visitShl(User &I) { visitShift(I, ISD::SHL); }
500   void visitShr(User &I) { 
501     visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
502   }
503
504   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
505   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
506   void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
507   void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
508   void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
509   void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
510   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
511
512   void visitExtractElement(User &I);
513   void visitInsertElement(User &I);
514   void visitShuffleVector(User &I);
515
516   void visitGetElementPtr(User &I);
517   void visitCast(User &I);
518   void visitSelect(User &I);
519
520   void visitMalloc(MallocInst &I);
521   void visitFree(FreeInst &I);
522   void visitAlloca(AllocaInst &I);
523   void visitLoad(LoadInst &I);
524   void visitStore(StoreInst &I);
525   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
526   void visitCall(CallInst &I);
527   void visitInlineAsm(CallInst &I);
528   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
529   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
530
531   void visitVAStart(CallInst &I);
532   void visitVAArg(VAArgInst &I);
533   void visitVAEnd(CallInst &I);
534   void visitVACopy(CallInst &I);
535   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
536
537   void visitMemIntrinsic(CallInst &I, unsigned Op);
538
539   void visitUserOp1(Instruction &I) {
540     assert(0 && "UserOp1 should not exist at instruction selection time!");
541     abort();
542   }
543   void visitUserOp2(Instruction &I) {
544     assert(0 && "UserOp2 should not exist at instruction selection time!");
545     abort();
546   }
547 };
548 } // end namespace llvm
549
550 SDOperand SelectionDAGLowering::getValue(const Value *V) {
551   SDOperand &N = NodeMap[V];
552   if (N.Val) return N;
553   
554   const Type *VTy = V->getType();
555   MVT::ValueType VT = TLI.getValueType(VTy);
556   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
557     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
558       visit(CE->getOpcode(), *CE);
559       assert(N.Val && "visit didn't populate the ValueMap!");
560       return N;
561     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
562       return N = DAG.getGlobalAddress(GV, VT);
563     } else if (isa<ConstantPointerNull>(C)) {
564       return N = DAG.getConstant(0, TLI.getPointerTy());
565     } else if (isa<UndefValue>(C)) {
566       if (!isa<PackedType>(VTy))
567         return N = DAG.getNode(ISD::UNDEF, VT);
568
569       // Create a VBUILD_VECTOR of undef nodes.
570       const PackedType *PTy = cast<PackedType>(VTy);
571       unsigned NumElements = PTy->getNumElements();
572       MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
573
574       std::vector<SDOperand> Ops;
575       Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
576       
577       // Create a VConstant node with generic Vector type.
578       Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
579       Ops.push_back(DAG.getValueType(PVT));
580       return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
581     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
582       return N = DAG.getConstantFP(CFP->getValue(), VT);
583     } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
584       unsigned NumElements = PTy->getNumElements();
585       MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
586       
587       // Now that we know the number and type of the elements, push a
588       // Constant or ConstantFP node onto the ops list for each element of
589       // the packed constant.
590       std::vector<SDOperand> Ops;
591       if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
592         for (unsigned i = 0; i != NumElements; ++i)
593           Ops.push_back(getValue(CP->getOperand(i)));
594       } else {
595         assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
596         SDOperand Op;
597         if (MVT::isFloatingPoint(PVT))
598           Op = DAG.getConstantFP(0, PVT);
599         else
600           Op = DAG.getConstant(0, PVT);
601         Ops.assign(NumElements, Op);
602       }
603       
604       // Create a VBUILD_VECTOR node with generic Vector type.
605       Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
606       Ops.push_back(DAG.getValueType(PVT));
607       return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
608     } else {
609       // Canonicalize all constant ints to be unsigned.
610       return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
611     }
612   }
613       
614   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
615     std::map<const AllocaInst*, int>::iterator SI =
616     FuncInfo.StaticAllocaMap.find(AI);
617     if (SI != FuncInfo.StaticAllocaMap.end())
618       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
619   }
620       
621   std::map<const Value*, unsigned>::const_iterator VMI =
622       FuncInfo.ValueMap.find(V);
623   assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
624   
625   unsigned InReg = VMI->second;
626   
627   // If this type is not legal, make it so now.
628   if (VT != MVT::Vector) {
629     MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
630   
631     N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
632     if (DestVT < VT) {
633       // Source must be expanded.  This input value is actually coming from the
634       // register pair VMI->second and VMI->second+1.
635       N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
636                       DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
637     } else if (DestVT > VT) { // Promotion case
638       if (MVT::isFloatingPoint(VT))
639         N = DAG.getNode(ISD::FP_ROUND, VT, N);
640       else
641         N = DAG.getNode(ISD::TRUNCATE, VT, N);
642     }
643   } else {
644     // Otherwise, if this is a vector, make it available as a generic vector
645     // here.
646     MVT::ValueType PTyElementVT, PTyLegalElementVT;
647     const PackedType *PTy = cast<PackedType>(VTy);
648     unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
649                                              PTyLegalElementVT);
650
651     // Build a VBUILD_VECTOR with the input registers.
652     std::vector<SDOperand> Ops;
653     if (PTyElementVT == PTyLegalElementVT) {
654       // If the value types are legal, just VBUILD the CopyFromReg nodes.
655       for (unsigned i = 0; i != NE; ++i)
656         Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
657                                          PTyElementVT));
658     } else if (PTyElementVT < PTyLegalElementVT) {
659       // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
660       for (unsigned i = 0; i != NE; ++i) {
661         SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
662                                           PTyElementVT);
663         if (MVT::isFloatingPoint(PTyElementVT))
664           Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
665         else
666           Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
667         Ops.push_back(Op);
668       }
669     } else {
670       // If the register was expanded, use BUILD_PAIR.
671       assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
672       for (unsigned i = 0; i != NE/2; ++i) {
673         SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
674                                            PTyElementVT);
675         SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
676                                            PTyElementVT);
677         Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
678       }
679     }
680     
681     Ops.push_back(DAG.getConstant(NE, MVT::i32));
682     Ops.push_back(DAG.getValueType(PTyLegalElementVT));
683     N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
684     
685     // Finally, use a VBIT_CONVERT to make this available as the appropriate
686     // vector type.
687     N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N, 
688                     DAG.getConstant(PTy->getNumElements(),
689                                     MVT::i32),
690                     DAG.getValueType(TLI.getValueType(PTy->getElementType())));
691   }
692   
693   return N;
694 }
695
696
697 void SelectionDAGLowering::visitRet(ReturnInst &I) {
698   if (I.getNumOperands() == 0) {
699     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
700     return;
701   }
702   std::vector<SDOperand> NewValues;
703   NewValues.push_back(getRoot());
704   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
705     SDOperand RetOp = getValue(I.getOperand(i));
706     
707     // If this is an integer return value, we need to promote it ourselves to
708     // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
709     // than sign/zero.
710     if (MVT::isInteger(RetOp.getValueType()) && 
711         RetOp.getValueType() < MVT::i64) {
712       MVT::ValueType TmpVT;
713       if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
714         TmpVT = TLI.getTypeToTransformTo(MVT::i32);
715       else
716         TmpVT = MVT::i32;
717
718       if (I.getOperand(i)->getType()->isSigned())
719         RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
720       else
721         RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
722     }
723     NewValues.push_back(RetOp);
724   }
725   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
726 }
727
728 void SelectionDAGLowering::visitBr(BranchInst &I) {
729   // Update machine-CFG edges.
730   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
731   CurMBB->addSuccessor(Succ0MBB);
732
733   // Figure out which block is immediately after the current one.
734   MachineBasicBlock *NextBlock = 0;
735   MachineFunction::iterator BBI = CurMBB;
736   if (++BBI != CurMBB->getParent()->end())
737     NextBlock = BBI;
738
739   if (I.isUnconditional()) {
740     // If this is not a fall-through branch, emit the branch.
741     if (Succ0MBB != NextBlock)
742       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
743                               DAG.getBasicBlock(Succ0MBB)));
744   } else {
745     MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
746     CurMBB->addSuccessor(Succ1MBB);
747
748     SDOperand Cond = getValue(I.getCondition());
749     if (Succ1MBB == NextBlock) {
750       // If the condition is false, fall through.  This means we should branch
751       // if the condition is true to Succ #0.
752       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
753                               Cond, DAG.getBasicBlock(Succ0MBB)));
754     } else if (Succ0MBB == NextBlock) {
755       // If the condition is true, fall through.  This means we should branch if
756       // the condition is false to Succ #1.  Invert the condition first.
757       SDOperand True = DAG.getConstant(1, Cond.getValueType());
758       Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
759       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
760                               Cond, DAG.getBasicBlock(Succ1MBB)));
761     } else {
762       std::vector<SDOperand> Ops;
763       Ops.push_back(getRoot());
764       // If the false case is the current basic block, then this is a self
765       // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
766       // adds an extra instruction in the loop.  Instead, invert the
767       // condition and emit "Loop: ... br!cond Loop; br Out. 
768       if (CurMBB == Succ1MBB) {
769         std::swap(Succ0MBB, Succ1MBB);
770         SDOperand True = DAG.getConstant(1, Cond.getValueType());
771         Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
772       }
773       SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
774                                    DAG.getBasicBlock(Succ0MBB));
775       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True, 
776                               DAG.getBasicBlock(Succ1MBB)));
777     }
778   }
779 }
780
781 /// visitSwitchCase - Emits the necessary code to represent a single node in
782 /// the binary search tree resulting from lowering a switch instruction.
783 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
784   SDOperand SwitchOp = getValue(CB.SwitchV);
785   SDOperand CaseOp = getValue(CB.CaseC);
786   SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
787   
788   // Set NextBlock to be the MBB immediately after the current one, if any.
789   // This is used to avoid emitting unnecessary branches to the next block.
790   MachineBasicBlock *NextBlock = 0;
791   MachineFunction::iterator BBI = CurMBB;
792   if (++BBI != CurMBB->getParent()->end())
793     NextBlock = BBI;
794   
795   // If the lhs block is the next block, invert the condition so that we can
796   // fall through to the lhs instead of the rhs block.
797   if (CB.LHSBB == NextBlock) {
798     std::swap(CB.LHSBB, CB.RHSBB);
799     SDOperand True = DAG.getConstant(1, Cond.getValueType());
800     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
801   }
802   SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
803                                  DAG.getBasicBlock(CB.LHSBB));
804   if (CB.RHSBB == NextBlock)
805     DAG.setRoot(BrCond);
806   else
807     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
808                             DAG.getBasicBlock(CB.RHSBB)));
809   // Update successor info
810   CurMBB->addSuccessor(CB.LHSBB);
811   CurMBB->addSuccessor(CB.RHSBB);
812 }
813
814 /// visitSwitchCase - Emits the necessary code to represent a single node in
815 /// the binary search tree resulting from lowering a switch instruction.
816 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
817   // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
818   // we need to add the address of the jump table to the value loaded, since
819   // the entries in the jump table will be differences rather than absolute
820   // addresses.
821   
822   // Emit the code for the jump table
823   MVT::ValueType PTy = TLI.getPointerTy();
824   unsigned PTyBytes = MVT::getSizeInBits(PTy)/8;
825   SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
826   SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
827                               DAG.getConstant(PTyBytes, PTy));
828   SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, DAG.getJumpTable(JT.JTI,PTy));
829   SDOperand LD  = DAG.getLoad(PTy, Copy.getValue(1), ADD, DAG.getSrcValue(0));
830   DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
831 }
832
833 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
834   // Figure out which block is immediately after the current one.
835   MachineBasicBlock *NextBlock = 0;
836   MachineFunction::iterator BBI = CurMBB;
837   if (++BBI != CurMBB->getParent()->end())
838     NextBlock = BBI;
839   
840   // If there is only the default destination, branch to it if it is not the
841   // next basic block.  Otherwise, just fall through.
842   if (I.getNumOperands() == 2) {
843     // Update machine-CFG edges.
844     MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
845     // If this is not a fall-through branch, emit the branch.
846     if (DefaultMBB != NextBlock)
847       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
848                               DAG.getBasicBlock(DefaultMBB)));
849     return;
850   }
851   
852   // If there are any non-default case statements, create a vector of Cases
853   // representing each one, and sort the vector so that we can efficiently
854   // create a binary search tree from them.
855   std::vector<Case> Cases;
856   for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
857     MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
858     Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
859   }
860   std::sort(Cases.begin(), Cases.end(), CaseCmp());
861   
862   // Get the Value to be switched on and default basic blocks, which will be
863   // inserted into CaseBlock records, representing basic blocks in the binary
864   // search tree.
865   Value *SV = I.getOperand(0);
866   MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
867
868   // Get the MachineFunction which holds the current MBB.  This is used during
869   // emission of jump tables, and when inserting any additional MBBs necessary
870   // to represent the switch.
871   MachineFunction *CurMF = CurMBB->getParent();
872   const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
873   Reloc::Model Relocs = TLI.getTargetMachine().getRelocationModel();
874
875   // If the switch has more than 5 blocks, and at least 31.25% dense, and the 
876   // target supports indirect branches, then emit a jump table rather than 
877   // lowering the switch to a binary tree of conditional branches.
878   // FIXME: Make this work with PIC code
879   if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
880       (Relocs == Reloc::Static || Relocs == Reloc::DynamicNoPIC) &&
881       Cases.size() > 5) {
882     uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
883     uint64_t Last  = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
884     double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
885     
886     if (Density >= 0.3125) {
887       // Create a new basic block to hold the code for loading the address
888       // of the jump table, and jumping to it.  Update successor information;
889       // we will either branch to the default case for the switch, or the jump
890       // table.
891       MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
892       CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
893       CurMBB->addSuccessor(Default);
894       CurMBB->addSuccessor(JumpTableBB);
895       
896       // Subtract the lowest switch case value from the value being switched on
897       // and conditional branch to default mbb if the result is greater than the
898       // difference between smallest and largest cases.
899       SDOperand SwitchOp = getValue(SV);
900       MVT::ValueType VT = SwitchOp.getValueType();
901       SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp, 
902                                   DAG.getConstant(First, VT));
903
904       // The SDNode we just created, which holds the value being switched on
905       // minus the the smallest case value, needs to be copied to a virtual
906       // register so it can be used as an index into the jump table in a 
907       // subsequent basic block.  This value may be smaller or larger than the
908       // target's pointer type, and therefore require extension or truncating.
909       if (VT > TLI.getPointerTy())
910         SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
911       else
912         SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
913       unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
914       SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
915       
916       // Emit the range check for the jump table, and branch to the default
917       // block for the switch statement if the value being switched on exceeds
918       // the largest case in the switch.
919       SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
920                                    DAG.getConstant(Last-First,VT), ISD::SETUGT);
921       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP, 
922                               DAG.getBasicBlock(Default)));
923
924       // Build a vector of destination BBs, corresponding to each target
925       // of the jump table.  If the value of the jump table slot corresponds to
926       // a case statement, push the case's BB onto the vector, otherwise, push
927       // the default BB.
928       std::set<MachineBasicBlock*> UniqueBBs;
929       std::vector<MachineBasicBlock*> DestBBs;
930       uint64_t TEI = First;
931       for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI) {
932         if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
933           DestBBs.push_back(ii->second);
934           UniqueBBs.insert(ii->second);
935           ++ii;
936         } else {
937           DestBBs.push_back(Default);
938           UniqueBBs.insert(Default);
939         }
940       }
941       
942       // Update successor info
943       for (std::set<MachineBasicBlock*>::iterator ii = UniqueBBs.begin(), 
944            ee = UniqueBBs.end(); ii != ee; ++ii)
945         JumpTableBB->addSuccessor(*ii);
946       
947       // Create a jump table index for this jump table, or return an existing
948       // one.
949       unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
950       
951       // Set the jump table information so that we can codegen it as a second
952       // MachineBasicBlock
953       JT.Reg = JumpTableReg;
954       JT.JTI = JTI;
955       JT.MBB = JumpTableBB;
956       JT.Default = Default;
957       return;
958     }
959   }
960   
961   // Push the initial CaseRec onto the worklist
962   std::vector<CaseRec> CaseVec;
963   CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
964   
965   while (!CaseVec.empty()) {
966     // Grab a record representing a case range to process off the worklist
967     CaseRec CR = CaseVec.back();
968     CaseVec.pop_back();
969     
970     // Size is the number of Cases represented by this range.  If Size is 1,
971     // then we are processing a leaf of the binary search tree.  Otherwise,
972     // we need to pick a pivot, and push left and right ranges onto the 
973     // worklist.
974     unsigned Size = CR.Range.second - CR.Range.first;
975     
976     if (Size == 1) {
977       // Create a CaseBlock record representing a conditional branch to
978       // the Case's target mbb if the value being switched on SV is equal
979       // to C.  Otherwise, branch to default.
980       Constant *C = CR.Range.first->first;
981       MachineBasicBlock *Target = CR.Range.first->second;
982       SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default, 
983                                      CR.CaseBB);
984       // If the MBB representing the leaf node is the current MBB, then just
985       // call visitSwitchCase to emit the code into the current block.
986       // Otherwise, push the CaseBlock onto the vector to be later processed
987       // by SDISel, and insert the node's MBB before the next MBB.
988       if (CR.CaseBB == CurMBB)
989         visitSwitchCase(CB);
990       else {
991         SwitchCases.push_back(CB);
992         CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
993       }
994     } else {
995       // split case range at pivot
996       CaseItr Pivot = CR.Range.first + (Size / 2);
997       CaseRange LHSR(CR.Range.first, Pivot);
998       CaseRange RHSR(Pivot, CR.Range.second);
999       Constant *C = Pivot->first;
1000       MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1001       // We know that we branch to the LHS if the Value being switched on is
1002       // less than the Pivot value, C.  We use this to optimize our binary 
1003       // tree a bit, by recognizing that if SV is greater than or equal to the
1004       // LHS's Case Value, and that Case Value is exactly one less than the 
1005       // Pivot's Value, then we can branch directly to the LHS's Target,
1006       // rather than creating a leaf node for it.
1007       if ((LHSR.second - LHSR.first) == 1 &&
1008           LHSR.first->first == CR.GE &&
1009           cast<ConstantIntegral>(C)->getRawValue() ==
1010           (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1011         LHSBB = LHSR.first->second;
1012       } else {
1013         LHSBB = new MachineBasicBlock(LLVMBB);
1014         CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1015       }
1016       // Similar to the optimization above, if the Value being switched on is
1017       // known to be less than the Constant CR.LT, and the current Case Value
1018       // is CR.LT - 1, then we can branch directly to the target block for
1019       // the current Case Value, rather than emitting a RHS leaf node for it.
1020       if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1021           cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1022           (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1023         RHSBB = RHSR.first->second;
1024       } else {
1025         RHSBB = new MachineBasicBlock(LLVMBB);
1026         CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1027       }
1028       // Create a CaseBlock record representing a conditional branch to
1029       // the LHS node if the value being switched on SV is less than C. 
1030       // Otherwise, branch to LHS.
1031       ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1032       SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1033       if (CR.CaseBB == CurMBB)
1034         visitSwitchCase(CB);
1035       else {
1036         SwitchCases.push_back(CB);
1037         CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1038       }
1039     }
1040   }
1041 }
1042
1043 void SelectionDAGLowering::visitSub(User &I) {
1044   // -0.0 - X --> fneg
1045   if (I.getType()->isFloatingPoint()) {
1046     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1047       if (CFP->isExactlyValue(-0.0)) {
1048         SDOperand Op2 = getValue(I.getOperand(1));
1049         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1050         return;
1051       }
1052   }
1053   visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
1054 }
1055
1056 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp, 
1057                                        unsigned VecOp) {
1058   const Type *Ty = I.getType();
1059   SDOperand Op1 = getValue(I.getOperand(0));
1060   SDOperand Op2 = getValue(I.getOperand(1));
1061
1062   if (Ty->isIntegral()) {
1063     setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1064   } else if (Ty->isFloatingPoint()) {
1065     setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1066   } else {
1067     const PackedType *PTy = cast<PackedType>(Ty);
1068     SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1069     SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1070     setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1071   }
1072 }
1073
1074 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1075   SDOperand Op1 = getValue(I.getOperand(0));
1076   SDOperand Op2 = getValue(I.getOperand(1));
1077   
1078   Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1079   
1080   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1081 }
1082
1083 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1084                                       ISD::CondCode UnsignedOpcode) {
1085   SDOperand Op1 = getValue(I.getOperand(0));
1086   SDOperand Op2 = getValue(I.getOperand(1));
1087   ISD::CondCode Opcode = SignedOpcode;
1088   if (I.getOperand(0)->getType()->isUnsigned())
1089     Opcode = UnsignedOpcode;
1090   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1091 }
1092
1093 void SelectionDAGLowering::visitSelect(User &I) {
1094   SDOperand Cond     = getValue(I.getOperand(0));
1095   SDOperand TrueVal  = getValue(I.getOperand(1));
1096   SDOperand FalseVal = getValue(I.getOperand(2));
1097   if (!isa<PackedType>(I.getType())) {
1098     setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1099                              TrueVal, FalseVal));
1100   } else {
1101     setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1102                              *(TrueVal.Val->op_end()-2),
1103                              *(TrueVal.Val->op_end()-1)));
1104   }
1105 }
1106
1107 void SelectionDAGLowering::visitCast(User &I) {
1108   SDOperand N = getValue(I.getOperand(0));
1109   MVT::ValueType SrcVT = N.getValueType();
1110   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1111
1112   if (DestVT == MVT::Vector) {
1113     // This is a cast to a vector from something else.  This is always a bit
1114     // convert.  Get information about the input vector.
1115     const PackedType *DestTy = cast<PackedType>(I.getType());
1116     MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1117     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N, 
1118                              DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1119                              DAG.getValueType(EltVT)));
1120   } else if (SrcVT == DestVT) {
1121     setValue(&I, N);  // noop cast.
1122   } else if (DestVT == MVT::i1) {
1123     // Cast to bool is a comparison against zero, not truncation to zero.
1124     SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1125                                        DAG.getConstantFP(0.0, N.getValueType());
1126     setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1127   } else if (isInteger(SrcVT)) {
1128     if (isInteger(DestVT)) {        // Int -> Int cast
1129       if (DestVT < SrcVT)   // Truncating cast?
1130         setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1131       else if (I.getOperand(0)->getType()->isSigned())
1132         setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1133       else
1134         setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1135     } else if (isFloatingPoint(DestVT)) {           // Int -> FP cast
1136       if (I.getOperand(0)->getType()->isSigned())
1137         setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1138       else
1139         setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1140     } else {
1141       assert(0 && "Unknown cast!");
1142     }
1143   } else if (isFloatingPoint(SrcVT)) {
1144     if (isFloatingPoint(DestVT)) {  // FP -> FP cast
1145       if (DestVT < SrcVT)   // Rounding cast?
1146         setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1147       else
1148         setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1149     } else if (isInteger(DestVT)) {        // FP -> Int cast.
1150       if (I.getType()->isSigned())
1151         setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1152       else
1153         setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1154     } else {
1155       assert(0 && "Unknown cast!");
1156     }
1157   } else {
1158     assert(SrcVT == MVT::Vector && "Unknown cast!");
1159     assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1160     // This is a cast from a vector to something else.  This is always a bit
1161     // convert.  Get information about the input vector.
1162     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1163   }
1164 }
1165
1166 void SelectionDAGLowering::visitInsertElement(User &I) {
1167   SDOperand InVec = getValue(I.getOperand(0));
1168   SDOperand InVal = getValue(I.getOperand(1));
1169   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1170                                 getValue(I.getOperand(2)));
1171
1172   SDOperand Num = *(InVec.Val->op_end()-2);
1173   SDOperand Typ = *(InVec.Val->op_end()-1);
1174   setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1175                            InVec, InVal, InIdx, Num, Typ));
1176 }
1177
1178 void SelectionDAGLowering::visitExtractElement(User &I) {
1179   SDOperand InVec = getValue(I.getOperand(0));
1180   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1181                                 getValue(I.getOperand(1)));
1182   SDOperand Typ = *(InVec.Val->op_end()-1);
1183   setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1184                            TLI.getValueType(I.getType()), InVec, InIdx));
1185 }
1186
1187 void SelectionDAGLowering::visitShuffleVector(User &I) {
1188   SDOperand V1   = getValue(I.getOperand(0));
1189   SDOperand V2   = getValue(I.getOperand(1));
1190   SDOperand Mask = getValue(I.getOperand(2));
1191
1192   SDOperand Num = *(V1.Val->op_end()-2);
1193   SDOperand Typ = *(V2.Val->op_end()-1);
1194   setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1195                            V1, V2, Mask, Num, Typ));
1196 }
1197
1198
1199 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1200   SDOperand N = getValue(I.getOperand(0));
1201   const Type *Ty = I.getOperand(0)->getType();
1202
1203   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1204        OI != E; ++OI) {
1205     Value *Idx = *OI;
1206     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1207       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1208       if (Field) {
1209         // N = N + Offset
1210         uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1211         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1212                         getIntPtrConstant(Offset));
1213       }
1214       Ty = StTy->getElementType(Field);
1215     } else {
1216       Ty = cast<SequentialType>(Ty)->getElementType();
1217
1218       // If this is a constant subscript, handle it quickly.
1219       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1220         if (CI->getRawValue() == 0) continue;
1221
1222         uint64_t Offs;
1223         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1224           Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
1225         else
1226           Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1227         N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1228         continue;
1229       }
1230       
1231       // N = N + Idx * ElementSize;
1232       uint64_t ElementSize = TD->getTypeSize(Ty);
1233       SDOperand IdxN = getValue(Idx);
1234
1235       // If the index is smaller or larger than intptr_t, truncate or extend
1236       // it.
1237       if (IdxN.getValueType() < N.getValueType()) {
1238         if (Idx->getType()->isSigned())
1239           IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1240         else
1241           IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1242       } else if (IdxN.getValueType() > N.getValueType())
1243         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1244
1245       // If this is a multiply by a power of two, turn it into a shl
1246       // immediately.  This is a very common case.
1247       if (isPowerOf2_64(ElementSize)) {
1248         unsigned Amt = Log2_64(ElementSize);
1249         IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1250                            DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1251         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1252         continue;
1253       }
1254       
1255       SDOperand Scale = getIntPtrConstant(ElementSize);
1256       IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1257       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1258     }
1259   }
1260   setValue(&I, N);
1261 }
1262
1263 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1264   // If this is a fixed sized alloca in the entry block of the function,
1265   // allocate it statically on the stack.
1266   if (FuncInfo.StaticAllocaMap.count(&I))
1267     return;   // getValue will auto-populate this.
1268
1269   const Type *Ty = I.getAllocatedType();
1270   uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1271   unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1272                             I.getAlignment());
1273
1274   SDOperand AllocSize = getValue(I.getArraySize());
1275   MVT::ValueType IntPtr = TLI.getPointerTy();
1276   if (IntPtr < AllocSize.getValueType())
1277     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1278   else if (IntPtr > AllocSize.getValueType())
1279     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1280
1281   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1282                           getIntPtrConstant(TySize));
1283
1284   // Handle alignment.  If the requested alignment is less than or equal to the
1285   // stack alignment, ignore it and round the size of the allocation up to the
1286   // stack alignment size.  If the size is greater than the stack alignment, we
1287   // note this in the DYNAMIC_STACKALLOC node.
1288   unsigned StackAlign =
1289     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1290   if (Align <= StackAlign) {
1291     Align = 0;
1292     // Add SA-1 to the size.
1293     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1294                             getIntPtrConstant(StackAlign-1));
1295     // Mask out the low bits for alignment purposes.
1296     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1297                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1298   }
1299
1300   std::vector<MVT::ValueType> VTs;
1301   VTs.push_back(AllocSize.getValueType());
1302   VTs.push_back(MVT::Other);
1303   std::vector<SDOperand> Ops;
1304   Ops.push_back(getRoot());
1305   Ops.push_back(AllocSize);
1306   Ops.push_back(getIntPtrConstant(Align));
1307   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1308   DAG.setRoot(setValue(&I, DSA).getValue(1));
1309
1310   // Inform the Frame Information that we have just allocated a variable-sized
1311   // object.
1312   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1313 }
1314
1315 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1316   SDOperand Ptr = getValue(I.getOperand(0));
1317
1318   SDOperand Root;
1319   if (I.isVolatile())
1320     Root = getRoot();
1321   else {
1322     // Do not serialize non-volatile loads against each other.
1323     Root = DAG.getRoot();
1324   }
1325
1326   setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1327                            Root, I.isVolatile()));
1328 }
1329
1330 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1331                                             SDOperand SrcValue, SDOperand Root,
1332                                             bool isVolatile) {
1333   SDOperand L;
1334   if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1335     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1336     L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1337   } else {
1338     L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1339   }
1340
1341   if (isVolatile)
1342     DAG.setRoot(L.getValue(1));
1343   else
1344     PendingLoads.push_back(L.getValue(1));
1345   
1346   return L;
1347 }
1348
1349
1350 void SelectionDAGLowering::visitStore(StoreInst &I) {
1351   Value *SrcV = I.getOperand(0);
1352   SDOperand Src = getValue(SrcV);
1353   SDOperand Ptr = getValue(I.getOperand(1));
1354   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1355                           DAG.getSrcValue(I.getOperand(1))));
1356 }
1357
1358 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1359 /// access memory and has no other side effects at all.
1360 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1361 #define GET_NO_MEMORY_INTRINSICS
1362 #include "llvm/Intrinsics.gen"
1363 #undef GET_NO_MEMORY_INTRINSICS
1364   return false;
1365 }
1366
1367 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1368 // have any side-effects or if it only reads memory.
1369 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1370 #define GET_SIDE_EFFECT_INFO
1371 #include "llvm/Intrinsics.gen"
1372 #undef GET_SIDE_EFFECT_INFO
1373   return false;
1374 }
1375
1376 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1377 /// node.
1378 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
1379                                                 unsigned Intrinsic) {
1380   bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1381   bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1382   
1383   // Build the operand list.
1384   std::vector<SDOperand> Ops;
1385   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
1386     if (OnlyLoad) {
1387       // We don't need to serialize loads against other loads.
1388       Ops.push_back(DAG.getRoot());
1389     } else { 
1390       Ops.push_back(getRoot());
1391     }
1392   }
1393   
1394   // Add the intrinsic ID as an integer operand.
1395   Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1396
1397   // Add all operands of the call to the operand list.
1398   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1399     SDOperand Op = getValue(I.getOperand(i));
1400     
1401     // If this is a vector type, force it to the right packed type.
1402     if (Op.getValueType() == MVT::Vector) {
1403       const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1404       MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1405       
1406       MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1407       assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1408       Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1409     }
1410     
1411     assert(TLI.isTypeLegal(Op.getValueType()) &&
1412            "Intrinsic uses a non-legal type?");
1413     Ops.push_back(Op);
1414   }
1415
1416   std::vector<MVT::ValueType> VTs;
1417   if (I.getType() != Type::VoidTy) {
1418     MVT::ValueType VT = TLI.getValueType(I.getType());
1419     if (VT == MVT::Vector) {
1420       const PackedType *DestTy = cast<PackedType>(I.getType());
1421       MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1422       
1423       VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1424       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1425     }
1426     
1427     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1428     VTs.push_back(VT);
1429   }
1430   if (HasChain)
1431     VTs.push_back(MVT::Other);
1432
1433   // Create the node.
1434   SDOperand Result;
1435   if (!HasChain)
1436     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1437   else if (I.getType() != Type::VoidTy)
1438     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1439   else
1440     Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1441
1442   if (HasChain) {
1443     SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1444     if (OnlyLoad)
1445       PendingLoads.push_back(Chain);
1446     else
1447       DAG.setRoot(Chain);
1448   }
1449   if (I.getType() != Type::VoidTy) {
1450     if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1451       MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1452       Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1453                            DAG.getConstant(PTy->getNumElements(), MVT::i32),
1454                            DAG.getValueType(EVT));
1455     } 
1456     setValue(&I, Result);
1457   }
1458 }
1459
1460 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
1461 /// we want to emit this as a call to a named external function, return the name
1462 /// otherwise lower it and return null.
1463 const char *
1464 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1465   switch (Intrinsic) {
1466   default:
1467     // By default, turn this into a target intrinsic node.
1468     visitTargetIntrinsic(I, Intrinsic);
1469     return 0;
1470   case Intrinsic::vastart:  visitVAStart(I); return 0;
1471   case Intrinsic::vaend:    visitVAEnd(I); return 0;
1472   case Intrinsic::vacopy:   visitVACopy(I); return 0;
1473   case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1474   case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
1475   case Intrinsic::setjmp:
1476     return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1477     break;
1478   case Intrinsic::longjmp:
1479     return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1480     break;
1481   case Intrinsic::memcpy_i32:
1482   case Intrinsic::memcpy_i64:
1483     visitMemIntrinsic(I, ISD::MEMCPY);
1484     return 0;
1485   case Intrinsic::memset_i32:
1486   case Intrinsic::memset_i64:
1487     visitMemIntrinsic(I, ISD::MEMSET);
1488     return 0;
1489   case Intrinsic::memmove_i32:
1490   case Intrinsic::memmove_i64:
1491     visitMemIntrinsic(I, ISD::MEMMOVE);
1492     return 0;
1493     
1494   case Intrinsic::dbg_stoppoint: {
1495     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1496     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1497     if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1498       std::vector<SDOperand> Ops;
1499
1500       Ops.push_back(getRoot());
1501       Ops.push_back(getValue(SPI.getLineValue()));
1502       Ops.push_back(getValue(SPI.getColumnValue()));
1503
1504       DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1505       assert(DD && "Not a debug information descriptor");
1506       CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1507       
1508       Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1509       Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1510       
1511       DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1512     }
1513
1514     return 0;
1515   }
1516   case Intrinsic::dbg_region_start: {
1517     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1518     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1519     if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1520       std::vector<SDOperand> Ops;
1521
1522       unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1523       
1524       Ops.push_back(getRoot());
1525       Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1526
1527       DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1528     }
1529
1530     return 0;
1531   }
1532   case Intrinsic::dbg_region_end: {
1533     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1534     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1535     if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1536       std::vector<SDOperand> Ops;
1537
1538       unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1539       
1540       Ops.push_back(getRoot());
1541       Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1542
1543       DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1544     }
1545
1546     return 0;
1547   }
1548   case Intrinsic::dbg_func_start: {
1549     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1550     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1551     if (DebugInfo && FSI.getSubprogram() &&
1552         DebugInfo->Verify(FSI.getSubprogram())) {
1553       std::vector<SDOperand> Ops;
1554
1555       unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1556       
1557       Ops.push_back(getRoot());
1558       Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1559
1560       DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1561     }
1562
1563     return 0;
1564   }
1565   case Intrinsic::dbg_declare: {
1566     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1567     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1568     if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1569       std::vector<SDOperand> Ops;
1570
1571       SDOperand AddressOp  = getValue(DI.getAddress());
1572       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1573         DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1574       }
1575     }
1576
1577     return 0;
1578   }
1579     
1580   case Intrinsic::isunordered_f32:
1581   case Intrinsic::isunordered_f64:
1582     setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1583                               getValue(I.getOperand(2)), ISD::SETUO));
1584     return 0;
1585     
1586   case Intrinsic::sqrt_f32:
1587   case Intrinsic::sqrt_f64:
1588     setValue(&I, DAG.getNode(ISD::FSQRT,
1589                              getValue(I.getOperand(1)).getValueType(),
1590                              getValue(I.getOperand(1))));
1591     return 0;
1592   case Intrinsic::pcmarker: {
1593     SDOperand Tmp = getValue(I.getOperand(1));
1594     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1595     return 0;
1596   }
1597   case Intrinsic::readcyclecounter: {
1598     std::vector<MVT::ValueType> VTs;
1599     VTs.push_back(MVT::i64);
1600     VTs.push_back(MVT::Other);
1601     std::vector<SDOperand> Ops;
1602     Ops.push_back(getRoot());
1603     SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1604     setValue(&I, Tmp);
1605     DAG.setRoot(Tmp.getValue(1));
1606     return 0;
1607   }
1608   case Intrinsic::bswap_i16:
1609   case Intrinsic::bswap_i32:
1610   case Intrinsic::bswap_i64:
1611     setValue(&I, DAG.getNode(ISD::BSWAP,
1612                              getValue(I.getOperand(1)).getValueType(),
1613                              getValue(I.getOperand(1))));
1614     return 0;
1615   case Intrinsic::cttz_i8:
1616   case Intrinsic::cttz_i16:
1617   case Intrinsic::cttz_i32:
1618   case Intrinsic::cttz_i64:
1619     setValue(&I, DAG.getNode(ISD::CTTZ,
1620                              getValue(I.getOperand(1)).getValueType(),
1621                              getValue(I.getOperand(1))));
1622     return 0;
1623   case Intrinsic::ctlz_i8:
1624   case Intrinsic::ctlz_i16:
1625   case Intrinsic::ctlz_i32:
1626   case Intrinsic::ctlz_i64:
1627     setValue(&I, DAG.getNode(ISD::CTLZ,
1628                              getValue(I.getOperand(1)).getValueType(),
1629                              getValue(I.getOperand(1))));
1630     return 0;
1631   case Intrinsic::ctpop_i8:
1632   case Intrinsic::ctpop_i16:
1633   case Intrinsic::ctpop_i32:
1634   case Intrinsic::ctpop_i64:
1635     setValue(&I, DAG.getNode(ISD::CTPOP,
1636                              getValue(I.getOperand(1)).getValueType(),
1637                              getValue(I.getOperand(1))));
1638     return 0;
1639   case Intrinsic::stacksave: {
1640     std::vector<MVT::ValueType> VTs;
1641     VTs.push_back(TLI.getPointerTy());
1642     VTs.push_back(MVT::Other);
1643     std::vector<SDOperand> Ops;
1644     Ops.push_back(getRoot());
1645     SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1646     setValue(&I, Tmp);
1647     DAG.setRoot(Tmp.getValue(1));
1648     return 0;
1649   }
1650   case Intrinsic::stackrestore: {
1651     SDOperand Tmp = getValue(I.getOperand(1));
1652     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1653     return 0;
1654   }
1655   case Intrinsic::prefetch:
1656     // FIXME: Currently discarding prefetches.
1657     return 0;
1658   }
1659 }
1660
1661
1662 void SelectionDAGLowering::visitCall(CallInst &I) {
1663   const char *RenameFn = 0;
1664   if (Function *F = I.getCalledFunction()) {
1665     if (F->isExternal())
1666       if (unsigned IID = F->getIntrinsicID()) {
1667         RenameFn = visitIntrinsicCall(I, IID);
1668         if (!RenameFn)
1669           return;
1670       } else {    // Not an LLVM intrinsic.
1671         const std::string &Name = F->getName();
1672         if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1673           if (I.getNumOperands() == 3 &&   // Basic sanity checks.
1674               I.getOperand(1)->getType()->isFloatingPoint() &&
1675               I.getType() == I.getOperand(1)->getType() &&
1676               I.getType() == I.getOperand(2)->getType()) {
1677             SDOperand LHS = getValue(I.getOperand(1));
1678             SDOperand RHS = getValue(I.getOperand(2));
1679             setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1680                                      LHS, RHS));
1681             return;
1682           }
1683         } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1684           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1685               I.getOperand(1)->getType()->isFloatingPoint() &&
1686               I.getType() == I.getOperand(1)->getType()) {
1687             SDOperand Tmp = getValue(I.getOperand(1));
1688             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1689             return;
1690           }
1691         } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1692           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1693               I.getOperand(1)->getType()->isFloatingPoint() &&
1694               I.getType() == I.getOperand(1)->getType()) {
1695             SDOperand Tmp = getValue(I.getOperand(1));
1696             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1697             return;
1698           }
1699         } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1700           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1701               I.getOperand(1)->getType()->isFloatingPoint() &&
1702               I.getType() == I.getOperand(1)->getType()) {
1703             SDOperand Tmp = getValue(I.getOperand(1));
1704             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1705             return;
1706           }
1707         }
1708       }
1709   } else if (isa<InlineAsm>(I.getOperand(0))) {
1710     visitInlineAsm(I);
1711     return;
1712   }
1713
1714   SDOperand Callee;
1715   if (!RenameFn)
1716     Callee = getValue(I.getOperand(0));
1717   else
1718     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1719   std::vector<std::pair<SDOperand, const Type*> > Args;
1720   Args.reserve(I.getNumOperands());
1721   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1722     Value *Arg = I.getOperand(i);
1723     SDOperand ArgNode = getValue(Arg);
1724     Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1725   }
1726
1727   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1728   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1729
1730   std::pair<SDOperand,SDOperand> Result =
1731     TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1732                     I.isTailCall(), Callee, Args, DAG);
1733   if (I.getType() != Type::VoidTy)
1734     setValue(&I, Result.first);
1735   DAG.setRoot(Result.second);
1736 }
1737
1738 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1739                                         SDOperand &Chain, SDOperand &Flag)const{
1740   SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1741   Chain = Val.getValue(1);
1742   Flag  = Val.getValue(2);
1743   
1744   // If the result was expanded, copy from the top part.
1745   if (Regs.size() > 1) {
1746     assert(Regs.size() == 2 &&
1747            "Cannot expand to more than 2 elts yet!");
1748     SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1749     Chain = Val.getValue(1);
1750     Flag  = Val.getValue(2);
1751     if (DAG.getTargetLoweringInfo().isLittleEndian())
1752       return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1753     else
1754       return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1755   }
1756
1757   // Otherwise, if the return value was promoted, truncate it to the
1758   // appropriate type.
1759   if (RegVT == ValueVT)
1760     return Val;
1761   
1762   if (MVT::isInteger(RegVT))
1763     return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1764   else
1765     return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1766 }
1767
1768 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1769 /// specified value into the registers specified by this object.  This uses 
1770 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1771 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1772                                  SDOperand &Chain, SDOperand &Flag) const {
1773   if (Regs.size() == 1) {
1774     // If there is a single register and the types differ, this must be
1775     // a promotion.
1776     if (RegVT != ValueVT) {
1777       if (MVT::isInteger(RegVT))
1778         Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1779       else
1780         Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1781     }
1782     Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1783     Flag = Chain.getValue(1);
1784   } else {
1785     std::vector<unsigned> R(Regs);
1786     if (!DAG.getTargetLoweringInfo().isLittleEndian())
1787       std::reverse(R.begin(), R.end());
1788     
1789     for (unsigned i = 0, e = R.size(); i != e; ++i) {
1790       SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val, 
1791                                    DAG.getConstant(i, MVT::i32));
1792       Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1793       Flag = Chain.getValue(1);
1794     }
1795   }
1796 }
1797
1798 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1799 /// operand list.  This adds the code marker and includes the number of 
1800 /// values added into it.
1801 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1802                                         std::vector<SDOperand> &Ops) const {
1803   Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1804   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1805     Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1806 }
1807
1808 /// isAllocatableRegister - If the specified register is safe to allocate, 
1809 /// i.e. it isn't a stack pointer or some other special register, return the
1810 /// register class for the register.  Otherwise, return null.
1811 static const TargetRegisterClass *
1812 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1813                       const TargetLowering &TLI, const MRegisterInfo *MRI) {
1814   MVT::ValueType FoundVT = MVT::Other;
1815   const TargetRegisterClass *FoundRC = 0;
1816   for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1817        E = MRI->regclass_end(); RCI != E; ++RCI) {
1818     MVT::ValueType ThisVT = MVT::Other;
1819
1820     const TargetRegisterClass *RC = *RCI;
1821     // If none of the the value types for this register class are valid, we 
1822     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1823     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1824          I != E; ++I) {
1825       if (TLI.isTypeLegal(*I)) {
1826         // If we have already found this register in a different register class,
1827         // choose the one with the largest VT specified.  For example, on
1828         // PowerPC, we favor f64 register classes over f32.
1829         if (FoundVT == MVT::Other || 
1830             MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1831           ThisVT = *I;
1832           break;
1833         }
1834       }
1835     }
1836     
1837     if (ThisVT == MVT::Other) continue;
1838     
1839     // NOTE: This isn't ideal.  In particular, this might allocate the
1840     // frame pointer in functions that need it (due to them not being taken
1841     // out of allocation, because a variable sized allocation hasn't been seen
1842     // yet).  This is a slight code pessimization, but should still work.
1843     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1844          E = RC->allocation_order_end(MF); I != E; ++I)
1845       if (*I == Reg) {
1846         // We found a matching register class.  Keep looking at others in case
1847         // we find one with larger registers that this physreg is also in.
1848         FoundRC = RC;
1849         FoundVT = ThisVT;
1850         break;
1851       }
1852   }
1853   return FoundRC;
1854 }    
1855
1856 RegsForValue SelectionDAGLowering::
1857 GetRegistersForValue(const std::string &ConstrCode,
1858                      MVT::ValueType VT, bool isOutReg, bool isInReg,
1859                      std::set<unsigned> &OutputRegs, 
1860                      std::set<unsigned> &InputRegs) {
1861   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
1862     TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1863   std::vector<unsigned> Regs;
1864
1865   unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1866   MVT::ValueType RegVT;
1867   MVT::ValueType ValueVT = VT;
1868   
1869   if (PhysReg.first) {
1870     if (VT == MVT::Other)
1871       ValueVT = *PhysReg.second->vt_begin();
1872     RegVT = VT;
1873     
1874     // This is a explicit reference to a physical register.
1875     Regs.push_back(PhysReg.first);
1876
1877     // If this is an expanded reference, add the rest of the regs to Regs.
1878     if (NumRegs != 1) {
1879       RegVT = *PhysReg.second->vt_begin();
1880       TargetRegisterClass::iterator I = PhysReg.second->begin();
1881       TargetRegisterClass::iterator E = PhysReg.second->end();
1882       for (; *I != PhysReg.first; ++I)
1883         assert(I != E && "Didn't find reg!"); 
1884       
1885       // Already added the first reg.
1886       --NumRegs; ++I;
1887       for (; NumRegs; --NumRegs, ++I) {
1888         assert(I != E && "Ran out of registers to allocate!");
1889         Regs.push_back(*I);
1890       }
1891     }
1892     return RegsForValue(Regs, RegVT, ValueVT);
1893   }
1894   
1895   // This is a reference to a register class.  Allocate NumRegs consecutive,
1896   // available, registers from the class.
1897   std::vector<unsigned> RegClassRegs =
1898     TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1899
1900   const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1901   MachineFunction &MF = *CurMBB->getParent();
1902   unsigned NumAllocated = 0;
1903   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1904     unsigned Reg = RegClassRegs[i];
1905     // See if this register is available.
1906     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
1907         (isInReg  && InputRegs.count(Reg))) {    // Already used.
1908       // Make sure we find consecutive registers.
1909       NumAllocated = 0;
1910       continue;
1911     }
1912     
1913     // Check to see if this register is allocatable (i.e. don't give out the
1914     // stack pointer).
1915     const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1916     if (!RC) {
1917       // Make sure we find consecutive registers.
1918       NumAllocated = 0;
1919       continue;
1920     }
1921     
1922     // Okay, this register is good, we can use it.
1923     ++NumAllocated;
1924
1925     // If we allocated enough consecutive   
1926     if (NumAllocated == NumRegs) {
1927       unsigned RegStart = (i-NumAllocated)+1;
1928       unsigned RegEnd   = i+1;
1929       // Mark all of the allocated registers used.
1930       for (unsigned i = RegStart; i != RegEnd; ++i) {
1931         unsigned Reg = RegClassRegs[i];
1932         Regs.push_back(Reg);
1933         if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
1934         if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
1935       }
1936       
1937       return RegsForValue(Regs, *RC->vt_begin(), VT);
1938     }
1939   }
1940   
1941   // Otherwise, we couldn't allocate enough registers for this.
1942   return RegsForValue();
1943 }
1944
1945
1946 /// visitInlineAsm - Handle a call to an InlineAsm object.
1947 ///
1948 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1949   InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1950   
1951   SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1952                                                  MVT::Other);
1953
1954   // Note, we treat inline asms both with and without side-effects as the same.
1955   // If an inline asm doesn't have side effects and doesn't access memory, we
1956   // could not choose to not chain it.
1957   bool hasSideEffects = IA->hasSideEffects();
1958
1959   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1960   std::vector<MVT::ValueType> ConstraintVTs;
1961   
1962   /// AsmNodeOperands - A list of pairs.  The first element is a register, the
1963   /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1964   /// if it is a def of that register.
1965   std::vector<SDOperand> AsmNodeOperands;
1966   AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
1967   AsmNodeOperands.push_back(AsmStr);
1968   
1969   SDOperand Chain = getRoot();
1970   SDOperand Flag;
1971   
1972   // We fully assign registers here at isel time.  This is not optimal, but
1973   // should work.  For register classes that correspond to LLVM classes, we
1974   // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
1975   // over the constraints, collecting fixed registers that we know we can't use.
1976   std::set<unsigned> OutputRegs, InputRegs;
1977   unsigned OpNum = 1;
1978   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1979     assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1980     std::string &ConstraintCode = Constraints[i].Codes[0];
1981     
1982     MVT::ValueType OpVT;
1983
1984     // Compute the value type for each operand and add it to ConstraintVTs.
1985     switch (Constraints[i].Type) {
1986     case InlineAsm::isOutput:
1987       if (!Constraints[i].isIndirectOutput) {
1988         assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1989         OpVT = TLI.getValueType(I.getType());
1990       } else {
1991         const Type *OpTy = I.getOperand(OpNum)->getType();
1992         OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1993         OpNum++;  // Consumes a call operand.
1994       }
1995       break;
1996     case InlineAsm::isInput:
1997       OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1998       OpNum++;  // Consumes a call operand.
1999       break;
2000     case InlineAsm::isClobber:
2001       OpVT = MVT::Other;
2002       break;
2003     }
2004     
2005     ConstraintVTs.push_back(OpVT);
2006
2007     if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2008       continue;  // Not assigned a fixed reg.
2009     
2010     // Build a list of regs that this operand uses.  This always has a single
2011     // element for promoted/expanded operands.
2012     RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2013                                              false, false,
2014                                              OutputRegs, InputRegs);
2015     
2016     switch (Constraints[i].Type) {
2017     case InlineAsm::isOutput:
2018       // We can't assign any other output to this register.
2019       OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2020       // If this is an early-clobber output, it cannot be assigned to the same
2021       // value as the input reg.
2022       if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2023         InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2024       break;
2025     case InlineAsm::isInput:
2026       // We can't assign any other input to this register.
2027       InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2028       break;
2029     case InlineAsm::isClobber:
2030       // Clobbered regs cannot be used as inputs or outputs.
2031       InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2032       OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2033       break;
2034     }
2035   }      
2036   
2037   // Loop over all of the inputs, copying the operand values into the
2038   // appropriate registers and processing the output regs.
2039   RegsForValue RetValRegs;
2040   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2041   OpNum = 1;
2042   
2043   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2044     assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2045     std::string &ConstraintCode = Constraints[i].Codes[0];
2046
2047     switch (Constraints[i].Type) {
2048     case InlineAsm::isOutput: {
2049       TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2050       if (ConstraintCode.size() == 1)   // not a physreg name.
2051         CTy = TLI.getConstraintType(ConstraintCode[0]);
2052       
2053       if (CTy == TargetLowering::C_Memory) {
2054         // Memory output.
2055         SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2056         
2057         // Check that the operand (the address to store to) isn't a float.
2058         if (!MVT::isInteger(InOperandVal.getValueType()))
2059           assert(0 && "MATCH FAIL!");
2060         
2061         if (!Constraints[i].isIndirectOutput)
2062           assert(0 && "MATCH FAIL!");
2063
2064         OpNum++;  // Consumes a call operand.
2065         
2066         // Extend/truncate to the right pointer type if needed.
2067         MVT::ValueType PtrType = TLI.getPointerTy();
2068         if (InOperandVal.getValueType() < PtrType)
2069           InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2070         else if (InOperandVal.getValueType() > PtrType)
2071           InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2072         
2073         // Add information to the INLINEASM node to know about this output.
2074         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2075         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2076         AsmNodeOperands.push_back(InOperandVal);
2077         break;
2078       }
2079
2080       // Otherwise, this is a register output.
2081       assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2082
2083       // If this is an early-clobber output, or if there is an input
2084       // constraint that matches this, we need to reserve the input register
2085       // so no other inputs allocate to it.
2086       bool UsesInputRegister = false;
2087       if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2088         UsesInputRegister = true;
2089       
2090       // Copy the output from the appropriate register.  Find a register that
2091       // we can use.
2092       RegsForValue Regs =
2093         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2094                              true, UsesInputRegister, 
2095                              OutputRegs, InputRegs);
2096       assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2097
2098       if (!Constraints[i].isIndirectOutput) {
2099         assert(RetValRegs.Regs.empty() &&
2100                "Cannot have multiple output constraints yet!");
2101         assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2102         RetValRegs = Regs;
2103       } else {
2104         IndirectStoresToEmit.push_back(std::make_pair(Regs, 
2105                                                       I.getOperand(OpNum)));
2106         OpNum++;  // Consumes a call operand.
2107       }
2108       
2109       // Add information to the INLINEASM node to know that this register is
2110       // set.
2111       Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2112       break;
2113     }
2114     case InlineAsm::isInput: {
2115       SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2116       OpNum++;  // Consumes a call operand.
2117       
2118       if (isdigit(ConstraintCode[0])) {    // Matching constraint?
2119         // If this is required to match an output register we have already set,
2120         // just use its register.
2121         unsigned OperandNo = atoi(ConstraintCode.c_str());
2122         
2123         // Scan until we find the definition we already emitted of this operand.
2124         // When we find it, create a RegsForValue operand.
2125         unsigned CurOp = 2;  // The first operand.
2126         for (; OperandNo; --OperandNo) {
2127           // Advance to the next operand.
2128           unsigned NumOps = 
2129             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2130           assert((NumOps & 7) == 2 /*REGDEF*/ &&
2131                  "Skipped past definitions?");
2132           CurOp += (NumOps>>3)+1;
2133         }
2134
2135         unsigned NumOps = 
2136           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2137         assert((NumOps & 7) == 2 /*REGDEF*/ &&
2138                "Skipped past definitions?");
2139         
2140         // Add NumOps>>3 registers to MatchedRegs.
2141         RegsForValue MatchedRegs;
2142         MatchedRegs.ValueVT = InOperandVal.getValueType();
2143         MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
2144         for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2145           unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2146           MatchedRegs.Regs.push_back(Reg);
2147         }
2148         
2149         // Use the produced MatchedRegs object to 
2150         MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2151         MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2152         break;
2153       }
2154       
2155       TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2156       if (ConstraintCode.size() == 1)   // not a physreg name.
2157         CTy = TLI.getConstraintType(ConstraintCode[0]);
2158         
2159       if (CTy == TargetLowering::C_Other) {
2160         if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2161           assert(0 && "MATCH FAIL!");
2162         
2163         // Add information to the INLINEASM node to know about this input.
2164         unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2165         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2166         AsmNodeOperands.push_back(InOperandVal);
2167         break;
2168       } else if (CTy == TargetLowering::C_Memory) {
2169         // Memory input.
2170         
2171         // Check that the operand isn't a float.
2172         if (!MVT::isInteger(InOperandVal.getValueType()))
2173           assert(0 && "MATCH FAIL!");
2174         
2175         // Extend/truncate to the right pointer type if needed.
2176         MVT::ValueType PtrType = TLI.getPointerTy();
2177         if (InOperandVal.getValueType() < PtrType)
2178           InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2179         else if (InOperandVal.getValueType() > PtrType)
2180           InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2181
2182         // Add information to the INLINEASM node to know about this input.
2183         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2184         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2185         AsmNodeOperands.push_back(InOperandVal);
2186         break;
2187       }
2188         
2189       assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2190
2191       // Copy the input into the appropriate registers.
2192       RegsForValue InRegs =
2193         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2194                              false, true, OutputRegs, InputRegs);
2195       // FIXME: should be match fail.
2196       assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2197
2198       InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2199       
2200       InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2201       break;
2202     }
2203     case InlineAsm::isClobber: {
2204       RegsForValue ClobberedRegs =
2205         GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2206                              OutputRegs, InputRegs);
2207       // Add the clobbered value to the operand list, so that the register
2208       // allocator is aware that the physreg got clobbered.
2209       if (!ClobberedRegs.Regs.empty())
2210         ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2211       break;
2212     }
2213     }
2214   }
2215   
2216   // Finish up input operands.
2217   AsmNodeOperands[0] = Chain;
2218   if (Flag.Val) AsmNodeOperands.push_back(Flag);
2219   
2220   std::vector<MVT::ValueType> VTs;
2221   VTs.push_back(MVT::Other);
2222   VTs.push_back(MVT::Flag);
2223   Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2224   Flag = Chain.getValue(1);
2225
2226   // If this asm returns a register value, copy the result from that register
2227   // and set it as the value of the call.
2228   if (!RetValRegs.Regs.empty())
2229     setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2230   
2231   std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2232   
2233   // Process indirect outputs, first output all of the flagged copies out of
2234   // physregs.
2235   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2236     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2237     Value *Ptr = IndirectStoresToEmit[i].second;
2238     SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2239     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2240   }
2241   
2242   // Emit the non-flagged stores from the physregs.
2243   std::vector<SDOperand> OutChains;
2244   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2245     OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain, 
2246                                     StoresToEmit[i].first,
2247                                     getValue(StoresToEmit[i].second),
2248                                     DAG.getSrcValue(StoresToEmit[i].second)));
2249   if (!OutChains.empty())
2250     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2251   DAG.setRoot(Chain);
2252 }
2253
2254
2255 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2256   SDOperand Src = getValue(I.getOperand(0));
2257
2258   MVT::ValueType IntPtr = TLI.getPointerTy();
2259
2260   if (IntPtr < Src.getValueType())
2261     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2262   else if (IntPtr > Src.getValueType())
2263     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2264
2265   // Scale the source by the type size.
2266   uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2267   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2268                     Src, getIntPtrConstant(ElementSize));
2269
2270   std::vector<std::pair<SDOperand, const Type*> > Args;
2271   Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2272
2273   std::pair<SDOperand,SDOperand> Result =
2274     TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2275                     DAG.getExternalSymbol("malloc", IntPtr),
2276                     Args, DAG);
2277   setValue(&I, Result.first);  // Pointers always fit in registers
2278   DAG.setRoot(Result.second);
2279 }
2280
2281 void SelectionDAGLowering::visitFree(FreeInst &I) {
2282   std::vector<std::pair<SDOperand, const Type*> > Args;
2283   Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2284                                 TLI.getTargetData()->getIntPtrType()));
2285   MVT::ValueType IntPtr = TLI.getPointerTy();
2286   std::pair<SDOperand,SDOperand> Result =
2287     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2288                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2289   DAG.setRoot(Result.second);
2290 }
2291
2292 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2293 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
2294 // instructions are special in various ways, which require special support to
2295 // insert.  The specified MachineInstr is created but not inserted into any
2296 // basic blocks, and the scheduler passes ownership of it to this method.
2297 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2298                                                        MachineBasicBlock *MBB) {
2299   std::cerr << "If a target marks an instruction with "
2300                "'usesCustomDAGSchedInserter', it must implement "
2301                "TargetLowering::InsertAtEndOfBasicBlock!\n";
2302   abort();
2303   return 0;  
2304 }
2305
2306 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2307   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
2308                           getValue(I.getOperand(1)), 
2309                           DAG.getSrcValue(I.getOperand(1))));
2310 }
2311
2312 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2313   SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2314                              getValue(I.getOperand(0)),
2315                              DAG.getSrcValue(I.getOperand(0)));
2316   setValue(&I, V);
2317   DAG.setRoot(V.getValue(1));
2318 }
2319
2320 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2321   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2322                           getValue(I.getOperand(1)), 
2323                           DAG.getSrcValue(I.getOperand(1))));
2324 }
2325
2326 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2327   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
2328                           getValue(I.getOperand(1)), 
2329                           getValue(I.getOperand(2)),
2330                           DAG.getSrcValue(I.getOperand(1)),
2331                           DAG.getSrcValue(I.getOperand(2))));
2332 }
2333
2334 /// TargetLowering::LowerArguments - This is the default LowerArguments
2335 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
2336 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be removed.
2337 std::vector<SDOperand> 
2338 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2339   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2340   std::vector<SDOperand> Ops;
2341   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2342   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2343
2344   // Add one result value for each formal argument.
2345   std::vector<MVT::ValueType> RetVals;
2346   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2347     MVT::ValueType VT = getValueType(I->getType());
2348     
2349     switch (getTypeAction(VT)) {
2350     default: assert(0 && "Unknown type action!");
2351     case Legal: 
2352       RetVals.push_back(VT);
2353       break;
2354     case Promote:
2355       RetVals.push_back(getTypeToTransformTo(VT));
2356       break;
2357     case Expand:
2358       if (VT != MVT::Vector) {
2359         // If this is a large integer, it needs to be broken up into small
2360         // integers.  Figure out what the destination type is and how many small
2361         // integers it turns into.
2362         MVT::ValueType NVT = getTypeToTransformTo(VT);
2363         unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2364         for (unsigned i = 0; i != NumVals; ++i)
2365           RetVals.push_back(NVT);
2366       } else {
2367         // Otherwise, this is a vector type.  We only support legal vectors
2368         // right now.
2369         unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2370         const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2371
2372         // Figure out if there is a Packed type corresponding to this Vector
2373         // type.  If so, convert to the packed type.
2374         MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2375         if (TVT != MVT::Other && isTypeLegal(TVT)) {
2376           RetVals.push_back(TVT);
2377         } else {
2378           assert(0 && "Don't support illegal by-val vector arguments yet!");
2379         }
2380       }
2381       break;
2382     }
2383   }
2384
2385   if (RetVals.size() == 0)
2386     RetVals.push_back(MVT::isVoid);
2387   
2388   // Create the node.
2389   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2390
2391   // Set up the return result vector.
2392   Ops.clear();
2393   unsigned i = 0;
2394   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2395     MVT::ValueType VT = getValueType(I->getType());
2396     
2397     switch (getTypeAction(VT)) {
2398     default: assert(0 && "Unknown type action!");
2399     case Legal: 
2400       Ops.push_back(SDOperand(Result, i++));
2401       break;
2402     case Promote: {
2403       SDOperand Op(Result, i++);
2404       if (MVT::isInteger(VT)) {
2405         unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
2406                                                      : ISD::AssertZext;
2407         Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2408         Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2409       } else {
2410         assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2411         Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2412       }
2413       Ops.push_back(Op);
2414       break;
2415     }
2416     case Expand:
2417       if (VT != MVT::Vector) {
2418         // If this is a large integer, it needs to be reassembled from small
2419         // integers.  Figure out what the source elt type is and how many small
2420         // integers it is.
2421         MVT::ValueType NVT = getTypeToTransformTo(VT);
2422         unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2423         if (NumVals == 2) {
2424           SDOperand Lo = SDOperand(Result, i++);
2425           SDOperand Hi = SDOperand(Result, i++);
2426           
2427           if (!isLittleEndian())
2428             std::swap(Lo, Hi);
2429             
2430           Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2431         } else {
2432           // Value scalarized into many values.  Unimp for now.
2433           assert(0 && "Cannot expand i64 -> i16 yet!");
2434         }
2435       } else {
2436         // Otherwise, this is a vector type.  We only support legal vectors
2437         // right now.
2438         const PackedType *PTy = cast<PackedType>(I->getType());
2439         unsigned NumElems = PTy->getNumElements();
2440         const Type *EltTy = PTy->getElementType();
2441
2442         // Figure out if there is a Packed type corresponding to this Vector
2443         // type.  If so, convert to the packed type.
2444         MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2445         if (TVT != MVT::Other && isTypeLegal(TVT)) {
2446           SDOperand N = SDOperand(Result, i++);
2447           // Handle copies from generic vectors to registers.
2448           MVT::ValueType PTyElementVT, PTyLegalElementVT;
2449           unsigned NE = getPackedTypeBreakdown(PTy, PTyElementVT,
2450                                                PTyLegalElementVT);
2451           // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2452           // "N x PTyElementVT" MVT::Vector type.
2453           N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2454                           DAG.getConstant(NE, MVT::i32), 
2455                           DAG.getValueType(PTyElementVT));
2456           Ops.push_back(N);
2457         } else {
2458           assert(0 && "Don't support illegal by-val vector arguments yet!");
2459         }
2460       }
2461       break;
2462     }
2463   }
2464   return Ops;
2465 }
2466
2467 // It is always conservatively correct for llvm.returnaddress and
2468 // llvm.frameaddress to return 0.
2469 std::pair<SDOperand, SDOperand>
2470 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2471                                         unsigned Depth, SelectionDAG &DAG) {
2472   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2473 }
2474
2475 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2476   assert(0 && "LowerOperation not implemented for this target!");
2477   abort();
2478   return SDOperand();
2479 }
2480
2481 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2482                                                  SelectionDAG &DAG) {
2483   assert(0 && "CustomPromoteOperation not implemented for this target!");
2484   abort();
2485   return SDOperand();
2486 }
2487
2488 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2489   unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2490   std::pair<SDOperand,SDOperand> Result =
2491     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2492   setValue(&I, Result.first);
2493   DAG.setRoot(Result.second);
2494 }
2495
2496 /// getMemsetValue - Vectorized representation of the memset value
2497 /// operand.
2498 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2499                                 SelectionDAG &DAG) {
2500   MVT::ValueType CurVT = VT;
2501   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2502     uint64_t Val   = C->getValue() & 255;
2503     unsigned Shift = 8;
2504     while (CurVT != MVT::i8) {
2505       Val = (Val << Shift) | Val;
2506       Shift <<= 1;
2507       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2508     }
2509     return DAG.getConstant(Val, VT);
2510   } else {
2511     Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2512     unsigned Shift = 8;
2513     while (CurVT != MVT::i8) {
2514       Value =
2515         DAG.getNode(ISD::OR, VT,
2516                     DAG.getNode(ISD::SHL, VT, Value,
2517                                 DAG.getConstant(Shift, MVT::i8)), Value);
2518       Shift <<= 1;
2519       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2520     }
2521
2522     return Value;
2523   }
2524 }
2525
2526 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2527 /// used when a memcpy is turned into a memset when the source is a constant
2528 /// string ptr.
2529 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2530                                     SelectionDAG &DAG, TargetLowering &TLI,
2531                                     std::string &Str, unsigned Offset) {
2532   MVT::ValueType CurVT = VT;
2533   uint64_t Val = 0;
2534   unsigned MSB = getSizeInBits(VT) / 8;
2535   if (TLI.isLittleEndian())
2536     Offset = Offset + MSB - 1;
2537   for (unsigned i = 0; i != MSB; ++i) {
2538     Val = (Val << 8) | Str[Offset];
2539     Offset += TLI.isLittleEndian() ? -1 : 1;
2540   }
2541   return DAG.getConstant(Val, VT);
2542 }
2543
2544 /// getMemBasePlusOffset - Returns base and offset node for the 
2545 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2546                                       SelectionDAG &DAG, TargetLowering &TLI) {
2547   MVT::ValueType VT = Base.getValueType();
2548   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2549 }
2550
2551 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2552 /// to replace the memset / memcpy is below the threshold. It also returns the
2553 /// types of the sequence of  memory ops to perform memset / memcpy.
2554 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2555                                      unsigned Limit, uint64_t Size,
2556                                      unsigned Align, TargetLowering &TLI) {
2557   MVT::ValueType VT;
2558
2559   if (TLI.allowsUnalignedMemoryAccesses()) {
2560     VT = MVT::i64;
2561   } else {
2562     switch (Align & 7) {
2563     case 0:
2564       VT = MVT::i64;
2565       break;
2566     case 4:
2567       VT = MVT::i32;
2568       break;
2569     case 2:
2570       VT = MVT::i16;
2571       break;
2572     default:
2573       VT = MVT::i8;
2574       break;
2575     }
2576   }
2577
2578   MVT::ValueType LVT = MVT::i64;
2579   while (!TLI.isTypeLegal(LVT))
2580     LVT = (MVT::ValueType)((unsigned)LVT - 1);
2581   assert(MVT::isInteger(LVT));
2582
2583   if (VT > LVT)
2584     VT = LVT;
2585
2586   unsigned NumMemOps = 0;
2587   while (Size != 0) {
2588     unsigned VTSize = getSizeInBits(VT) / 8;
2589     while (VTSize > Size) {
2590       VT = (MVT::ValueType)((unsigned)VT - 1);
2591       VTSize >>= 1;
2592     }
2593     assert(MVT::isInteger(VT));
2594
2595     if (++NumMemOps > Limit)
2596       return false;
2597     MemOps.push_back(VT);
2598     Size -= VTSize;
2599   }
2600
2601   return true;
2602 }
2603
2604 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2605   SDOperand Op1 = getValue(I.getOperand(1));
2606   SDOperand Op2 = getValue(I.getOperand(2));
2607   SDOperand Op3 = getValue(I.getOperand(3));
2608   SDOperand Op4 = getValue(I.getOperand(4));
2609   unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2610   if (Align == 0) Align = 1;
2611
2612   if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2613     std::vector<MVT::ValueType> MemOps;
2614
2615     // Expand memset / memcpy to a series of load / store ops
2616     // if the size operand falls below a certain threshold.
2617     std::vector<SDOperand> OutChains;
2618     switch (Op) {
2619     default: break;  // Do nothing for now.
2620     case ISD::MEMSET: {
2621       if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2622                                    Size->getValue(), Align, TLI)) {
2623         unsigned NumMemOps = MemOps.size();
2624         unsigned Offset = 0;
2625         for (unsigned i = 0; i < NumMemOps; i++) {
2626           MVT::ValueType VT = MemOps[i];
2627           unsigned VTSize = getSizeInBits(VT) / 8;
2628           SDOperand Value = getMemsetValue(Op2, VT, DAG);
2629           SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2630                                         Value,
2631                                     getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2632                                       DAG.getSrcValue(I.getOperand(1), Offset));
2633           OutChains.push_back(Store);
2634           Offset += VTSize;
2635         }
2636       }
2637       break;
2638     }
2639     case ISD::MEMCPY: {
2640       if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2641                                    Size->getValue(), Align, TLI)) {
2642         unsigned NumMemOps = MemOps.size();
2643         unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2644         GlobalAddressSDNode *G = NULL;
2645         std::string Str;
2646         bool CopyFromStr = false;
2647
2648         if (Op2.getOpcode() == ISD::GlobalAddress)
2649           G = cast<GlobalAddressSDNode>(Op2);
2650         else if (Op2.getOpcode() == ISD::ADD &&
2651                  Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2652                  Op2.getOperand(1).getOpcode() == ISD::Constant) {
2653           G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2654           SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2655         }
2656         if (G) {
2657           GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2658           if (GV) {
2659             Str = GV->getStringValue(false);
2660             if (!Str.empty()) {
2661               CopyFromStr = true;
2662               SrcOff += SrcDelta;
2663             }
2664           }
2665         }
2666
2667         for (unsigned i = 0; i < NumMemOps; i++) {
2668           MVT::ValueType VT = MemOps[i];
2669           unsigned VTSize = getSizeInBits(VT) / 8;
2670           SDOperand Value, Chain, Store;
2671
2672           if (CopyFromStr) {
2673             Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2674             Chain = getRoot();
2675             Store =
2676               DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2677                           getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2678                           DAG.getSrcValue(I.getOperand(1), DstOff));
2679           } else {
2680             Value = DAG.getLoad(VT, getRoot(),
2681                         getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2682                         DAG.getSrcValue(I.getOperand(2), SrcOff));
2683             Chain = Value.getValue(1);
2684             Store =
2685               DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2686                           getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2687                           DAG.getSrcValue(I.getOperand(1), DstOff));
2688           }
2689           OutChains.push_back(Store);
2690           SrcOff += VTSize;
2691           DstOff += VTSize;
2692         }
2693       }
2694       break;
2695     }
2696     }
2697
2698     if (!OutChains.empty()) {
2699       DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2700       return;
2701     }
2702   }
2703
2704   std::vector<SDOperand> Ops;
2705   Ops.push_back(getRoot());
2706   Ops.push_back(Op1);
2707   Ops.push_back(Op2);
2708   Ops.push_back(Op3);
2709   Ops.push_back(Op4);
2710   DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2711 }
2712
2713 //===----------------------------------------------------------------------===//
2714 // SelectionDAGISel code
2715 //===----------------------------------------------------------------------===//
2716
2717 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2718   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2719 }
2720
2721 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2722   // FIXME: we only modify the CFG to split critical edges.  This
2723   // updates dom and loop info.
2724 }
2725
2726
2727 /// OptimizeNoopCopyExpression - We have determined that the specified cast
2728 /// instruction is a noop copy (e.g. it's casting from one pointer type to
2729 /// another, int->uint, or int->sbyte on PPC.
2730 ///
2731 /// Return true if any changes are made.
2732 static bool OptimizeNoopCopyExpression(CastInst *CI) {
2733   BasicBlock *DefBB = CI->getParent();
2734   
2735   /// InsertedCasts - Only insert a cast in each block once.
2736   std::map<BasicBlock*, CastInst*> InsertedCasts;
2737   
2738   bool MadeChange = false;
2739   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
2740        UI != E; ) {
2741     Use &TheUse = UI.getUse();
2742     Instruction *User = cast<Instruction>(*UI);
2743     
2744     // Figure out which BB this cast is used in.  For PHI's this is the
2745     // appropriate predecessor block.
2746     BasicBlock *UserBB = User->getParent();
2747     if (PHINode *PN = dyn_cast<PHINode>(User)) {
2748       unsigned OpVal = UI.getOperandNo()/2;
2749       UserBB = PN->getIncomingBlock(OpVal);
2750     }
2751     
2752     // Preincrement use iterator so we don't invalidate it.
2753     ++UI;
2754     
2755     // If this user is in the same block as the cast, don't change the cast.
2756     if (UserBB == DefBB) continue;
2757     
2758     // If we have already inserted a cast into this block, use it.
2759     CastInst *&InsertedCast = InsertedCasts[UserBB];
2760
2761     if (!InsertedCast) {
2762       BasicBlock::iterator InsertPt = UserBB->begin();
2763       while (isa<PHINode>(InsertPt)) ++InsertPt;
2764       
2765       InsertedCast = 
2766         new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2767       MadeChange = true;
2768     }
2769     
2770     // Replace a use of the cast with a use of the new casat.
2771     TheUse = InsertedCast;
2772   }
2773   
2774   // If we removed all uses, nuke the cast.
2775   if (CI->use_empty())
2776     CI->eraseFromParent();
2777   
2778   return MadeChange;
2779 }
2780
2781 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2782 /// casting to the type of GEPI.
2783 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
2784                                          Instruction *GEPI, Value *Ptr,
2785                                          Value *PtrOffset) {
2786   if (V) return V;   // Already computed.
2787   
2788   BasicBlock::iterator InsertPt;
2789   if (BB == GEPI->getParent()) {
2790     // If insert into the GEP's block, insert right after the GEP.
2791     InsertPt = GEPI;
2792     ++InsertPt;
2793   } else {
2794     // Otherwise, insert at the top of BB, after any PHI nodes
2795     InsertPt = BB->begin();
2796     while (isa<PHINode>(InsertPt)) ++InsertPt;
2797   }
2798   
2799   // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2800   // BB so that there is only one value live across basic blocks (the cast 
2801   // operand).
2802   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2803     if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2804       Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2805   
2806   // Add the offset, cast it to the right type.
2807   Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2808   return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2809 }
2810
2811 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
2812 /// compute its value.  The RepPtr value can be computed with Ptr+PtrOffset. One
2813 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
2814 /// block, then ReplaceAllUsesWith'ing everything.  However, we would prefer to
2815 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
2816 /// the constant add into a load or store instruction.  Additionally, if a user
2817 /// is a pointer-pointer cast, we look through it to find its users.
2818 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr, 
2819                                  Constant *PtrOffset, BasicBlock *DefBB,
2820                                  GetElementPtrInst *GEPI,
2821                            std::map<BasicBlock*,Instruction*> &InsertedExprs) {
2822   while (!RepPtr->use_empty()) {
2823     Instruction *User = cast<Instruction>(RepPtr->use_back());
2824     
2825     // If the user is a Pointer-Pointer cast, recurse.
2826     if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
2827       ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
2828       
2829       // Drop the use of RepPtr. The cast is dead.  Don't delete it now, else we
2830       // could invalidate an iterator.
2831       User->setOperand(0, UndefValue::get(RepPtr->getType()));
2832       continue;
2833     }
2834     
2835     // If this is a load of the pointer, or a store through the pointer, emit
2836     // the increment into the load/store block.
2837     Instruction *NewVal;
2838     if (isa<LoadInst>(User) ||
2839         (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
2840       NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()], 
2841                                     User->getParent(), GEPI,
2842                                     Ptr, PtrOffset);
2843     } else {
2844       // If this use is not foldable into the addressing mode, use a version 
2845       // emitted in the GEP block.
2846       NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI, 
2847                                     Ptr, PtrOffset);
2848     }
2849     
2850     if (GEPI->getType() != RepPtr->getType()) {
2851       BasicBlock::iterator IP = NewVal;
2852       ++IP;
2853       NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
2854     }
2855     User->replaceUsesOfWith(RepPtr, NewVal);
2856   }
2857 }
2858
2859
2860 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2861 /// selection, we want to be a bit careful about some things.  In particular, if
2862 /// we have a GEP instruction that is used in a different block than it is
2863 /// defined, the addressing expression of the GEP cannot be folded into loads or
2864 /// stores that use it.  In this case, decompose the GEP and move constant
2865 /// indices into blocks that use it.
2866 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
2867                                   const TargetData *TD) {
2868   // If this GEP is only used inside the block it is defined in, there is no
2869   // need to rewrite it.
2870   bool isUsedOutsideDefBB = false;
2871   BasicBlock *DefBB = GEPI->getParent();
2872   for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end(); 
2873        UI != E; ++UI) {
2874     if (cast<Instruction>(*UI)->getParent() != DefBB) {
2875       isUsedOutsideDefBB = true;
2876       break;
2877     }
2878   }
2879   if (!isUsedOutsideDefBB) return false;
2880
2881   // If this GEP has no non-zero constant indices, there is nothing we can do,
2882   // ignore it.
2883   bool hasConstantIndex = false;
2884   bool hasVariableIndex = false;
2885   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2886        E = GEPI->op_end(); OI != E; ++OI) {
2887     if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
2888       if (CI->getRawValue()) {
2889         hasConstantIndex = true;
2890         break;
2891       }
2892     } else {
2893       hasVariableIndex = true;
2894     }
2895   }
2896   
2897   // If this is a "GEP X, 0, 0, 0", turn this into a cast.
2898   if (!hasConstantIndex && !hasVariableIndex) {
2899     Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(), 
2900                              GEPI->getName(), GEPI);
2901     GEPI->replaceAllUsesWith(NC);
2902     GEPI->eraseFromParent();
2903     return true;
2904   }
2905   
2906   // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2907   if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
2908     return false;
2909   
2910   // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
2911   // constant offset (which we now know is non-zero) and deal with it later.
2912   uint64_t ConstantOffset = 0;
2913   const Type *UIntPtrTy = TD->getIntPtrType();
2914   Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2915   const Type *Ty = GEPI->getOperand(0)->getType();
2916
2917   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2918        E = GEPI->op_end(); OI != E; ++OI) {
2919     Value *Idx = *OI;
2920     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2921       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2922       if (Field)
2923         ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
2924       Ty = StTy->getElementType(Field);
2925     } else {
2926       Ty = cast<SequentialType>(Ty)->getElementType();
2927
2928       // Handle constant subscripts.
2929       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2930         if (CI->getRawValue() == 0) continue;
2931         
2932         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2933           ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
2934         else
2935           ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2936         continue;
2937       }
2938       
2939       // Ptr = Ptr + Idx * ElementSize;
2940       
2941       // Cast Idx to UIntPtrTy if needed.
2942       Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2943       
2944       uint64_t ElementSize = TD->getTypeSize(Ty);
2945       // Mask off bits that should not be set.
2946       ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2947       Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2948
2949       // Multiply by the element size and add to the base.
2950       Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2951       Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2952     }
2953   }
2954   
2955   // Make sure that the offset fits in uintptr_t.
2956   ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2957   Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2958   
2959   // Okay, we have now emitted all of the variable index parts to the BB that
2960   // the GEP is defined in.  Loop over all of the using instructions, inserting
2961   // an "add Ptr, ConstantOffset" into each block that uses it and update the
2962   // instruction to use the newly computed value, making GEPI dead.  When the
2963   // user is a load or store instruction address, we emit the add into the user
2964   // block, otherwise we use a canonical version right next to the gep (these 
2965   // won't be foldable as addresses, so we might as well share the computation).
2966   
2967   std::map<BasicBlock*,Instruction*> InsertedExprs;
2968   ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
2969   
2970   // Finally, the GEP is dead, remove it.
2971   GEPI->eraseFromParent();
2972   
2973   return true;
2974 }
2975
2976 bool SelectionDAGISel::runOnFunction(Function &Fn) {
2977   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2978   RegMap = MF.getSSARegMap();
2979   DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2980
2981   // First, split all critical edges for PHI nodes with incoming values that are
2982   // constants, this way the load of the constant into a vreg will not be placed
2983   // into MBBs that are used some other way.
2984   //
2985   // In this pass we also look for GEP and cast instructions that are used
2986   // across basic blocks and rewrite them to improve basic-block-at-a-time
2987   // selection.
2988   //
2989   // 
2990   bool MadeChange = true;
2991   while (MadeChange) {
2992     MadeChange = false;
2993   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2994     PHINode *PN;
2995     BasicBlock::iterator BBI;
2996     for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2997       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2998         if (isa<Constant>(PN->getIncomingValue(i)))
2999           SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3000     
3001     for (BasicBlock::iterator E = BB->end(); BBI != E; ) {
3002       Instruction *I = BBI++;
3003       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3004         MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3005       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3006         // If this is a noop copy, sink it into user blocks to reduce the number
3007         // of virtual registers that must be created and coallesced.
3008         MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3009         MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3010         
3011         // This is an fp<->int conversion?
3012         if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3013           continue;
3014         
3015         // If this is an extension, it will be a zero or sign extension, which
3016         // isn't a noop.
3017         if (SrcVT < DstVT) continue;
3018         
3019         // If these values will be promoted, find out what they will be promoted
3020         // to.  This helps us consider truncates on PPC as noop copies when they
3021         // are.
3022         if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3023           SrcVT = TLI.getTypeToTransformTo(SrcVT);
3024         if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3025           DstVT = TLI.getTypeToTransformTo(DstVT);
3026
3027         // If, after promotion, these are the same types, this is a noop copy.
3028         if (SrcVT == DstVT)
3029           MadeChange |= OptimizeNoopCopyExpression(CI);
3030       }
3031     }
3032   }
3033   }
3034   
3035   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3036
3037   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3038     SelectBasicBlock(I, MF, FuncInfo);
3039
3040   return true;
3041 }
3042
3043
3044 SDOperand SelectionDAGISel::
3045 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
3046   SDOperand Op = SDL.getValue(V);
3047   assert((Op.getOpcode() != ISD::CopyFromReg ||
3048           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3049          "Copy from a reg to the same reg!");
3050   
3051   // If this type is not legal, we must make sure to not create an invalid
3052   // register use.
3053   MVT::ValueType SrcVT = Op.getValueType();
3054   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3055   SelectionDAG &DAG = SDL.DAG;
3056   if (SrcVT == DestVT) {
3057     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3058   } else if (SrcVT == MVT::Vector) {
3059     // Handle copies from generic vectors to registers.
3060     MVT::ValueType PTyElementVT, PTyLegalElementVT;
3061     unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3062                                              PTyElementVT, PTyLegalElementVT);
3063     
3064     // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT" 
3065     // MVT::Vector type.
3066     Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3067                      DAG.getConstant(NE, MVT::i32), 
3068                      DAG.getValueType(PTyElementVT));
3069
3070     // Loop over all of the elements of the resultant vector,
3071     // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3072     // copying them into output registers.
3073     std::vector<SDOperand> OutChains;
3074     SDOperand Root = SDL.getRoot();
3075     for (unsigned i = 0; i != NE; ++i) {
3076       SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3077                                   Op, DAG.getConstant(i, MVT::i32));
3078       if (PTyElementVT == PTyLegalElementVT) {
3079         // Elements are legal.
3080         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3081       } else if (PTyLegalElementVT > PTyElementVT) {
3082         // Elements are promoted.
3083         if (MVT::isFloatingPoint(PTyLegalElementVT))
3084           Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3085         else
3086           Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3087         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3088       } else {
3089         // Elements are expanded.
3090         // The src value is expanded into multiple registers.
3091         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3092                                    Elt, DAG.getConstant(0, MVT::i32));
3093         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3094                                    Elt, DAG.getConstant(1, MVT::i32));
3095         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3096         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3097       }
3098     }
3099     return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
3100   } else if (SrcVT < DestVT) {
3101     // The src value is promoted to the register.
3102     if (MVT::isFloatingPoint(SrcVT))
3103       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3104     else
3105       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3106     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3107   } else  {
3108     // The src value is expanded into multiple registers.
3109     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3110                                Op, DAG.getConstant(0, MVT::i32));
3111     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3112                                Op, DAG.getConstant(1, MVT::i32));
3113     Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3114     return DAG.getCopyToReg(Op, Reg+1, Hi);
3115   }
3116 }
3117
3118 void SelectionDAGISel::
3119 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3120                std::vector<SDOperand> &UnorderedChains) {
3121   // If this is the entry block, emit arguments.
3122   Function &F = *BB->getParent();
3123   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3124   SDOperand OldRoot = SDL.DAG.getRoot();
3125   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3126
3127   unsigned a = 0;
3128   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3129        AI != E; ++AI, ++a)
3130     if (!AI->use_empty()) {
3131       SDL.setValue(AI, Args[a]);
3132
3133       // If this argument is live outside of the entry block, insert a copy from
3134       // whereever we got it to the vreg that other BB's will reference it as.
3135       if (FuncInfo.ValueMap.count(AI)) {
3136         SDOperand Copy =
3137           CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3138         UnorderedChains.push_back(Copy);
3139       }
3140     }
3141
3142   // Next, if the function has live ins that need to be copied into vregs,
3143   // emit the copies now, into the top of the block.
3144   MachineFunction &MF = SDL.DAG.getMachineFunction();
3145   if (MF.livein_begin() != MF.livein_end()) {
3146     SSARegMap *RegMap = MF.getSSARegMap();
3147     const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
3148     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
3149          E = MF.livein_end(); LI != E; ++LI)
3150       if (LI->second)
3151         MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
3152                          LI->first, RegMap->getRegClass(LI->second));
3153   }
3154     
3155   // Finally, if the target has anything special to do, allow it to do so.
3156   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3157 }
3158
3159
3160 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3161        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3162                                          FunctionLoweringInfo &FuncInfo) {
3163   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3164
3165   std::vector<SDOperand> UnorderedChains;
3166
3167   // Lower any arguments needed in this block if this is the entry block.
3168   if (LLVMBB == &LLVMBB->getParent()->front())
3169     LowerArguments(LLVMBB, SDL, UnorderedChains);
3170
3171   BB = FuncInfo.MBBMap[LLVMBB];
3172   SDL.setCurrentBasicBlock(BB);
3173
3174   // Lower all of the non-terminator instructions.
3175   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3176        I != E; ++I)
3177     SDL.visit(*I);
3178   
3179   // Ensure that all instructions which are used outside of their defining
3180   // blocks are available as virtual registers.
3181   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3182     if (!I->use_empty() && !isa<PHINode>(I)) {
3183       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3184       if (VMI != FuncInfo.ValueMap.end())
3185         UnorderedChains.push_back(
3186                            CopyValueToVirtualRegister(SDL, I, VMI->second));
3187     }
3188
3189   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
3190   // ensure constants are generated when needed.  Remember the virtual registers
3191   // that need to be added to the Machine PHI nodes as input.  We cannot just
3192   // directly add them, because expansion might result in multiple MBB's for one
3193   // BB.  As such, the start of the BB might correspond to a different MBB than
3194   // the end.
3195   //
3196
3197   // Emit constants only once even if used by multiple PHI nodes.
3198   std::map<Constant*, unsigned> ConstantsOut;
3199
3200   // Check successor nodes PHI nodes that expect a constant to be available from
3201   // this block.
3202   TerminatorInst *TI = LLVMBB->getTerminator();
3203   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3204     BasicBlock *SuccBB = TI->getSuccessor(succ);
3205     MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3206     PHINode *PN;
3207
3208     // At this point we know that there is a 1-1 correspondence between LLVM PHI
3209     // nodes and Machine PHI nodes, but the incoming operands have not been
3210     // emitted yet.
3211     for (BasicBlock::iterator I = SuccBB->begin();
3212          (PN = dyn_cast<PHINode>(I)); ++I)
3213       if (!PN->use_empty()) {
3214         unsigned Reg;
3215         Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3216         if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3217           unsigned &RegOut = ConstantsOut[C];
3218           if (RegOut == 0) {
3219             RegOut = FuncInfo.CreateRegForValue(C);
3220             UnorderedChains.push_back(
3221                              CopyValueToVirtualRegister(SDL, C, RegOut));
3222           }
3223           Reg = RegOut;
3224         } else {
3225           Reg = FuncInfo.ValueMap[PHIOp];
3226           if (Reg == 0) {
3227             assert(isa<AllocaInst>(PHIOp) &&
3228                    FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3229                    "Didn't codegen value into a register!??");
3230             Reg = FuncInfo.CreateRegForValue(PHIOp);
3231             UnorderedChains.push_back(
3232                              CopyValueToVirtualRegister(SDL, PHIOp, Reg));
3233           }
3234         }
3235
3236         // Remember that this register needs to added to the machine PHI node as
3237         // the input for this MBB.
3238         MVT::ValueType VT = TLI.getValueType(PN->getType());
3239         unsigned NumElements;
3240         if (VT != MVT::Vector)
3241           NumElements = TLI.getNumElements(VT);
3242         else {
3243           MVT::ValueType VT1,VT2;
3244           NumElements = 
3245             TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3246                                        VT1, VT2);
3247         }
3248         for (unsigned i = 0, e = NumElements; i != e; ++i)
3249           PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3250       }
3251   }
3252   ConstantsOut.clear();
3253
3254   // Turn all of the unordered chains into one factored node.
3255   if (!UnorderedChains.empty()) {
3256     SDOperand Root = SDL.getRoot();
3257     if (Root.getOpcode() != ISD::EntryToken) {
3258       unsigned i = 0, e = UnorderedChains.size();
3259       for (; i != e; ++i) {
3260         assert(UnorderedChains[i].Val->getNumOperands() > 1);
3261         if (UnorderedChains[i].Val->getOperand(0) == Root)
3262           break;  // Don't add the root if we already indirectly depend on it.
3263       }
3264         
3265       if (i == e)
3266         UnorderedChains.push_back(Root);
3267     }
3268     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3269   }
3270
3271   // Lower the terminator after the copies are emitted.
3272   SDL.visit(*LLVMBB->getTerminator());
3273
3274   // Copy over any CaseBlock records that may now exist due to SwitchInst
3275   // lowering, as well as any jump table information.
3276   SwitchCases.clear();
3277   SwitchCases = SDL.SwitchCases;
3278   JT = SDL.JT;
3279   
3280   // Make sure the root of the DAG is up-to-date.
3281   DAG.setRoot(SDL.getRoot());
3282 }
3283
3284 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3285   // Run the DAG combiner in pre-legalize mode.
3286   DAG.Combine(false);
3287   
3288   DEBUG(std::cerr << "Lowered selection DAG:\n");
3289   DEBUG(DAG.dump());
3290   
3291   // Second step, hack on the DAG until it only uses operations and types that
3292   // the target supports.
3293   DAG.Legalize();
3294   
3295   DEBUG(std::cerr << "Legalized selection DAG:\n");
3296   DEBUG(DAG.dump());
3297   
3298   // Run the DAG combiner in post-legalize mode.
3299   DAG.Combine(true);
3300   
3301   if (ViewISelDAGs) DAG.viewGraph();
3302
3303   // Third, instruction select all of the operations to machine code, adding the
3304   // code to the MachineBasicBlock.
3305   InstructionSelectBasicBlock(DAG);
3306   
3307   DEBUG(std::cerr << "Selected machine code:\n");
3308   DEBUG(BB->dump());
3309 }  
3310
3311 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3312                                         FunctionLoweringInfo &FuncInfo) {
3313   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3314   {
3315     SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3316     CurDAG = &DAG;
3317   
3318     // First step, lower LLVM code to some DAG.  This DAG may use operations and
3319     // types that are not supported by the target.
3320     BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3321
3322     // Second step, emit the lowered DAG as machine code.
3323     CodeGenAndEmitDAG(DAG);
3324   }
3325   
3326   // Next, now that we know what the last MBB the LLVM BB expanded is, update
3327   // PHI nodes in successors.
3328   if (SwitchCases.empty() && JT.Reg == 0) {
3329     for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3330       MachineInstr *PHI = PHINodesToUpdate[i].first;
3331       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3332              "This is not a machine PHI node that we are updating!");
3333       PHI->addRegOperand(PHINodesToUpdate[i].second);
3334       PHI->addMachineBasicBlockOperand(BB);
3335     }
3336     return;
3337   }
3338   
3339   // If the JumpTable record is filled in, then we need to emit a jump table.
3340   // Updating the PHI nodes is tricky in this case, since we need to determine
3341   // whether the PHI is a successor of the range check MBB or the jump table MBB
3342   if (JT.Reg) {
3343     assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3344     SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3345     CurDAG = &SDAG;
3346     SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3347     MachineBasicBlock *RangeBB = BB;
3348     // Set the current basic block to the mbb we wish to insert the code into
3349     BB = JT.MBB;
3350     SDL.setCurrentBasicBlock(BB);
3351     // Emit the code
3352     SDL.visitJumpTable(JT);
3353     SDAG.setRoot(SDL.getRoot());
3354     CodeGenAndEmitDAG(SDAG);
3355     // Update PHI Nodes
3356     for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3357       MachineInstr *PHI = PHINodesToUpdate[pi].first;
3358       MachineBasicBlock *PHIBB = PHI->getParent();
3359       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3360              "This is not a machine PHI node that we are updating!");
3361       if (PHIBB == JT.Default) {
3362         PHI->addRegOperand(PHINodesToUpdate[pi].second);
3363         PHI->addMachineBasicBlockOperand(RangeBB);
3364       }
3365       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3366         PHI->addRegOperand(PHINodesToUpdate[pi].second);
3367         PHI->addMachineBasicBlockOperand(BB);
3368       }
3369     }
3370     return;
3371   }
3372   
3373   // If we generated any switch lowering information, build and codegen any
3374   // additional DAGs necessary.
3375   for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3376     SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3377     CurDAG = &SDAG;
3378     SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3379     // Set the current basic block to the mbb we wish to insert the code into
3380     BB = SwitchCases[i].ThisBB;
3381     SDL.setCurrentBasicBlock(BB);
3382     // Emit the code
3383     SDL.visitSwitchCase(SwitchCases[i]);
3384     SDAG.setRoot(SDL.getRoot());
3385     CodeGenAndEmitDAG(SDAG);
3386     // Iterate over the phi nodes, if there is a phi node in a successor of this
3387     // block (for instance, the default block), then add a pair of operands to
3388     // the phi node for this block, as if we were coming from the original
3389     // BB before switch expansion.
3390     for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3391       MachineInstr *PHI = PHINodesToUpdate[pi].first;
3392       MachineBasicBlock *PHIBB = PHI->getParent();
3393       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3394              "This is not a machine PHI node that we are updating!");
3395       if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3396         PHI->addRegOperand(PHINodesToUpdate[pi].second);
3397         PHI->addMachineBasicBlockOperand(BB);
3398       }
3399     }
3400   }
3401 }
3402
3403 //===----------------------------------------------------------------------===//
3404 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3405 /// target node in the graph.
3406 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3407   if (ViewSchedDAGs) DAG.viewGraph();
3408   ScheduleDAG *SL = NULL;
3409
3410   switch (ISHeuristic) {
3411   default: assert(0 && "Unrecognized scheduling heuristic");
3412   case ScheduleDAG::defaultScheduling:
3413     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3414       SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3415     else {
3416       assert(TLI.getSchedulingPreference() ==
3417              TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
3418       SL = createBURRListDAGScheduler(DAG, BB);
3419     }
3420     break;
3421   case ScheduleDAG::noScheduling:
3422     SL = createBFS_DAGScheduler(DAG, BB);
3423     break;
3424   case ScheduleDAG::simpleScheduling:
3425     SL = createSimpleDAGScheduler(false, DAG, BB);
3426     break;
3427   case ScheduleDAG::simpleNoItinScheduling:
3428     SL = createSimpleDAGScheduler(true, DAG, BB);
3429     break;
3430   case ScheduleDAG::listSchedulingBURR:
3431     SL = createBURRListDAGScheduler(DAG, BB);
3432     break;
3433   case ScheduleDAG::listSchedulingTDRR:
3434     SL = createTDRRListDAGScheduler(DAG, BB);
3435     break;
3436   case ScheduleDAG::listSchedulingTD:
3437     SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3438     break;
3439   }
3440   BB = SL->Run();
3441   delete SL;
3442 }
3443
3444 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3445   return new HazardRecognizer();
3446 }
3447
3448 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3449 /// by tblgen.  Others should not call it.
3450 void SelectionDAGISel::
3451 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3452   std::vector<SDOperand> InOps;
3453   std::swap(InOps, Ops);
3454
3455   Ops.push_back(InOps[0]);  // input chain.
3456   Ops.push_back(InOps[1]);  // input asm string.
3457
3458   unsigned i = 2, e = InOps.size();
3459   if (InOps[e-1].getValueType() == MVT::Flag)
3460     --e;  // Don't process a flag operand if it is here.
3461   
3462   while (i != e) {
3463     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3464     if ((Flags & 7) != 4 /*MEM*/) {
3465       // Just skip over this operand, copying the operands verbatim.
3466       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3467       i += (Flags >> 3) + 1;
3468     } else {
3469       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3470       // Otherwise, this is a memory operand.  Ask the target to select it.
3471       std::vector<SDOperand> SelOps;
3472       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3473         std::cerr << "Could not match memory address.  Inline asm failure!\n";
3474         exit(1);
3475       }
3476       
3477       // Add this to the output node.
3478       Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3479       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3480       i += 2;
3481     }
3482   }
3483   
3484   // Add the flag input back if present.
3485   if (e != InOps.size())
3486     Ops.push_back(InOps.back());
3487 }