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