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