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