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