Fix spelling.
[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 is distributed under the University of Illinois Open Source
6 // 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/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
48 #include <algorithm>
49 using namespace llvm;
50
51 #ifndef NDEBUG
52 static cl::opt<bool>
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54           cl::desc("Pop up a window to show isel dags as they are selected"));
55 static cl::opt<bool>
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57           cl::desc("Pop up a window to show sched dags as they are processed"));
58 static cl::opt<bool>
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60       cl::desc("Pop up a window to show SUnit dags after they are processed"));
61 #else
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
63 #endif
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 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78                RegisterPassParser<RegisterScheduler> >
79 ISHeuristic("pre-RA-sched",
80             cl::init(&createDefaultScheduler),
81             cl::desc("Instruction schedulers available (before register"
82                      " allocation):"));
83
84 static RegisterScheduler
85 defaultListDAGScheduler("default", "  Best scheduler for the target",
86                         createDefaultScheduler);
87
88 namespace { struct SDISelAsmOperandInfo; }
89
90 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
91 /// insertvalue or extractvalue indices that identify a member, return
92 /// the linearized index of the start of the member.
93 ///
94 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
95                                    const unsigned *Indices,
96                                    const unsigned *IndicesEnd,
97                                    unsigned CurIndex = 0) {
98   // Base case: We're done.
99   if (Indices == IndicesEnd)
100     return CurIndex;
101
102   // Otherwise we need to recurse. A non-negative value is used to
103   // indicate the final result value; a negative value carries the
104   // complemented position to continue the search.
105   CurIndex = ~CurIndex;
106
107   // Given a struct type, recursively traverse the elements.
108   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
109     for (StructType::element_iterator EI = STy->element_begin(),
110                                       EE = STy->element_end();
111         EI != EE; ++EI) {
112       CurIndex = ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd,
113                                     ~CurIndex);
114       if ((int)CurIndex >= 0)
115         return CurIndex;
116     }
117   }
118   // Given an array type, recursively traverse the elements.
119   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
120     const Type *EltTy = ATy->getElementType();
121     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
122       CurIndex = ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd,
123                                     ~CurIndex);
124       if ((int)CurIndex >= 0)
125         return CurIndex;
126     }
127   }
128   // We haven't found the type we're looking for, so keep searching.
129   return CurIndex;
130 }
131
132 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
133 /// MVTs that represent all the individual underlying
134 /// non-aggregate types that comprise it.
135 ///
136 /// If Offsets is non-null, it points to a vector to be filled in
137 /// with the in-memory offsets of each of the individual values.
138 ///
139 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
140                             SmallVectorImpl<MVT> &ValueVTs,
141                             SmallVectorImpl<uint64_t> *Offsets = 0,
142                             uint64_t StartingOffset = 0) {
143   // Given a struct type, recursively traverse the elements.
144   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
145     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
146     for (StructType::element_iterator EB = STy->element_begin(),
147                                       EI = EB,
148                                       EE = STy->element_end();
149          EI != EE; ++EI)
150       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
151                       StartingOffset + SL->getElementOffset(EI - EB));
152     return;
153   }
154   // Given an array type, recursively traverse the elements.
155   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
156     const Type *EltTy = ATy->getElementType();
157     uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
158     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
159       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
160                       StartingOffset + i * EltSize);
161     return;
162   }
163   // Base case: we can get an MVT for this LLVM IR type.
164   ValueVTs.push_back(TLI.getValueType(Ty));
165   if (Offsets)
166     Offsets->push_back(StartingOffset);
167 }
168
169 namespace {
170   /// RegsForValue - This struct represents the registers (physical or virtual)
171   /// that a particular set of values is assigned, and the type information about
172   /// the value. The most common situation is to represent one value at a time,
173   /// but struct or array values are handled element-wise as multiple values.
174   /// The splitting of aggregates is performed recursively, so that we never
175   /// have aggregate-typed registers. The values at this point do not necessarily
176   /// have legal types, so each value may require one or more registers of some
177   /// legal type.
178   /// 
179   struct VISIBILITY_HIDDEN RegsForValue {
180     /// TLI - The TargetLowering object.
181     ///
182     const TargetLowering *TLI;
183
184     /// ValueVTs - The value types of the values, which may not be legal, and
185     /// may need be promoted or synthesized from one or more registers.
186     ///
187     SmallVector<MVT, 4> ValueVTs;
188     
189     /// RegVTs - The value types of the registers. This is the same size as
190     /// ValueVTs and it records, for each value, what the type of the assigned
191     /// register or registers are. (Individual values are never synthesized
192     /// from more than one type of register.)
193     ///
194     /// With virtual registers, the contents of RegVTs is redundant with TLI's
195     /// getRegisterType member function, however when with physical registers
196     /// it is necessary to have a separate record of the types.
197     ///
198     SmallVector<MVT, 4> RegVTs;
199     
200     /// Regs - This list holds the registers assigned to the values.
201     /// Each legal or promoted value requires one register, and each
202     /// expanded value requires multiple registers.
203     ///
204     SmallVector<unsigned, 4> Regs;
205     
206     RegsForValue() : TLI(0) {}
207     
208     RegsForValue(const TargetLowering &tli,
209                  const SmallVector<unsigned, 4> &regs, 
210                  MVT regvt, MVT valuevt)
211       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
212     RegsForValue(const TargetLowering &tli,
213                  const SmallVector<unsigned, 4> &regs, 
214                  const SmallVector<MVT, 4> &regvts,
215                  const SmallVector<MVT, 4> &valuevts)
216       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
217     RegsForValue(const TargetLowering &tli,
218                  unsigned Reg, const Type *Ty) : TLI(&tli) {
219       ComputeValueVTs(tli, Ty, ValueVTs);
220
221       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
222         MVT ValueVT = ValueVTs[Value];
223         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
224         MVT RegisterVT = TLI->getRegisterType(ValueVT);
225         for (unsigned i = 0; i != NumRegs; ++i)
226           Regs.push_back(Reg + i);
227         RegVTs.push_back(RegisterVT);
228         Reg += NumRegs;
229       }
230     }
231     
232     /// append - Add the specified values to this one.
233     void append(const RegsForValue &RHS) {
234       TLI = RHS.TLI;
235       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
236       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
237       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
238     }
239     
240     
241     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
242     /// this value and returns the result as a ValueVTs value.  This uses 
243     /// Chain/Flag as the input and updates them for the output Chain/Flag.
244     /// If the Flag pointer is NULL, no flag is used.
245     SDOperand getCopyFromRegs(SelectionDAG &DAG,
246                               SDOperand &Chain, SDOperand *Flag) const;
247
248     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
249     /// specified value into the registers specified by this object.  This uses 
250     /// Chain/Flag as the input and updates them for the output Chain/Flag.
251     /// If the Flag pointer is NULL, no flag is used.
252     void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
253                        SDOperand &Chain, SDOperand *Flag) const;
254     
255     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
256     /// operand list.  This adds the code marker and includes the number of 
257     /// values added into it.
258     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
259                               std::vector<SDOperand> &Ops) const;
260   };
261 }
262
263 namespace llvm {
264   //===--------------------------------------------------------------------===//
265   /// createDefaultScheduler - This creates an instruction scheduler appropriate
266   /// for the target.
267   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
268                                       SelectionDAG *DAG,
269                                       MachineBasicBlock *BB) {
270     TargetLowering &TLI = IS->getTargetLowering();
271     
272     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
273       return createTDListDAGScheduler(IS, DAG, BB);
274     } else {
275       assert(TLI.getSchedulingPreference() ==
276            TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
277       return createBURRListDAGScheduler(IS, DAG, BB);
278     }
279   }
280
281
282   //===--------------------------------------------------------------------===//
283   /// FunctionLoweringInfo - This contains information that is global to a
284   /// function that is used when lowering a region of the function.
285   class FunctionLoweringInfo {
286   public:
287     TargetLowering &TLI;
288     Function &Fn;
289     MachineFunction &MF;
290     MachineRegisterInfo &RegInfo;
291
292     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
293
294     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
295     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
296
297     /// ValueMap - Since we emit code for the function a basic block at a time,
298     /// we must remember which virtual registers hold the values for
299     /// cross-basic-block values.
300     DenseMap<const Value*, unsigned> ValueMap;
301
302     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
303     /// the entry block.  This allows the allocas to be efficiently referenced
304     /// anywhere in the function.
305     std::map<const AllocaInst*, int> StaticAllocaMap;
306
307 #ifndef NDEBUG
308     SmallSet<Instruction*, 8> CatchInfoLost;
309     SmallSet<Instruction*, 8> CatchInfoFound;
310 #endif
311
312     unsigned MakeReg(MVT VT) {
313       return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
314     }
315     
316     /// isExportedInst - Return true if the specified value is an instruction
317     /// exported from its block.
318     bool isExportedInst(const Value *V) {
319       return ValueMap.count(V);
320     }
321
322     unsigned CreateRegForValue(const Value *V);
323     
324     unsigned InitializeRegForValue(const Value *V) {
325       unsigned &R = ValueMap[V];
326       assert(R == 0 && "Already initialized this value register!");
327       return R = CreateRegForValue(V);
328     }
329   };
330 }
331
332 /// isSelector - Return true if this instruction is a call to the
333 /// eh.selector intrinsic.
334 static bool isSelector(Instruction *I) {
335   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
336     return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
337             II->getIntrinsicID() == Intrinsic::eh_selector_i64);
338   return false;
339 }
340
341 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
342 /// PHI nodes or outside of the basic block that defines it, or used by a 
343 /// switch or atomic instruction, which may expand to multiple basic blocks.
344 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
345   if (isa<PHINode>(I)) return true;
346   BasicBlock *BB = I->getParent();
347   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
348     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
349         // FIXME: Remove switchinst special case.
350         isa<SwitchInst>(*UI))
351       return true;
352   return false;
353 }
354
355 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
356 /// entry block, return true.  This includes arguments used by switches, since
357 /// the switch may expand into multiple basic blocks.
358 static bool isOnlyUsedInEntryBlock(Argument *A) {
359   BasicBlock *Entry = A->getParent()->begin();
360   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
361     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
362       return false;  // Use not in entry block.
363   return true;
364 }
365
366 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
367                                            Function &fn, MachineFunction &mf)
368     : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
369
370   // Create a vreg for each argument register that is not dead and is used
371   // outside of the entry block for the function.
372   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
373        AI != E; ++AI)
374     if (!isOnlyUsedInEntryBlock(AI))
375       InitializeRegForValue(AI);
376
377   // Initialize the mapping of values to registers.  This is only set up for
378   // instruction values that are used outside of the block that defines
379   // them.
380   Function::iterator BB = Fn.begin(), EB = Fn.end();
381   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
382     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
383       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
384         const Type *Ty = AI->getAllocatedType();
385         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
386         unsigned Align = 
387           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
388                    AI->getAlignment());
389
390         TySize *= CUI->getZExtValue();   // Get total allocated size.
391         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
392         StaticAllocaMap[AI] =
393           MF.getFrameInfo()->CreateStackObject(TySize, Align);
394       }
395
396   for (; BB != EB; ++BB)
397     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
398       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
399         if (!isa<AllocaInst>(I) ||
400             !StaticAllocaMap.count(cast<AllocaInst>(I)))
401           InitializeRegForValue(I);
402
403   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
404   // also creates the initial PHI MachineInstrs, though none of the input
405   // operands are populated.
406   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
407     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
408     MBBMap[BB] = MBB;
409     MF.getBasicBlockList().push_back(MBB);
410
411     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
412     // appropriate.
413     PHINode *PN;
414     for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
415       if (PN->use_empty()) continue;
416       
417       MVT VT = TLI.getValueType(PN->getType());
418       unsigned NumRegisters = TLI.getNumRegisters(VT);
419       unsigned PHIReg = ValueMap[PN];
420       assert(PHIReg && "PHI node does not have an assigned virtual register!");
421       const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
422       for (unsigned i = 0; i != NumRegisters; ++i)
423         BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
424     }
425   }
426 }
427
428 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
429 /// the correctly promoted or expanded types.  Assign these registers
430 /// consecutive vreg numbers and return the first assigned number.
431 ///
432 /// In the case that the given value has struct or array type, this function
433 /// will assign registers for each member or element.
434 ///
435 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
436   SmallVector<MVT, 4> ValueVTs;
437   ComputeValueVTs(TLI, V->getType(), ValueVTs);
438
439   unsigned FirstReg = 0;
440   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
441     MVT ValueVT = ValueVTs[Value];
442     MVT RegisterVT = TLI.getRegisterType(ValueVT);
443
444     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
445     for (unsigned i = 0; i != NumRegs; ++i) {
446       unsigned R = MakeReg(RegisterVT);
447       if (!FirstReg) FirstReg = R;
448     }
449   }
450   return FirstReg;
451 }
452
453 //===----------------------------------------------------------------------===//
454 /// SelectionDAGLowering - This is the common target-independent lowering
455 /// implementation that is parameterized by a TargetLowering object.
456 /// Also, targets can overload any lowering method.
457 ///
458 namespace llvm {
459 class SelectionDAGLowering {
460   MachineBasicBlock *CurMBB;
461
462   DenseMap<const Value*, SDOperand> NodeMap;
463
464   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
465   /// them up and then emit token factor nodes when possible.  This allows us to
466   /// get simple disambiguation between loads without worrying about alias
467   /// analysis.
468   std::vector<SDOperand> PendingLoads;
469
470   /// PendingExports - CopyToReg nodes that copy values to virtual registers
471   /// for export to other blocks need to be emitted before any terminator
472   /// instruction, but they have no other ordering requirements. We bunch them
473   /// up and the emit a single tokenfactor for them just before terminator
474   /// instructions.
475   std::vector<SDOperand> PendingExports;
476
477   /// Case - A struct to record the Value for a switch case, and the
478   /// case's target basic block.
479   struct Case {
480     Constant* Low;
481     Constant* High;
482     MachineBasicBlock* BB;
483
484     Case() : Low(0), High(0), BB(0) { }
485     Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
486       Low(low), High(high), BB(bb) { }
487     uint64_t size() const {
488       uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
489       uint64_t rLow  = cast<ConstantInt>(Low)->getSExtValue();
490       return (rHigh - rLow + 1ULL);
491     }
492   };
493
494   struct CaseBits {
495     uint64_t Mask;
496     MachineBasicBlock* BB;
497     unsigned Bits;
498
499     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
500       Mask(mask), BB(bb), Bits(bits) { }
501   };
502
503   typedef std::vector<Case>           CaseVector;
504   typedef std::vector<CaseBits>       CaseBitsVector;
505   typedef CaseVector::iterator        CaseItr;
506   typedef std::pair<CaseItr, CaseItr> CaseRange;
507
508   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
509   /// of conditional branches.
510   struct CaseRec {
511     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
512     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
513
514     /// CaseBB - The MBB in which to emit the compare and branch
515     MachineBasicBlock *CaseBB;
516     /// LT, GE - If nonzero, we know the current case value must be less-than or
517     /// greater-than-or-equal-to these Constants.
518     Constant *LT;
519     Constant *GE;
520     /// Range - A pair of iterators representing the range of case values to be
521     /// processed at this point in the binary search tree.
522     CaseRange Range;
523   };
524
525   typedef std::vector<CaseRec> CaseRecVector;
526
527   /// The comparison function for sorting the switch case values in the vector.
528   /// WARNING: Case ranges should be disjoint!
529   struct CaseCmp {
530     bool operator () (const Case& C1, const Case& C2) {
531       assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
532       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
533       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
534       return CI1->getValue().slt(CI2->getValue());
535     }
536   };
537
538   struct CaseBitsCmp {
539     bool operator () (const CaseBits& C1, const CaseBits& C2) {
540       return C1.Bits > C2.Bits;
541     }
542   };
543
544   unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
545   
546 public:
547   // TLI - This is information that describes the available target features we
548   // need for lowering.  This indicates when operations are unavailable,
549   // implemented with a libcall, etc.
550   TargetLowering &TLI;
551   SelectionDAG &DAG;
552   const TargetData *TD;
553   AliasAnalysis &AA;
554
555   /// SwitchCases - Vector of CaseBlock structures used to communicate
556   /// SwitchInst code generation information.
557   std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
558   /// JTCases - Vector of JumpTable structures used to communicate
559   /// SwitchInst code generation information.
560   std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
561   std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
562   
563   /// FuncInfo - Information about the function as a whole.
564   ///
565   FunctionLoweringInfo &FuncInfo;
566   
567   /// GCI - Garbage collection metadata for the function.
568   CollectorMetadata *GCI;
569
570   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
571                        AliasAnalysis &aa,
572                        FunctionLoweringInfo &funcinfo,
573                        CollectorMetadata *gci)
574     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
575       FuncInfo(funcinfo), GCI(gci) {
576   }
577
578   /// getRoot - Return the current virtual root of the Selection DAG,
579   /// flushing any PendingLoad items. This must be done before emitting
580   /// a store or any other node that may need to be ordered after any
581   /// prior load instructions.
582   ///
583   SDOperand getRoot() {
584     if (PendingLoads.empty())
585       return DAG.getRoot();
586
587     if (PendingLoads.size() == 1) {
588       SDOperand Root = PendingLoads[0];
589       DAG.setRoot(Root);
590       PendingLoads.clear();
591       return Root;
592     }
593
594     // Otherwise, we have to make a token factor node.
595     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
596                                  &PendingLoads[0], PendingLoads.size());
597     PendingLoads.clear();
598     DAG.setRoot(Root);
599     return Root;
600   }
601
602   /// getControlRoot - Similar to getRoot, but instead of flushing all the
603   /// PendingLoad items, flush all the PendingExports items. It is necessary
604   /// to do this before emitting a terminator instruction.
605   ///
606   SDOperand getControlRoot() {
607     SDOperand Root = DAG.getRoot();
608
609     if (PendingExports.empty())
610       return Root;
611
612     // Turn all of the CopyToReg chains into one factored node.
613     if (Root.getOpcode() != ISD::EntryToken) {
614       unsigned i = 0, e = PendingExports.size();
615       for (; i != e; ++i) {
616         assert(PendingExports[i].Val->getNumOperands() > 1);
617         if (PendingExports[i].Val->getOperand(0) == Root)
618           break;  // Don't add the root if we already indirectly depend on it.
619       }
620         
621       if (i == e)
622         PendingExports.push_back(Root);
623     }
624
625     Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
626                        &PendingExports[0],
627                        PendingExports.size());
628     PendingExports.clear();
629     DAG.setRoot(Root);
630     return Root;
631   }
632
633   void CopyValueToVirtualRegister(Value *V, unsigned Reg);
634
635   void visit(Instruction &I) { visit(I.getOpcode(), I); }
636
637   void visit(unsigned Opcode, User &I) {
638     // Note: this doesn't use InstVisitor, because it has to work with
639     // ConstantExpr's in addition to instructions.
640     switch (Opcode) {
641     default: assert(0 && "Unknown instruction type encountered!");
642              abort();
643       // Build the switch statement using the Instruction.def file.
644 #define HANDLE_INST(NUM, OPCODE, CLASS) \
645     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
646 #include "llvm/Instruction.def"
647     }
648   }
649
650   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
651
652   SDOperand getValue(const Value *V);
653
654   void setValue(const Value *V, SDOperand NewN) {
655     SDOperand &N = NodeMap[V];
656     assert(N.Val == 0 && "Already set a value for this node!");
657     N = NewN;
658   }
659   
660   void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
661                             std::set<unsigned> &OutputRegs, 
662                             std::set<unsigned> &InputRegs);
663
664   void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
665                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
666                             unsigned Opc);
667   bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
668   void ExportFromCurrentBlock(Value *V);
669   void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
670                    MachineBasicBlock *LandingPad = NULL);
671
672   // Terminator instructions.
673   void visitRet(ReturnInst &I);
674   void visitBr(BranchInst &I);
675   void visitSwitch(SwitchInst &I);
676   void visitUnreachable(UnreachableInst &I) { /* noop */ }
677
678   // Helpers for visitSwitch
679   bool handleSmallSwitchRange(CaseRec& CR,
680                               CaseRecVector& WorkList,
681                               Value* SV,
682                               MachineBasicBlock* Default);
683   bool handleJTSwitchCase(CaseRec& CR,
684                           CaseRecVector& WorkList,
685                           Value* SV,
686                           MachineBasicBlock* Default);
687   bool handleBTSplitSwitchCase(CaseRec& CR,
688                                CaseRecVector& WorkList,
689                                Value* SV,
690                                MachineBasicBlock* Default);
691   bool handleBitTestsSwitchCase(CaseRec& CR,
692                                 CaseRecVector& WorkList,
693                                 Value* SV,
694                                 MachineBasicBlock* Default);  
695   void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
696   void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
697   void visitBitTestCase(MachineBasicBlock* NextMBB,
698                         unsigned Reg,
699                         SelectionDAGISel::BitTestCase &B);
700   void visitJumpTable(SelectionDAGISel::JumpTable &JT);
701   void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
702                             SelectionDAGISel::JumpTableHeader &JTH);
703   
704   // These all get lowered before this pass.
705   void visitInvoke(InvokeInst &I);
706   void visitUnwind(UnwindInst &I);
707
708   void visitBinary(User &I, unsigned OpCode);
709   void visitShift(User &I, unsigned Opcode);
710   void visitAdd(User &I) { 
711     if (I.getType()->isFPOrFPVector())
712       visitBinary(I, ISD::FADD);
713     else
714       visitBinary(I, ISD::ADD);
715   }
716   void visitSub(User &I);
717   void visitMul(User &I) {
718     if (I.getType()->isFPOrFPVector())
719       visitBinary(I, ISD::FMUL);
720     else
721       visitBinary(I, ISD::MUL);
722   }
723   void visitURem(User &I) { visitBinary(I, ISD::UREM); }
724   void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
725   void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
726   void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
727   void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
728   void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
729   void visitAnd (User &I) { visitBinary(I, ISD::AND); }
730   void visitOr  (User &I) { visitBinary(I, ISD::OR); }
731   void visitXor (User &I) { visitBinary(I, ISD::XOR); }
732   void visitShl (User &I) { visitShift(I, ISD::SHL); }
733   void visitLShr(User &I) { visitShift(I, ISD::SRL); }
734   void visitAShr(User &I) { visitShift(I, ISD::SRA); }
735   void visitICmp(User &I);
736   void visitFCmp(User &I);
737   void visitVICmp(User &I);
738   void visitVFCmp(User &I);
739   // Visit the conversion instructions
740   void visitTrunc(User &I);
741   void visitZExt(User &I);
742   void visitSExt(User &I);
743   void visitFPTrunc(User &I);
744   void visitFPExt(User &I);
745   void visitFPToUI(User &I);
746   void visitFPToSI(User &I);
747   void visitUIToFP(User &I);
748   void visitSIToFP(User &I);
749   void visitPtrToInt(User &I);
750   void visitIntToPtr(User &I);
751   void visitBitCast(User &I);
752
753   void visitExtractElement(User &I);
754   void visitInsertElement(User &I);
755   void visitShuffleVector(User &I);
756
757   void visitExtractValue(ExtractValueInst &I);
758   void visitInsertValue(InsertValueInst &I);
759
760   void visitGetElementPtr(User &I);
761   void visitSelect(User &I);
762
763   void visitMalloc(MallocInst &I);
764   void visitFree(FreeInst &I);
765   void visitAlloca(AllocaInst &I);
766   void visitLoad(LoadInst &I);
767   void visitStore(StoreInst &I);
768   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
769   void visitCall(CallInst &I);
770   void visitInlineAsm(CallSite CS);
771   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
772   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
773
774   void visitVAStart(CallInst &I);
775   void visitVAArg(VAArgInst &I);
776   void visitVAEnd(CallInst &I);
777   void visitVACopy(CallInst &I);
778
779   void visitGetResult(GetResultInst &I);
780
781   void visitUserOp1(Instruction &I) {
782     assert(0 && "UserOp1 should not exist at instruction selection time!");
783     abort();
784   }
785   void visitUserOp2(Instruction &I) {
786     assert(0 && "UserOp2 should not exist at instruction selection time!");
787     abort();
788   }
789   
790 private:
791   inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
792
793 };
794 } // end namespace llvm
795
796
797 /// getCopyFromParts - Create a value that contains the specified legal parts
798 /// combined into the value they represent.  If the parts combine to a type
799 /// larger then ValueVT then AssertOp can be used to specify whether the extra
800 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
801 /// (ISD::AssertSext).
802 static SDOperand getCopyFromParts(SelectionDAG &DAG,
803                                   const SDOperand *Parts,
804                                   unsigned NumParts,
805                                   MVT PartVT,
806                                   MVT ValueVT,
807                                   ISD::NodeType AssertOp = ISD::DELETED_NODE) {
808   assert(NumParts > 0 && "No parts to assemble!");
809   TargetLowering &TLI = DAG.getTargetLoweringInfo();
810   SDOperand Val = Parts[0];
811
812   if (NumParts > 1) {
813     // Assemble the value from multiple parts.
814     if (!ValueVT.isVector()) {
815       unsigned PartBits = PartVT.getSizeInBits();
816       unsigned ValueBits = ValueVT.getSizeInBits();
817
818       // Assemble the power of 2 part.
819       unsigned RoundParts = NumParts & (NumParts - 1) ?
820         1 << Log2_32(NumParts) : NumParts;
821       unsigned RoundBits = PartBits * RoundParts;
822       MVT RoundVT = RoundBits == ValueBits ?
823         ValueVT : MVT::getIntegerVT(RoundBits);
824       SDOperand Lo, Hi;
825
826       if (RoundParts > 2) {
827         MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
828         Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
829         Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
830                               PartVT, HalfVT);
831       } else {
832         Lo = Parts[0];
833         Hi = Parts[1];
834       }
835       if (TLI.isBigEndian())
836         std::swap(Lo, Hi);
837       Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
838
839       if (RoundParts < NumParts) {
840         // Assemble the trailing non-power-of-2 part.
841         unsigned OddParts = NumParts - RoundParts;
842         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
843         Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
844
845         // Combine the round and odd parts.
846         Lo = Val;
847         if (TLI.isBigEndian())
848           std::swap(Lo, Hi);
849         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
850         Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
851         Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
852                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
853                                          TLI.getShiftAmountTy()));
854         Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
855         Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
856       }
857     } else {
858       // Handle a multi-element vector.
859       MVT IntermediateVT, RegisterVT;
860       unsigned NumIntermediates;
861       unsigned NumRegs =
862         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
863                                    RegisterVT);
864       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
865       NumParts = NumRegs; // Silence a compiler warning.
866       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
867       assert(RegisterVT == Parts[0].getValueType() &&
868              "Part type doesn't match part!");
869
870       // Assemble the parts into intermediate operands.
871       SmallVector<SDOperand, 8> Ops(NumIntermediates);
872       if (NumIntermediates == NumParts) {
873         // If the register was not expanded, truncate or copy the value,
874         // as appropriate.
875         for (unsigned i = 0; i != NumParts; ++i)
876           Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
877                                     PartVT, IntermediateVT);
878       } else if (NumParts > 0) {
879         // If the intermediate type was expanded, build the intermediate operands
880         // from the parts.
881         assert(NumParts % NumIntermediates == 0 &&
882                "Must expand into a divisible number of parts!");
883         unsigned Factor = NumParts / NumIntermediates;
884         for (unsigned i = 0; i != NumIntermediates; ++i)
885           Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
886                                     PartVT, IntermediateVT);
887       }
888
889       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
890       // operands.
891       Val = DAG.getNode(IntermediateVT.isVector() ?
892                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
893                         ValueVT, &Ops[0], NumIntermediates);
894     }
895   }
896
897   // There is now one part, held in Val.  Correct it to match ValueVT.
898   PartVT = Val.getValueType();
899
900   if (PartVT == ValueVT)
901     return Val;
902
903   if (PartVT.isVector()) {
904     assert(ValueVT.isVector() && "Unknown vector conversion!");
905     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
906   }
907
908   if (ValueVT.isVector()) {
909     assert(ValueVT.getVectorElementType() == PartVT &&
910            ValueVT.getVectorNumElements() == 1 &&
911            "Only trivial scalar-to-vector conversions should get here!");
912     return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
913   }
914
915   if (PartVT.isInteger() &&
916       ValueVT.isInteger()) {
917     if (ValueVT.bitsLT(PartVT)) {
918       // For a truncate, see if we have any information to
919       // indicate whether the truncated bits will always be
920       // zero or sign-extension.
921       if (AssertOp != ISD::DELETED_NODE)
922         Val = DAG.getNode(AssertOp, PartVT, Val,
923                           DAG.getValueType(ValueVT));
924       return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
925     } else {
926       return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
927     }
928   }
929
930   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
931     if (ValueVT.bitsLT(Val.getValueType()))
932       // FP_ROUND's are always exact here.
933       return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
934                          DAG.getIntPtrConstant(1));
935     return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
936   }
937
938   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
939     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
940
941   assert(0 && "Unknown mismatch!");
942   return SDOperand();
943 }
944
945 /// getCopyToParts - Create a series of nodes that contain the specified value
946 /// split into legal parts.  If the parts contain more bits than Val, then, for
947 /// integers, ExtendKind can be used to specify how to generate the extra bits.
948 static void getCopyToParts(SelectionDAG &DAG,
949                            SDOperand Val,
950                            SDOperand *Parts,
951                            unsigned NumParts,
952                            MVT PartVT,
953                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
954   TargetLowering &TLI = DAG.getTargetLoweringInfo();
955   MVT PtrVT = TLI.getPointerTy();
956   MVT ValueVT = Val.getValueType();
957   unsigned PartBits = PartVT.getSizeInBits();
958   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
959
960   if (!NumParts)
961     return;
962
963   if (!ValueVT.isVector()) {
964     if (PartVT == ValueVT) {
965       assert(NumParts == 1 && "No-op copy with multiple parts!");
966       Parts[0] = Val;
967       return;
968     }
969
970     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
971       // If the parts cover more bits than the value has, promote the value.
972       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
973         assert(NumParts == 1 && "Do not know what to promote to!");
974         Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
975       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
976         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
977         Val = DAG.getNode(ExtendKind, ValueVT, Val);
978       } else {
979         assert(0 && "Unknown mismatch!");
980       }
981     } else if (PartBits == ValueVT.getSizeInBits()) {
982       // Different types of the same size.
983       assert(NumParts == 1 && PartVT != ValueVT);
984       Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
985     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
986       // If the parts cover less bits than value has, truncate the value.
987       if (PartVT.isInteger() && ValueVT.isInteger()) {
988         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
989         Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
990       } else {
991         assert(0 && "Unknown mismatch!");
992       }
993     }
994
995     // The value may have changed - recompute ValueVT.
996     ValueVT = Val.getValueType();
997     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
998            "Failed to tile the value with PartVT!");
999
1000     if (NumParts == 1) {
1001       assert(PartVT == ValueVT && "Type conversion failed!");
1002       Parts[0] = Val;
1003       return;
1004     }
1005
1006     // Expand the value into multiple parts.
1007     if (NumParts & (NumParts - 1)) {
1008       // The number of parts is not a power of 2.  Split off and copy the tail.
1009       assert(PartVT.isInteger() && ValueVT.isInteger() &&
1010              "Do not know what to expand to!");
1011       unsigned RoundParts = 1 << Log2_32(NumParts);
1012       unsigned RoundBits = RoundParts * PartBits;
1013       unsigned OddParts = NumParts - RoundParts;
1014       SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1015                                      DAG.getConstant(RoundBits,
1016                                                      TLI.getShiftAmountTy()));
1017       getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1018       if (TLI.isBigEndian())
1019         // The odd parts were reversed by getCopyToParts - unreverse them.
1020         std::reverse(Parts + RoundParts, Parts + NumParts);
1021       NumParts = RoundParts;
1022       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1023       Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1024     }
1025
1026     // The number of parts is a power of 2.  Repeatedly bisect the value using
1027     // EXTRACT_ELEMENT.
1028     Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
1029                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
1030                            Val);
1031     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1032       for (unsigned i = 0; i < NumParts; i += StepSize) {
1033         unsigned ThisBits = StepSize * PartBits / 2;
1034         MVT ThisVT = MVT::getIntegerVT (ThisBits);
1035         SDOperand &Part0 = Parts[i];
1036         SDOperand &Part1 = Parts[i+StepSize/2];
1037
1038         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1039                             DAG.getConstant(1, PtrVT));
1040         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1041                             DAG.getConstant(0, PtrVT));
1042
1043         if (ThisBits == PartBits && ThisVT != PartVT) {
1044           Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1045           Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1046         }
1047       }
1048     }
1049
1050     if (TLI.isBigEndian())
1051       std::reverse(Parts, Parts + NumParts);
1052
1053     return;
1054   }
1055
1056   // Vector ValueVT.
1057   if (NumParts == 1) {
1058     if (PartVT != ValueVT) {
1059       if (PartVT.isVector()) {
1060         Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1061       } else {
1062         assert(ValueVT.getVectorElementType() == PartVT &&
1063                ValueVT.getVectorNumElements() == 1 &&
1064                "Only trivial vector-to-scalar conversions should get here!");
1065         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1066                           DAG.getConstant(0, PtrVT));
1067       }
1068     }
1069
1070     Parts[0] = Val;
1071     return;
1072   }
1073
1074   // Handle a multi-element vector.
1075   MVT IntermediateVT, RegisterVT;
1076   unsigned NumIntermediates;
1077   unsigned NumRegs =
1078     DAG.getTargetLoweringInfo()
1079       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1080                               RegisterVT);
1081   unsigned NumElements = ValueVT.getVectorNumElements();
1082
1083   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1084   NumParts = NumRegs; // Silence a compiler warning.
1085   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1086
1087   // Split the vector into intermediate operands.
1088   SmallVector<SDOperand, 8> Ops(NumIntermediates);
1089   for (unsigned i = 0; i != NumIntermediates; ++i)
1090     if (IntermediateVT.isVector())
1091       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1092                            IntermediateVT, Val,
1093                            DAG.getConstant(i * (NumElements / NumIntermediates),
1094                                            PtrVT));
1095     else
1096       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1097                            IntermediateVT, Val, 
1098                            DAG.getConstant(i, PtrVT));
1099
1100   // Split the intermediate operands into legal parts.
1101   if (NumParts == NumIntermediates) {
1102     // If the register was not expanded, promote or copy the value,
1103     // as appropriate.
1104     for (unsigned i = 0; i != NumParts; ++i)
1105       getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1106   } else if (NumParts > 0) {
1107     // If the intermediate type was expanded, split each the value into
1108     // legal parts.
1109     assert(NumParts % NumIntermediates == 0 &&
1110            "Must expand into a divisible number of parts!");
1111     unsigned Factor = NumParts / NumIntermediates;
1112     for (unsigned i = 0; i != NumIntermediates; ++i)
1113       getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1114   }
1115 }
1116
1117
1118 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1119   SDOperand &N = NodeMap[V];
1120   if (N.Val) return N;
1121   
1122   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1123     MVT VT = TLI.getValueType(V->getType(), true);
1124     
1125     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1126       return N = DAG.getConstant(CI->getValue(), VT);
1127
1128     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1129       return N = DAG.getGlobalAddress(GV, VT);
1130     
1131     if (isa<ConstantPointerNull>(C))
1132       return N = DAG.getConstant(0, TLI.getPointerTy());
1133     
1134     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1135       return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1136     
1137     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1138         !V->getType()->isAggregateType())
1139       return N = DAG.getNode(ISD::UNDEF, VT);
1140
1141     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1142       visit(CE->getOpcode(), *CE);
1143       SDOperand N1 = NodeMap[V];
1144       assert(N1.Val && "visit didn't populate the ValueMap!");
1145       return N1;
1146     }
1147     
1148     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1149       SmallVector<SDOperand, 4> Constants;
1150       SmallVector<MVT, 4> ValueVTs;
1151       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1152            OI != OE; ++OI) {
1153         SDNode *Val = getValue(*OI).Val;
1154         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) {
1155           Constants.push_back(SDOperand(Val, i));
1156           ValueVTs.push_back(Val->getValueType(i));
1157         }
1158       }
1159       return DAG.getNode(ISD::MERGE_VALUES,
1160                          DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1161                          &Constants[0], Constants.size());
1162     }
1163
1164     if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
1165       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1166              "Unknown array constant!");
1167       unsigned NumElts = ATy->getNumElements();
1168       if (NumElts == 0)
1169         return SDOperand(); // empty array
1170       MVT EltVT = TLI.getValueType(ATy->getElementType());
1171       SmallVector<SDOperand, 4> Constants(NumElts);
1172       SmallVector<MVT, 4> ValueVTs(NumElts, EltVT);
1173       for (unsigned i = 0, e = NumElts; i != e; ++i) {
1174         if (isa<UndefValue>(C))
1175           Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1176         else if (EltVT.isFloatingPoint())
1177           Constants[i] = DAG.getConstantFP(0, EltVT);
1178         else
1179           Constants[i] = DAG.getConstant(0, EltVT);
1180       }
1181       return DAG.getNode(ISD::MERGE_VALUES,
1182                          DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1183                          &Constants[0], Constants.size());
1184     }
1185
1186     if (const StructType *STy = dyn_cast<StructType>(C->getType())) {
1187       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1188              "Unknown struct constant!");
1189       unsigned NumElts = STy->getNumElements();
1190       if (NumElts == 0)
1191         return SDOperand(); // empty struct
1192       SmallVector<SDOperand, 4> Constants(NumElts);
1193       SmallVector<MVT, 4> ValueVTs(NumElts);
1194       for (unsigned i = 0, e = NumElts; i != e; ++i) {
1195         MVT EltVT = TLI.getValueType(STy->getElementType(i));
1196         ValueVTs[i] = EltVT;
1197         if (isa<UndefValue>(C))
1198           Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1199         else if (EltVT.isFloatingPoint())
1200           Constants[i] = DAG.getConstantFP(0, EltVT);
1201         else
1202           Constants[i] = DAG.getConstant(0, EltVT);
1203       }
1204       return DAG.getNode(ISD::MERGE_VALUES,
1205                          DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1206                          &Constants[0], Constants.size());
1207     }
1208
1209     const VectorType *VecTy = cast<VectorType>(V->getType());
1210     unsigned NumElements = VecTy->getNumElements();
1211     
1212     // Now that we know the number and type of the elements, get that number of
1213     // elements into the Ops array based on what kind of constant it is.
1214     SmallVector<SDOperand, 16> Ops;
1215     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1216       for (unsigned i = 0; i != NumElements; ++i)
1217         Ops.push_back(getValue(CP->getOperand(i)));
1218     } else {
1219       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1220              "Unknown vector constant!");
1221       MVT EltVT = TLI.getValueType(VecTy->getElementType());
1222
1223       SDOperand Op;
1224       if (isa<UndefValue>(C))
1225         Op = DAG.getNode(ISD::UNDEF, EltVT);
1226       else if (EltVT.isFloatingPoint())
1227         Op = DAG.getConstantFP(0, EltVT);
1228       else
1229         Op = DAG.getConstant(0, EltVT);
1230       Ops.assign(NumElements, Op);
1231     }
1232     
1233     // Create a BUILD_VECTOR node.
1234     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1235   }
1236       
1237   // If this is a static alloca, generate it as the frameindex instead of
1238   // computation.
1239   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1240     std::map<const AllocaInst*, int>::iterator SI =
1241       FuncInfo.StaticAllocaMap.find(AI);
1242     if (SI != FuncInfo.StaticAllocaMap.end())
1243       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1244   }
1245       
1246   unsigned InReg = FuncInfo.ValueMap[V];
1247   assert(InReg && "Value not in map!");
1248   
1249   RegsForValue RFV(TLI, InReg, V->getType());
1250   SDOperand Chain = DAG.getEntryNode();
1251   return RFV.getCopyFromRegs(DAG, Chain, NULL);
1252 }
1253
1254
1255 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1256   if (I.getNumOperands() == 0) {
1257     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1258     return;
1259   }
1260   
1261   SmallVector<SDOperand, 8> NewValues;
1262   NewValues.push_back(getControlRoot());
1263   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {  
1264     SDOperand RetOp = getValue(I.getOperand(i));
1265     MVT VT = RetOp.getValueType();
1266
1267     // FIXME: C calling convention requires the return type to be promoted to
1268     // at least 32-bit. But this is not necessary for non-C calling conventions.
1269     if (VT.isInteger()) {
1270       MVT MinVT = TLI.getRegisterType(MVT::i32);
1271       if (VT.bitsLT(MinVT))
1272         VT = MinVT;
1273     }
1274
1275     unsigned NumParts = TLI.getNumRegisters(VT);
1276     MVT PartVT = TLI.getRegisterType(VT);
1277     SmallVector<SDOperand, 4> Parts(NumParts);
1278     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1279
1280     const Function *F = I.getParent()->getParent();
1281     if (F->paramHasAttr(0, ParamAttr::SExt))
1282       ExtendKind = ISD::SIGN_EXTEND;
1283     else if (F->paramHasAttr(0, ParamAttr::ZExt))
1284       ExtendKind = ISD::ZERO_EXTEND;
1285
1286     getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1287
1288     for (unsigned i = 0; i < NumParts; ++i) {
1289       NewValues.push_back(Parts[i]);
1290       NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1291     }
1292   }
1293   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1294                           &NewValues[0], NewValues.size()));
1295 }
1296
1297 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1298 /// the current basic block, add it to ValueMap now so that we'll get a
1299 /// CopyTo/FromReg.
1300 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1301   // No need to export constants.
1302   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1303   
1304   // Already exported?
1305   if (FuncInfo.isExportedInst(V)) return;
1306
1307   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1308   CopyValueToVirtualRegister(V, Reg);
1309 }
1310
1311 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1312                                                     const BasicBlock *FromBB) {
1313   // The operands of the setcc have to be in this block.  We don't know
1314   // how to export them from some other block.
1315   if (Instruction *VI = dyn_cast<Instruction>(V)) {
1316     // Can export from current BB.
1317     if (VI->getParent() == FromBB)
1318       return true;
1319     
1320     // Is already exported, noop.
1321     return FuncInfo.isExportedInst(V);
1322   }
1323   
1324   // If this is an argument, we can export it if the BB is the entry block or
1325   // if it is already exported.
1326   if (isa<Argument>(V)) {
1327     if (FromBB == &FromBB->getParent()->getEntryBlock())
1328       return true;
1329
1330     // Otherwise, can only export this if it is already exported.
1331     return FuncInfo.isExportedInst(V);
1332   }
1333   
1334   // Otherwise, constants can always be exported.
1335   return true;
1336 }
1337
1338 static bool InBlock(const Value *V, const BasicBlock *BB) {
1339   if (const Instruction *I = dyn_cast<Instruction>(V))
1340     return I->getParent() == BB;
1341   return true;
1342 }
1343
1344 /// FindMergedConditions - If Cond is an expression like 
1345 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1346                                                 MachineBasicBlock *TBB,
1347                                                 MachineBasicBlock *FBB,
1348                                                 MachineBasicBlock *CurBB,
1349                                                 unsigned Opc) {
1350   // If this node is not part of the or/and tree, emit it as a branch.
1351   Instruction *BOp = dyn_cast<Instruction>(Cond);
1352
1353   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 
1354       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1355       BOp->getParent() != CurBB->getBasicBlock() ||
1356       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1357       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1358     const BasicBlock *BB = CurBB->getBasicBlock();
1359     
1360     // If the leaf of the tree is a comparison, merge the condition into 
1361     // the caseblock.
1362     if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1363         // The operands of the cmp have to be in this block.  We don't know
1364         // how to export them from some other block.  If this is the first block
1365         // of the sequence, no exporting is needed.
1366         (CurBB == CurMBB ||
1367          (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1368           isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1369       BOp = cast<Instruction>(Cond);
1370       ISD::CondCode Condition;
1371       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1372         switch (IC->getPredicate()) {
1373         default: assert(0 && "Unknown icmp predicate opcode!");
1374         case ICmpInst::ICMP_EQ:  Condition = ISD::SETEQ;  break;
1375         case ICmpInst::ICMP_NE:  Condition = ISD::SETNE;  break;
1376         case ICmpInst::ICMP_SLE: Condition = ISD::SETLE;  break;
1377         case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1378         case ICmpInst::ICMP_SGE: Condition = ISD::SETGE;  break;
1379         case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1380         case ICmpInst::ICMP_SLT: Condition = ISD::SETLT;  break;
1381         case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1382         case ICmpInst::ICMP_SGT: Condition = ISD::SETGT;  break;
1383         case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1384         }
1385       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1386         ISD::CondCode FPC, FOC;
1387         switch (FC->getPredicate()) {
1388         default: assert(0 && "Unknown fcmp predicate opcode!");
1389         case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1390         case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1391         case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1392         case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1393         case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1394         case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1395         case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1396         case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1397         case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1398         case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1399         case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1400         case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1401         case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1402         case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1403         case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1404         case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1405         }
1406         if (FiniteOnlyFPMath())
1407           Condition = FOC;
1408         else 
1409           Condition = FPC;
1410       } else {
1411         Condition = ISD::SETEQ; // silence warning.
1412         assert(0 && "Unknown compare instruction");
1413       }
1414       
1415       SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0), 
1416                                      BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1417       SwitchCases.push_back(CB);
1418       return;
1419     }
1420     
1421     // Create a CaseBlock record representing this branch.
1422     SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1423                                    NULL, TBB, FBB, CurBB);
1424     SwitchCases.push_back(CB);
1425     return;
1426   }
1427   
1428   
1429   //  Create TmpBB after CurBB.
1430   MachineFunction::iterator BBI = CurBB;
1431   MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1432   CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1433   
1434   if (Opc == Instruction::Or) {
1435     // Codegen X | Y as:
1436     //   jmp_if_X TBB
1437     //   jmp TmpBB
1438     // TmpBB:
1439     //   jmp_if_Y TBB
1440     //   jmp FBB
1441     //
1442   
1443     // Emit the LHS condition.
1444     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1445   
1446     // Emit the RHS condition into TmpBB.
1447     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1448   } else {
1449     assert(Opc == Instruction::And && "Unknown merge op!");
1450     // Codegen X & Y as:
1451     //   jmp_if_X TmpBB
1452     //   jmp FBB
1453     // TmpBB:
1454     //   jmp_if_Y TBB
1455     //   jmp FBB
1456     //
1457     //  This requires creation of TmpBB after CurBB.
1458     
1459     // Emit the LHS condition.
1460     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1461     
1462     // Emit the RHS condition into TmpBB.
1463     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1464   }
1465 }
1466
1467 /// If the set of cases should be emitted as a series of branches, return true.
1468 /// If we should emit this as a bunch of and/or'd together conditions, return
1469 /// false.
1470 static bool 
1471 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1472   if (Cases.size() != 2) return true;
1473   
1474   // If this is two comparisons of the same values or'd or and'd together, they
1475   // will get folded into a single comparison, so don't emit two blocks.
1476   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1477        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1478       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1479        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1480     return false;
1481   }
1482   
1483   return true;
1484 }
1485
1486 void SelectionDAGLowering::visitBr(BranchInst &I) {
1487   // Update machine-CFG edges.
1488   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1489
1490   // Figure out which block is immediately after the current one.
1491   MachineBasicBlock *NextBlock = 0;
1492   MachineFunction::iterator BBI = CurMBB;
1493   if (++BBI != CurMBB->getParent()->end())
1494     NextBlock = BBI;
1495
1496   if (I.isUnconditional()) {
1497     // Update machine-CFG edges.
1498     CurMBB->addSuccessor(Succ0MBB);
1499     
1500     // If this is not a fall-through branch, emit the branch.
1501     if (Succ0MBB != NextBlock)
1502       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1503                               DAG.getBasicBlock(Succ0MBB)));
1504     return;
1505   }
1506
1507   // If this condition is one of the special cases we handle, do special stuff
1508   // now.
1509   Value *CondVal = I.getCondition();
1510   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1511
1512   // If this is a series of conditions that are or'd or and'd together, emit
1513   // this as a sequence of branches instead of setcc's with and/or operations.
1514   // For example, instead of something like:
1515   //     cmp A, B
1516   //     C = seteq 
1517   //     cmp D, E
1518   //     F = setle 
1519   //     or C, F
1520   //     jnz foo
1521   // Emit:
1522   //     cmp A, B
1523   //     je foo
1524   //     cmp D, E
1525   //     jle foo
1526   //
1527   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1528     if (BOp->hasOneUse() && 
1529         (BOp->getOpcode() == Instruction::And ||
1530          BOp->getOpcode() == Instruction::Or)) {
1531       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1532       // If the compares in later blocks need to use values not currently
1533       // exported from this block, export them now.  This block should always
1534       // be the first entry.
1535       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1536       
1537       // Allow some cases to be rejected.
1538       if (ShouldEmitAsBranches(SwitchCases)) {
1539         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1540           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1541           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1542         }
1543         
1544         // Emit the branch for this block.
1545         visitSwitchCase(SwitchCases[0]);
1546         SwitchCases.erase(SwitchCases.begin());
1547         return;
1548       }
1549       
1550       // Okay, we decided not to do this, remove any inserted MBB's and clear
1551       // SwitchCases.
1552       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1553         CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1554       
1555       SwitchCases.clear();
1556     }
1557   }
1558   
1559   // Create a CaseBlock record representing this branch.
1560   SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1561                                  NULL, Succ0MBB, Succ1MBB, CurMBB);
1562   // Use visitSwitchCase to actually insert the fast branch sequence for this
1563   // cond branch.
1564   visitSwitchCase(CB);
1565 }
1566
1567 /// visitSwitchCase - Emits the necessary code to represent a single node in
1568 /// the binary search tree resulting from lowering a switch instruction.
1569 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1570   SDOperand Cond;
1571   SDOperand CondLHS = getValue(CB.CmpLHS);
1572   
1573   // Build the setcc now. 
1574   if (CB.CmpMHS == NULL) {
1575     // Fold "(X == true)" to X and "(X == false)" to !X to
1576     // handle common cases produced by branch lowering.
1577     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1578       Cond = CondLHS;
1579     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1580       SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1581       Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1582     } else
1583       Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1584   } else {
1585     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1586
1587     uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1588     uint64_t High  = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1589
1590     SDOperand CmpOp = getValue(CB.CmpMHS);
1591     MVT VT = CmpOp.getValueType();
1592
1593     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1594       Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1595     } else {
1596       SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1597       Cond = DAG.getSetCC(MVT::i1, SUB,
1598                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1599     }
1600   }
1601   
1602   // Update successor info
1603   CurMBB->addSuccessor(CB.TrueBB);
1604   CurMBB->addSuccessor(CB.FalseBB);
1605   
1606   // Set NextBlock to be the MBB immediately after the current one, if any.
1607   // This is used to avoid emitting unnecessary branches to the next block.
1608   MachineBasicBlock *NextBlock = 0;
1609   MachineFunction::iterator BBI = CurMBB;
1610   if (++BBI != CurMBB->getParent()->end())
1611     NextBlock = BBI;
1612   
1613   // If the lhs block is the next block, invert the condition so that we can
1614   // fall through to the lhs instead of the rhs block.
1615   if (CB.TrueBB == NextBlock) {
1616     std::swap(CB.TrueBB, CB.FalseBB);
1617     SDOperand True = DAG.getConstant(1, Cond.getValueType());
1618     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1619   }
1620   SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1621                                  DAG.getBasicBlock(CB.TrueBB));
1622   if (CB.FalseBB == NextBlock)
1623     DAG.setRoot(BrCond);
1624   else
1625     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1626                             DAG.getBasicBlock(CB.FalseBB)));
1627 }
1628
1629 /// visitJumpTable - Emit JumpTable node in the current MBB
1630 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1631   // Emit the code for the jump table
1632   assert(JT.Reg != -1U && "Should lower JT Header first!");
1633   MVT PTy = TLI.getPointerTy();
1634   SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1635   SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1636   DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1637                           Table, Index));
1638   return;
1639 }
1640
1641 /// visitJumpTableHeader - This function emits necessary code to produce index
1642 /// in the JumpTable from switch case.
1643 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1644                                          SelectionDAGISel::JumpTableHeader &JTH) {
1645   // Subtract the lowest switch case value from the value being switched on
1646   // and conditional branch to default mbb if the result is greater than the
1647   // difference between smallest and largest cases.
1648   SDOperand SwitchOp = getValue(JTH.SValue);
1649   MVT VT = SwitchOp.getValueType();
1650   SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1651                               DAG.getConstant(JTH.First, VT));
1652   
1653   // The SDNode we just created, which holds the value being switched on
1654   // minus the the smallest case value, needs to be copied to a virtual
1655   // register so it can be used as an index into the jump table in a 
1656   // subsequent basic block.  This value may be smaller or larger than the
1657   // target's pointer type, and therefore require extension or truncating.
1658   if (VT.bitsGT(TLI.getPointerTy()))
1659     SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1660   else
1661     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1662   
1663   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1664   SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1665   JT.Reg = JumpTableReg;
1666
1667   // Emit the range check for the jump table, and branch to the default
1668   // block for the switch statement if the value being switched on exceeds
1669   // the largest case in the switch.
1670   SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1671                                DAG.getConstant(JTH.Last-JTH.First,VT),
1672                                ISD::SETUGT);
1673
1674   // Set NextBlock to be the MBB immediately after the current one, if any.
1675   // This is used to avoid emitting unnecessary branches to the next block.
1676   MachineBasicBlock *NextBlock = 0;
1677   MachineFunction::iterator BBI = CurMBB;
1678   if (++BBI != CurMBB->getParent()->end())
1679     NextBlock = BBI;
1680
1681   SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1682                                  DAG.getBasicBlock(JT.Default));
1683
1684   if (JT.MBB == NextBlock)
1685     DAG.setRoot(BrCond);
1686   else
1687     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1688                             DAG.getBasicBlock(JT.MBB)));
1689
1690   return;
1691 }
1692
1693 /// visitBitTestHeader - This function emits necessary code to produce value
1694 /// suitable for "bit tests"
1695 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1696   // Subtract the minimum value
1697   SDOperand SwitchOp = getValue(B.SValue);
1698   MVT VT = SwitchOp.getValueType();
1699   SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1700                               DAG.getConstant(B.First, VT));
1701
1702   // Check range
1703   SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1704                                     DAG.getConstant(B.Range, VT),
1705                                     ISD::SETUGT);
1706
1707   SDOperand ShiftOp;
1708   if (VT.bitsGT(TLI.getShiftAmountTy()))
1709     ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1710   else
1711     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1712
1713   // Make desired shift
1714   SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1715                                     DAG.getConstant(1, TLI.getPointerTy()),
1716                                     ShiftOp);
1717
1718   unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1719   SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1720   B.Reg = SwitchReg;
1721
1722   // Set NextBlock to be the MBB immediately after the current one, if any.
1723   // This is used to avoid emitting unnecessary branches to the next block.
1724   MachineBasicBlock *NextBlock = 0;
1725   MachineFunction::iterator BBI = CurMBB;
1726   if (++BBI != CurMBB->getParent()->end())
1727     NextBlock = BBI;
1728
1729   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1730
1731   CurMBB->addSuccessor(B.Default);
1732   CurMBB->addSuccessor(MBB);
1733
1734   SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1735                                   DAG.getBasicBlock(B.Default));
1736   
1737   if (MBB == NextBlock)
1738     DAG.setRoot(BrRange);
1739   else
1740     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1741                             DAG.getBasicBlock(MBB)));
1742
1743   return;
1744 }
1745
1746 /// visitBitTestCase - this function produces one "bit test"
1747 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1748                                             unsigned Reg,
1749                                             SelectionDAGISel::BitTestCase &B) {
1750   // Emit bit tests and jumps
1751   SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1752   
1753   SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1754                                 SwitchVal,
1755                                 DAG.getConstant(B.Mask,
1756                                                 TLI.getPointerTy()));
1757   SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1758                                   DAG.getConstant(0, TLI.getPointerTy()),
1759                                   ISD::SETNE);
1760
1761   CurMBB->addSuccessor(B.TargetBB);
1762   CurMBB->addSuccessor(NextMBB);
1763   
1764   SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1765                                 AndCmp, DAG.getBasicBlock(B.TargetBB));
1766
1767   // Set NextBlock to be the MBB immediately after the current one, if any.
1768   // This is used to avoid emitting unnecessary branches to the next block.
1769   MachineBasicBlock *NextBlock = 0;
1770   MachineFunction::iterator BBI = CurMBB;
1771   if (++BBI != CurMBB->getParent()->end())
1772     NextBlock = BBI;
1773
1774   if (NextMBB == NextBlock)
1775     DAG.setRoot(BrAnd);
1776   else
1777     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1778                             DAG.getBasicBlock(NextMBB)));
1779
1780   return;
1781 }
1782
1783 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1784   // Retrieve successors.
1785   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1786   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1787
1788   if (isa<InlineAsm>(I.getCalledValue()))
1789     visitInlineAsm(&I);
1790   else
1791     LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1792
1793   // If the value of the invoke is used outside of its defining block, make it
1794   // available as a virtual register.
1795   if (!I.use_empty()) {
1796     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1797     if (VMI != FuncInfo.ValueMap.end())
1798       CopyValueToVirtualRegister(&I, VMI->second);
1799   }
1800
1801   // Update successor info
1802   CurMBB->addSuccessor(Return);
1803   CurMBB->addSuccessor(LandingPad);
1804
1805   // Drop into normal successor.
1806   DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1807                           DAG.getBasicBlock(Return)));
1808 }
1809
1810 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1811 }
1812
1813 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1814 /// small case ranges).
1815 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1816                                                   CaseRecVector& WorkList,
1817                                                   Value* SV,
1818                                                   MachineBasicBlock* Default) {
1819   Case& BackCase  = *(CR.Range.second-1);
1820   
1821   // Size is the number of Cases represented by this range.
1822   unsigned Size = CR.Range.second - CR.Range.first;
1823   if (Size > 3)
1824     return false;  
1825   
1826   // Get the MachineFunction which holds the current MBB.  This is used when
1827   // inserting any additional MBBs necessary to represent the switch.
1828   MachineFunction *CurMF = CurMBB->getParent();  
1829
1830   // Figure out which block is immediately after the current one.
1831   MachineBasicBlock *NextBlock = 0;
1832   MachineFunction::iterator BBI = CR.CaseBB;
1833
1834   if (++BBI != CurMBB->getParent()->end())
1835     NextBlock = BBI;
1836
1837   // TODO: If any two of the cases has the same destination, and if one value
1838   // is the same as the other, but has one bit unset that the other has set,
1839   // use bit manipulation to do two compares at once.  For example:
1840   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1841     
1842   // Rearrange the case blocks so that the last one falls through if possible.
1843   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1844     // The last case block won't fall through into 'NextBlock' if we emit the
1845     // branches in this order.  See if rearranging a case value would help.
1846     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1847       if (I->BB == NextBlock) {
1848         std::swap(*I, BackCase);
1849         break;
1850       }
1851     }
1852   }
1853   
1854   // Create a CaseBlock record representing a conditional branch to
1855   // the Case's target mbb if the value being switched on SV is equal
1856   // to C.
1857   MachineBasicBlock *CurBlock = CR.CaseBB;
1858   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1859     MachineBasicBlock *FallThrough;
1860     if (I != E-1) {
1861       FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1862       CurMF->getBasicBlockList().insert(BBI, FallThrough);
1863     } else {
1864       // If the last case doesn't match, go to the default block.
1865       FallThrough = Default;
1866     }
1867
1868     Value *RHS, *LHS, *MHS;
1869     ISD::CondCode CC;
1870     if (I->High == I->Low) {
1871       // This is just small small case range :) containing exactly 1 case
1872       CC = ISD::SETEQ;
1873       LHS = SV; RHS = I->High; MHS = NULL;
1874     } else {
1875       CC = ISD::SETLE;
1876       LHS = I->Low; MHS = SV; RHS = I->High;
1877     }
1878     SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1879                                    I->BB, FallThrough, CurBlock);
1880     
1881     // If emitting the first comparison, just call visitSwitchCase to emit the
1882     // code into the current block.  Otherwise, push the CaseBlock onto the
1883     // vector to be later processed by SDISel, and insert the node's MBB
1884     // before the next MBB.
1885     if (CurBlock == CurMBB)
1886       visitSwitchCase(CB);
1887     else
1888       SwitchCases.push_back(CB);
1889     
1890     CurBlock = FallThrough;
1891   }
1892
1893   return true;
1894 }
1895
1896 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1897   return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1898           TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1899 }
1900   
1901 /// handleJTSwitchCase - Emit jumptable for current switch case range
1902 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1903                                               CaseRecVector& WorkList,
1904                                               Value* SV,
1905                                               MachineBasicBlock* Default) {
1906   Case& FrontCase = *CR.Range.first;
1907   Case& BackCase  = *(CR.Range.second-1);
1908
1909   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1910   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
1911
1912   uint64_t TSize = 0;
1913   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1914        I!=E; ++I)
1915     TSize += I->size();
1916
1917   if (!areJTsAllowed(TLI) || TSize <= 3)
1918     return false;
1919   
1920   double Density = (double)TSize / (double)((Last - First) + 1ULL);  
1921   if (Density < 0.4)
1922     return false;
1923
1924   DOUT << "Lowering jump table\n"
1925        << "First entry: " << First << ". Last entry: " << Last << "\n"
1926        << "Size: " << TSize << ". Density: " << Density << "\n\n";
1927
1928   // Get the MachineFunction which holds the current MBB.  This is used when
1929   // inserting any additional MBBs necessary to represent the switch.
1930   MachineFunction *CurMF = CurMBB->getParent();
1931
1932   // Figure out which block is immediately after the current one.
1933   MachineBasicBlock *NextBlock = 0;
1934   MachineFunction::iterator BBI = CR.CaseBB;
1935
1936   if (++BBI != CurMBB->getParent()->end())
1937     NextBlock = BBI;
1938
1939   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1940
1941   // Create a new basic block to hold the code for loading the address
1942   // of the jump table, and jumping to it.  Update successor information;
1943   // we will either branch to the default case for the switch, or the jump
1944   // table.
1945   MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1946   CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1947   CR.CaseBB->addSuccessor(Default);
1948   CR.CaseBB->addSuccessor(JumpTableBB);
1949                 
1950   // Build a vector of destination BBs, corresponding to each target
1951   // of the jump table. If the value of the jump table slot corresponds to
1952   // a case statement, push the case's BB onto the vector, otherwise, push
1953   // the default BB.
1954   std::vector<MachineBasicBlock*> DestBBs;
1955   int64_t TEI = First;
1956   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1957     int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1958     int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1959     
1960     if ((Low <= TEI) && (TEI <= High)) {
1961       DestBBs.push_back(I->BB);
1962       if (TEI==High)
1963         ++I;
1964     } else {
1965       DestBBs.push_back(Default);
1966     }
1967   }
1968   
1969   // Update successor info. Add one edge to each unique successor.
1970   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());  
1971   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 
1972          E = DestBBs.end(); I != E; ++I) {
1973     if (!SuccsHandled[(*I)->getNumber()]) {
1974       SuccsHandled[(*I)->getNumber()] = true;
1975       JumpTableBB->addSuccessor(*I);
1976     }
1977   }
1978       
1979   // Create a jump table index for this jump table, or return an existing
1980   // one.
1981   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1982   
1983   // Set the jump table information so that we can codegen it as a second
1984   // MachineBasicBlock
1985   SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1986   SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1987                                         (CR.CaseBB == CurMBB));
1988   if (CR.CaseBB == CurMBB)
1989     visitJumpTableHeader(JT, JTH);
1990         
1991   JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1992
1993   return true;
1994 }
1995
1996 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1997 /// 2 subtrees.
1998 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1999                                                    CaseRecVector& WorkList,
2000                                                    Value* SV,
2001                                                    MachineBasicBlock* Default) {
2002   // Get the MachineFunction which holds the current MBB.  This is used when
2003   // inserting any additional MBBs necessary to represent the switch.
2004   MachineFunction *CurMF = CurMBB->getParent();  
2005
2006   // Figure out which block is immediately after the current one.
2007   MachineBasicBlock *NextBlock = 0;
2008   MachineFunction::iterator BBI = CR.CaseBB;
2009
2010   if (++BBI != CurMBB->getParent()->end())
2011     NextBlock = BBI;
2012
2013   Case& FrontCase = *CR.Range.first;
2014   Case& BackCase  = *(CR.Range.second-1);
2015   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2016
2017   // Size is the number of Cases represented by this range.
2018   unsigned Size = CR.Range.second - CR.Range.first;
2019
2020   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2021   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
2022   double FMetric = 0;
2023   CaseItr Pivot = CR.Range.first + Size/2;
2024
2025   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2026   // (heuristically) allow us to emit JumpTable's later.
2027   uint64_t TSize = 0;
2028   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2029        I!=E; ++I)
2030     TSize += I->size();
2031
2032   uint64_t LSize = FrontCase.size();
2033   uint64_t RSize = TSize-LSize;
2034   DOUT << "Selecting best pivot: \n"
2035        << "First: " << First << ", Last: " << Last <<"\n"
2036        << "LSize: " << LSize << ", RSize: " << RSize << "\n";
2037   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2038        J!=E; ++I, ++J) {
2039     int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2040     int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
2041     assert((RBegin-LEnd>=1) && "Invalid case distance");
2042     double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2043     double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
2044     double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
2045     // Should always split in some non-trivial place
2046     DOUT <<"=>Step\n"
2047          << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2048          << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2049          << "Metric: " << Metric << "\n"; 
2050     if (FMetric < Metric) {
2051       Pivot = J;
2052       FMetric = Metric;
2053       DOUT << "Current metric set to: " << FMetric << "\n";
2054     }
2055
2056     LSize += J->size();
2057     RSize -= J->size();
2058   }
2059   if (areJTsAllowed(TLI)) {
2060     // If our case is dense we *really* should handle it earlier!
2061     assert((FMetric > 0) && "Should handle dense range earlier!");
2062   } else {
2063     Pivot = CR.Range.first + Size/2;
2064   }
2065   
2066   CaseRange LHSR(CR.Range.first, Pivot);
2067   CaseRange RHSR(Pivot, CR.Range.second);
2068   Constant *C = Pivot->Low;
2069   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2070       
2071   // We know that we branch to the LHS if the Value being switched on is
2072   // less than the Pivot value, C.  We use this to optimize our binary 
2073   // tree a bit, by recognizing that if SV is greater than or equal to the
2074   // LHS's Case Value, and that Case Value is exactly one less than the 
2075   // Pivot's Value, then we can branch directly to the LHS's Target,
2076   // rather than creating a leaf node for it.
2077   if ((LHSR.second - LHSR.first) == 1 &&
2078       LHSR.first->High == CR.GE &&
2079       cast<ConstantInt>(C)->getSExtValue() ==
2080       (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2081     TrueBB = LHSR.first->BB;
2082   } else {
2083     TrueBB = new MachineBasicBlock(LLVMBB);
2084     CurMF->getBasicBlockList().insert(BBI, TrueBB);
2085     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2086   }
2087   
2088   // Similar to the optimization above, if the Value being switched on is
2089   // known to be less than the Constant CR.LT, and the current Case Value
2090   // is CR.LT - 1, then we can branch directly to the target block for
2091   // the current Case Value, rather than emitting a RHS leaf node for it.
2092   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2093       cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2094       (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2095     FalseBB = RHSR.first->BB;
2096   } else {
2097     FalseBB = new MachineBasicBlock(LLVMBB);
2098     CurMF->getBasicBlockList().insert(BBI, FalseBB);
2099     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2100   }
2101
2102   // Create a CaseBlock record representing a conditional branch to
2103   // the LHS node if the value being switched on SV is less than C. 
2104   // Otherwise, branch to LHS.
2105   SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2106                                  TrueBB, FalseBB, CR.CaseBB);
2107
2108   if (CR.CaseBB == CurMBB)
2109     visitSwitchCase(CB);
2110   else
2111     SwitchCases.push_back(CB);
2112
2113   return true;
2114 }
2115
2116 /// handleBitTestsSwitchCase - if current case range has few destination and
2117 /// range span less, than machine word bitwidth, encode case range into series
2118 /// of masks and emit bit tests with these masks.
2119 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2120                                                     CaseRecVector& WorkList,
2121                                                     Value* SV,
2122                                                     MachineBasicBlock* Default){
2123   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
2124
2125   Case& FrontCase = *CR.Range.first;
2126   Case& BackCase  = *(CR.Range.second-1);
2127
2128   // Get the MachineFunction which holds the current MBB.  This is used when
2129   // inserting any additional MBBs necessary to represent the switch.
2130   MachineFunction *CurMF = CurMBB->getParent();  
2131
2132   unsigned numCmps = 0;
2133   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2134        I!=E; ++I) {
2135     // Single case counts one, case range - two.
2136     if (I->Low == I->High)
2137       numCmps +=1;
2138     else
2139       numCmps +=2;
2140   }
2141     
2142   // Count unique destinations
2143   SmallSet<MachineBasicBlock*, 4> Dests;
2144   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2145     Dests.insert(I->BB);
2146     if (Dests.size() > 3)
2147       // Don't bother the code below, if there are too much unique destinations
2148       return false;
2149   }
2150   DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2151        << "Total number of comparisons: " << numCmps << "\n";
2152   
2153   // Compute span of values.
2154   Constant* minValue = FrontCase.Low;
2155   Constant* maxValue = BackCase.High;
2156   uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2157                    cast<ConstantInt>(minValue)->getSExtValue();
2158   DOUT << "Compare range: " << range << "\n"
2159        << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2160        << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2161   
2162   if (range>=IntPtrBits ||
2163       (!(Dests.size() == 1 && numCmps >= 3) &&
2164        !(Dests.size() == 2 && numCmps >= 5) &&
2165        !(Dests.size() >= 3 && numCmps >= 6)))
2166     return false;
2167   
2168   DOUT << "Emitting bit tests\n";
2169   int64_t lowBound = 0;
2170     
2171   // Optimize the case where all the case values fit in a
2172   // word without having to subtract minValue. In this case,
2173   // we can optimize away the subtraction.
2174   if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2175       cast<ConstantInt>(maxValue)->getSExtValue() <  IntPtrBits) {
2176     range = cast<ConstantInt>(maxValue)->getSExtValue();
2177   } else {
2178     lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2179   }
2180     
2181   CaseBitsVector CasesBits;
2182   unsigned i, count = 0;
2183
2184   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2185     MachineBasicBlock* Dest = I->BB;
2186     for (i = 0; i < count; ++i)
2187       if (Dest == CasesBits[i].BB)
2188         break;
2189     
2190     if (i == count) {
2191       assert((count < 3) && "Too much destinations to test!");
2192       CasesBits.push_back(CaseBits(0, Dest, 0));
2193       count++;
2194     }
2195     
2196     uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2197     uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2198     
2199     for (uint64_t j = lo; j <= hi; j++) {
2200       CasesBits[i].Mask |=  1ULL << j;
2201       CasesBits[i].Bits++;
2202     }
2203       
2204   }
2205   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2206   
2207   SelectionDAGISel::BitTestInfo BTC;
2208
2209   // Figure out which block is immediately after the current one.
2210   MachineFunction::iterator BBI = CR.CaseBB;
2211   ++BBI;
2212
2213   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2214
2215   DOUT << "Cases:\n";
2216   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2217     DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2218          << ", BB: " << CasesBits[i].BB << "\n";
2219
2220     MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2221     CurMF->getBasicBlockList().insert(BBI, CaseBB);
2222     BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2223                                                 CaseBB,
2224                                                 CasesBits[i].BB));
2225   }
2226   
2227   SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2228                                      -1U, (CR.CaseBB == CurMBB),
2229                                      CR.CaseBB, Default, BTC);
2230
2231   if (CR.CaseBB == CurMBB)
2232     visitBitTestHeader(BTB);
2233   
2234   BitTestCases.push_back(BTB);
2235
2236   return true;
2237 }
2238
2239
2240 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2241 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2242                                           const SwitchInst& SI) {
2243   unsigned numCmps = 0;
2244
2245   // Start with "simple" cases
2246   for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2247     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2248     Cases.push_back(Case(SI.getSuccessorValue(i),
2249                          SI.getSuccessorValue(i),
2250                          SMBB));
2251   }
2252   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2253
2254   // Merge case into clusters
2255   if (Cases.size()>=2)
2256     // Must recompute end() each iteration because it may be
2257     // invalidated by erase if we hold on to it
2258     for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2259       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2260       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2261       MachineBasicBlock* nextBB = J->BB;
2262       MachineBasicBlock* currentBB = I->BB;
2263
2264       // If the two neighboring cases go to the same destination, merge them
2265       // into a single case.
2266       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2267         I->High = J->High;
2268         J = Cases.erase(J);
2269       } else {
2270         I = J++;
2271       }
2272     }
2273
2274   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2275     if (I->Low != I->High)
2276       // A range counts double, since it requires two compares.
2277       ++numCmps;
2278   }
2279
2280   return numCmps;
2281 }
2282
2283 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {  
2284   // Figure out which block is immediately after the current one.
2285   MachineBasicBlock *NextBlock = 0;
2286   MachineFunction::iterator BBI = CurMBB;
2287
2288   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2289
2290   // If there is only the default destination, branch to it if it is not the
2291   // next basic block.  Otherwise, just fall through.
2292   if (SI.getNumOperands() == 2) {
2293     // Update machine-CFG edges.
2294
2295     // If this is not a fall-through branch, emit the branch.
2296     CurMBB->addSuccessor(Default);
2297     if (Default != NextBlock)
2298       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2299                               DAG.getBasicBlock(Default)));
2300     
2301     return;
2302   }
2303   
2304   // If there are any non-default case statements, create a vector of Cases
2305   // representing each one, and sort the vector so that we can efficiently
2306   // create a binary search tree from them.
2307   CaseVector Cases;
2308   unsigned numCmps = Clusterify(Cases, SI);
2309   DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2310        << ". Total compares: " << numCmps << "\n";
2311
2312   // Get the Value to be switched on and default basic blocks, which will be
2313   // inserted into CaseBlock records, representing basic blocks in the binary
2314   // search tree.
2315   Value *SV = SI.getOperand(0);
2316
2317   // Push the initial CaseRec onto the worklist
2318   CaseRecVector WorkList;
2319   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2320
2321   while (!WorkList.empty()) {
2322     // Grab a record representing a case range to process off the worklist
2323     CaseRec CR = WorkList.back();
2324     WorkList.pop_back();
2325
2326     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2327       continue;
2328     
2329     // If the range has few cases (two or less) emit a series of specific
2330     // tests.
2331     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2332       continue;
2333     
2334     // If the switch has more than 5 blocks, and at least 40% dense, and the 
2335     // target supports indirect branches, then emit a jump table rather than 
2336     // lowering the switch to a binary tree of conditional branches.
2337     if (handleJTSwitchCase(CR, WorkList, SV, Default))
2338       continue;
2339           
2340     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2341     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2342     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2343   }
2344 }
2345
2346
2347 void SelectionDAGLowering::visitSub(User &I) {
2348   // -0.0 - X --> fneg
2349   const Type *Ty = I.getType();
2350   if (isa<VectorType>(Ty)) {
2351     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2352       const VectorType *DestTy = cast<VectorType>(I.getType());
2353       const Type *ElTy = DestTy->getElementType();
2354       if (ElTy->isFloatingPoint()) {
2355         unsigned VL = DestTy->getNumElements();
2356         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2357         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2358         if (CV == CNZ) {
2359           SDOperand Op2 = getValue(I.getOperand(1));
2360           setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2361           return;
2362         }
2363       }
2364     }
2365   }
2366   if (Ty->isFloatingPoint()) {
2367     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2368       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2369         SDOperand Op2 = getValue(I.getOperand(1));
2370         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2371         return;
2372       }
2373   }
2374
2375   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2376 }
2377
2378 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2379   SDOperand Op1 = getValue(I.getOperand(0));
2380   SDOperand Op2 = getValue(I.getOperand(1));
2381   
2382   setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2383 }
2384
2385 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2386   SDOperand Op1 = getValue(I.getOperand(0));
2387   SDOperand Op2 = getValue(I.getOperand(1));
2388   
2389   if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2390     Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2391   else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2392     Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2393   
2394   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2395 }
2396
2397 void SelectionDAGLowering::visitICmp(User &I) {
2398   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2399   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2400     predicate = IC->getPredicate();
2401   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2402     predicate = ICmpInst::Predicate(IC->getPredicate());
2403   SDOperand Op1 = getValue(I.getOperand(0));
2404   SDOperand Op2 = getValue(I.getOperand(1));
2405   ISD::CondCode Opcode;
2406   switch (predicate) {
2407     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2408     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2409     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2410     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2411     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2412     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2413     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2414     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2415     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2416     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2417     default:
2418       assert(!"Invalid ICmp predicate value");
2419       Opcode = ISD::SETEQ;
2420       break;
2421   }
2422   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2423 }
2424
2425 void SelectionDAGLowering::visitFCmp(User &I) {
2426   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2427   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2428     predicate = FC->getPredicate();
2429   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2430     predicate = FCmpInst::Predicate(FC->getPredicate());
2431   SDOperand Op1 = getValue(I.getOperand(0));
2432   SDOperand Op2 = getValue(I.getOperand(1));
2433   ISD::CondCode Condition, FOC, FPC;
2434   switch (predicate) {
2435     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2436     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2437     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2438     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2439     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2440     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2441     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2442     case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2443     case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2444     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2445     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2446     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2447     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2448     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2449     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2450     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2451     default:
2452       assert(!"Invalid FCmp predicate value");
2453       FOC = FPC = ISD::SETFALSE;
2454       break;
2455   }
2456   if (FiniteOnlyFPMath())
2457     Condition = FOC;
2458   else 
2459     Condition = FPC;
2460   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2461 }
2462
2463 void SelectionDAGLowering::visitVICmp(User &I) {
2464   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2465   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2466     predicate = IC->getPredicate();
2467   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2468     predicate = ICmpInst::Predicate(IC->getPredicate());
2469   SDOperand Op1 = getValue(I.getOperand(0));
2470   SDOperand Op2 = getValue(I.getOperand(1));
2471   ISD::CondCode Opcode;
2472   switch (predicate) {
2473     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2474     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2475     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2476     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2477     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2478     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2479     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2480     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2481     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2482     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2483     default:
2484       assert(!"Invalid ICmp predicate value");
2485       Opcode = ISD::SETEQ;
2486       break;
2487   }
2488   setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2489 }
2490
2491 void SelectionDAGLowering::visitVFCmp(User &I) {
2492   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2493   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2494     predicate = FC->getPredicate();
2495   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2496     predicate = FCmpInst::Predicate(FC->getPredicate());
2497   SDOperand Op1 = getValue(I.getOperand(0));
2498   SDOperand Op2 = getValue(I.getOperand(1));
2499   ISD::CondCode Condition, FOC, FPC;
2500   switch (predicate) {
2501     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2502     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2503     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2504     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2505     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2506     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2507     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2508     case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2509     case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2510     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2511     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2512     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2513     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2514     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2515     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2516     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2517     default:
2518       assert(!"Invalid VFCmp predicate value");
2519       FOC = FPC = ISD::SETFALSE;
2520       break;
2521   }
2522   if (FiniteOnlyFPMath())
2523     Condition = FOC;
2524   else 
2525     Condition = FPC;
2526     
2527   MVT DestVT = TLI.getValueType(I.getType());
2528     
2529   setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2530 }
2531
2532 void SelectionDAGLowering::visitSelect(User &I) {
2533   SDOperand Cond     = getValue(I.getOperand(0));
2534   SDOperand TrueVal  = getValue(I.getOperand(1));
2535   SDOperand FalseVal = getValue(I.getOperand(2));
2536   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2537                            TrueVal, FalseVal));
2538 }
2539
2540
2541 void SelectionDAGLowering::visitTrunc(User &I) {
2542   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2543   SDOperand N = getValue(I.getOperand(0));
2544   MVT DestVT = TLI.getValueType(I.getType());
2545   setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2546 }
2547
2548 void SelectionDAGLowering::visitZExt(User &I) {
2549   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2550   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2551   SDOperand N = getValue(I.getOperand(0));
2552   MVT DestVT = TLI.getValueType(I.getType());
2553   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2554 }
2555
2556 void SelectionDAGLowering::visitSExt(User &I) {
2557   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2558   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2559   SDOperand N = getValue(I.getOperand(0));
2560   MVT DestVT = TLI.getValueType(I.getType());
2561   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2562 }
2563
2564 void SelectionDAGLowering::visitFPTrunc(User &I) {
2565   // FPTrunc is never a no-op cast, no need to check
2566   SDOperand N = getValue(I.getOperand(0));
2567   MVT DestVT = TLI.getValueType(I.getType());
2568   setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2569 }
2570
2571 void SelectionDAGLowering::visitFPExt(User &I){ 
2572   // FPTrunc is never a no-op cast, no need to check
2573   SDOperand N = getValue(I.getOperand(0));
2574   MVT DestVT = TLI.getValueType(I.getType());
2575   setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2576 }
2577
2578 void SelectionDAGLowering::visitFPToUI(User &I) { 
2579   // FPToUI is never a no-op cast, no need to check
2580   SDOperand N = getValue(I.getOperand(0));
2581   MVT DestVT = TLI.getValueType(I.getType());
2582   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2583 }
2584
2585 void SelectionDAGLowering::visitFPToSI(User &I) {
2586   // FPToSI is never a no-op cast, no need to check
2587   SDOperand N = getValue(I.getOperand(0));
2588   MVT DestVT = TLI.getValueType(I.getType());
2589   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2590 }
2591
2592 void SelectionDAGLowering::visitUIToFP(User &I) { 
2593   // UIToFP is never a no-op cast, no need to check
2594   SDOperand N = getValue(I.getOperand(0));
2595   MVT DestVT = TLI.getValueType(I.getType());
2596   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2597 }
2598
2599 void SelectionDAGLowering::visitSIToFP(User &I){ 
2600   // UIToFP is never a no-op cast, no need to check
2601   SDOperand N = getValue(I.getOperand(0));
2602   MVT DestVT = TLI.getValueType(I.getType());
2603   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2604 }
2605
2606 void SelectionDAGLowering::visitPtrToInt(User &I) {
2607   // What to do depends on the size of the integer and the size of the pointer.
2608   // We can either truncate, zero extend, or no-op, accordingly.
2609   SDOperand N = getValue(I.getOperand(0));
2610   MVT SrcVT = N.getValueType();
2611   MVT DestVT = TLI.getValueType(I.getType());
2612   SDOperand Result;
2613   if (DestVT.bitsLT(SrcVT))
2614     Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2615   else 
2616     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2617     Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2618   setValue(&I, Result);
2619 }
2620
2621 void SelectionDAGLowering::visitIntToPtr(User &I) {
2622   // What to do depends on the size of the integer and the size of the pointer.
2623   // We can either truncate, zero extend, or no-op, accordingly.
2624   SDOperand N = getValue(I.getOperand(0));
2625   MVT SrcVT = N.getValueType();
2626   MVT DestVT = TLI.getValueType(I.getType());
2627   if (DestVT.bitsLT(SrcVT))
2628     setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2629   else 
2630     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2631     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2632 }
2633
2634 void SelectionDAGLowering::visitBitCast(User &I) { 
2635   SDOperand N = getValue(I.getOperand(0));
2636   MVT DestVT = TLI.getValueType(I.getType());
2637
2638   // BitCast assures us that source and destination are the same size so this 
2639   // is either a BIT_CONVERT or a no-op.
2640   if (DestVT != N.getValueType())
2641     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2642   else
2643     setValue(&I, N); // noop cast.
2644 }
2645
2646 void SelectionDAGLowering::visitInsertElement(User &I) {
2647   SDOperand InVec = getValue(I.getOperand(0));
2648   SDOperand InVal = getValue(I.getOperand(1));
2649   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2650                                 getValue(I.getOperand(2)));
2651
2652   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2653                            TLI.getValueType(I.getType()),
2654                            InVec, InVal, InIdx));
2655 }
2656
2657 void SelectionDAGLowering::visitExtractElement(User &I) {
2658   SDOperand InVec = getValue(I.getOperand(0));
2659   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2660                                 getValue(I.getOperand(1)));
2661   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2662                            TLI.getValueType(I.getType()), InVec, InIdx));
2663 }
2664
2665 void SelectionDAGLowering::visitShuffleVector(User &I) {
2666   SDOperand V1   = getValue(I.getOperand(0));
2667   SDOperand V2   = getValue(I.getOperand(1));
2668   SDOperand Mask = getValue(I.getOperand(2));
2669
2670   setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2671                            TLI.getValueType(I.getType()),
2672                            V1, V2, Mask));
2673 }
2674
2675 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2676   const Value *Op0 = I.getOperand(0);
2677   const Value *Op1 = I.getOperand(1);
2678   const Type *AggTy = I.getType();
2679   const Type *ValTy = Op1->getType();
2680   bool IntoUndef = isa<UndefValue>(Op0);
2681   bool FromUndef = isa<UndefValue>(Op1);
2682
2683   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2684                                             I.idx_begin(), I.idx_end());
2685
2686   SmallVector<MVT, 4> AggValueVTs;
2687   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2688   SmallVector<MVT, 4> ValValueVTs;
2689   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2690
2691   unsigned NumAggValues = AggValueVTs.size();
2692   unsigned NumValValues = ValValueVTs.size();
2693   SmallVector<SDOperand, 4> Values(NumAggValues);
2694
2695   SDOperand Agg = getValue(Op0);
2696   SDOperand Val = getValue(Op1);
2697   unsigned i = 0;
2698   // Copy the beginning value(s) from the original aggregate.
2699   for (; i != LinearIndex; ++i)
2700     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2701                 SDOperand(Agg.Val, Agg.ResNo + i);
2702   // Copy values from the inserted value(s).
2703   for (; i != LinearIndex + NumValValues; ++i)
2704     Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2705                 SDOperand(Val.Val, Val.ResNo + i - LinearIndex);
2706   // Copy remaining value(s) from the original aggregate.
2707   for (; i != NumAggValues; ++i)
2708     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2709                 SDOperand(Agg.Val, Agg.ResNo + i);
2710
2711   setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2712                            DAG.getVTList(&AggValueVTs[0], NumAggValues),
2713                            &Values[0], NumAggValues));
2714 }
2715
2716 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2717   const Value *Op0 = I.getOperand(0);
2718   const Type *AggTy = Op0->getType();
2719   const Type *ValTy = I.getType();
2720   bool OutOfUndef = isa<UndefValue>(Op0);
2721
2722   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2723                                             I.idx_begin(), I.idx_end());
2724
2725   SmallVector<MVT, 4> ValValueVTs;
2726   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2727
2728   unsigned NumValValues = ValValueVTs.size();
2729   SmallVector<SDOperand, 4> Values(NumValValues);
2730
2731   SDOperand Agg = getValue(Op0);
2732   // Copy out the selected value(s).
2733   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2734     Values[i - LinearIndex] =
2735       OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(i)) :
2736                    SDOperand(Agg.Val, Agg.ResNo + i - LinearIndex);
2737
2738   setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2739                            DAG.getVTList(&ValValueVTs[0], NumValValues),
2740                            &Values[0], NumValValues));
2741 }
2742
2743
2744 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2745   SDOperand N = getValue(I.getOperand(0));
2746   const Type *Ty = I.getOperand(0)->getType();
2747
2748   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2749        OI != E; ++OI) {
2750     Value *Idx = *OI;
2751     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2752       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2753       if (Field) {
2754         // N = N + Offset
2755         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2756         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2757                         DAG.getIntPtrConstant(Offset));
2758       }
2759       Ty = StTy->getElementType(Field);
2760     } else {
2761       Ty = cast<SequentialType>(Ty)->getElementType();
2762
2763       // If this is a constant subscript, handle it quickly.
2764       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2765         if (CI->getZExtValue() == 0) continue;
2766         uint64_t Offs = 
2767             TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2768         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2769                         DAG.getIntPtrConstant(Offs));
2770         continue;
2771       }
2772       
2773       // N = N + Idx * ElementSize;
2774       uint64_t ElementSize = TD->getABITypeSize(Ty);
2775       SDOperand IdxN = getValue(Idx);
2776
2777       // If the index is smaller or larger than intptr_t, truncate or extend
2778       // it.
2779       if (IdxN.getValueType().bitsLT(N.getValueType())) {
2780         IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2781       } else if (IdxN.getValueType().bitsGT(N.getValueType()))
2782         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2783
2784       // If this is a multiply by a power of two, turn it into a shl
2785       // immediately.  This is a very common case.
2786       if (isPowerOf2_64(ElementSize)) {
2787         unsigned Amt = Log2_64(ElementSize);
2788         IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2789                            DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2790         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2791         continue;
2792       }
2793       
2794       SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2795       IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2796       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2797     }
2798   }
2799   setValue(&I, N);
2800 }
2801
2802 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2803   // If this is a fixed sized alloca in the entry block of the function,
2804   // allocate it statically on the stack.
2805   if (FuncInfo.StaticAllocaMap.count(&I))
2806     return;   // getValue will auto-populate this.
2807
2808   const Type *Ty = I.getAllocatedType();
2809   uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2810   unsigned Align =
2811     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2812              I.getAlignment());
2813
2814   SDOperand AllocSize = getValue(I.getArraySize());
2815   MVT IntPtr = TLI.getPointerTy();
2816   if (IntPtr.bitsLT(AllocSize.getValueType()))
2817     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2818   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2819     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2820
2821   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2822                           DAG.getIntPtrConstant(TySize));
2823
2824   // Handle alignment.  If the requested alignment is less than or equal to
2825   // the stack alignment, ignore it.  If the size is greater than or equal to
2826   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2827   unsigned StackAlign =
2828     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2829   if (Align <= StackAlign)
2830     Align = 0;
2831
2832   // Round the size of the allocation up to the stack alignment size
2833   // by add SA-1 to the size.
2834   AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2835                           DAG.getIntPtrConstant(StackAlign-1));
2836   // Mask out the low bits for alignment purposes.
2837   AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2838                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2839
2840   SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2841   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2842                                                     MVT::Other);
2843   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2844   setValue(&I, DSA);
2845   DAG.setRoot(DSA.getValue(1));
2846
2847   // Inform the Frame Information that we have just allocated a variable-sized
2848   // object.
2849   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2850 }
2851
2852 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2853   const Value *SV = I.getOperand(0);
2854   SDOperand Ptr = getValue(SV);
2855
2856   const Type *Ty = I.getType();
2857   bool isVolatile = I.isVolatile();
2858   unsigned Alignment = I.getAlignment();
2859
2860   SmallVector<MVT, 4> ValueVTs;
2861   SmallVector<uint64_t, 4> Offsets;
2862   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2863   unsigned NumValues = ValueVTs.size();
2864   if (NumValues == 0)
2865     return;
2866
2867   SDOperand Root;
2868   if (I.isVolatile())
2869     Root = getRoot();
2870   else {
2871     // Do not serialize non-volatile loads against each other.
2872     Root = DAG.getRoot();
2873   }
2874
2875   SmallVector<SDOperand, 4> Values(NumValues);
2876   SmallVector<SDOperand, 4> Chains(NumValues);
2877   MVT PtrVT = Ptr.getValueType();
2878   for (unsigned i = 0; i != NumValues; ++i) {
2879     SDOperand L = DAG.getLoad(ValueVTs[i], Root,
2880                               DAG.getNode(ISD::ADD, PtrVT, Ptr,
2881                                           DAG.getConstant(Offsets[i], PtrVT)),
2882                               SV, Offsets[i],
2883                               isVolatile, Alignment);
2884     Values[i] = L;
2885     Chains[i] = L.getValue(1);
2886   }
2887   
2888   SDOperand Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2889                                 &Chains[0], NumValues);
2890   if (isVolatile)
2891     DAG.setRoot(Chain);
2892   else
2893     PendingLoads.push_back(Chain);
2894
2895   setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2896                            DAG.getVTList(&ValueVTs[0], NumValues),
2897                            &Values[0], NumValues));
2898 }
2899
2900
2901 void SelectionDAGLowering::visitStore(StoreInst &I) {
2902   Value *SrcV = I.getOperand(0);
2903   SDOperand Src = getValue(SrcV);
2904   Value *PtrV = I.getOperand(1);
2905   SDOperand Ptr = getValue(PtrV);
2906
2907   SmallVector<MVT, 4> ValueVTs;
2908   SmallVector<uint64_t, 4> Offsets;
2909   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2910   unsigned NumValues = ValueVTs.size();
2911   if (NumValues == 0)
2912     return;
2913
2914   SDOperand Root = getRoot();
2915   SmallVector<SDOperand, 4> Chains(NumValues);
2916   MVT PtrVT = Ptr.getValueType();
2917   bool isVolatile = I.isVolatile();
2918   unsigned Alignment = I.getAlignment();
2919   for (unsigned i = 0; i != NumValues; ++i)
2920     Chains[i] = DAG.getStore(Root, SDOperand(Src.Val, Src.ResNo + i),
2921                              DAG.getNode(ISD::ADD, PtrVT, Ptr,
2922                                          DAG.getConstant(Offsets[i], PtrVT)),
2923                              PtrV, Offsets[i],
2924                              isVolatile, Alignment);
2925
2926   DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2927 }
2928
2929 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2930 /// node.
2931 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
2932                                                 unsigned Intrinsic) {
2933   bool HasChain = !I.doesNotAccessMemory();
2934   bool OnlyLoad = HasChain && I.onlyReadsMemory();
2935
2936   // Build the operand list.
2937   SmallVector<SDOperand, 8> Ops;
2938   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2939     if (OnlyLoad) {
2940       // We don't need to serialize loads against other loads.
2941       Ops.push_back(DAG.getRoot());
2942     } else { 
2943       Ops.push_back(getRoot());
2944     }
2945   }
2946   
2947   // Add the intrinsic ID as an integer operand.
2948   Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2949
2950   // Add all operands of the call to the operand list.
2951   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2952     SDOperand Op = getValue(I.getOperand(i));
2953     assert(TLI.isTypeLegal(Op.getValueType()) &&
2954            "Intrinsic uses a non-legal type?");
2955     Ops.push_back(Op);
2956   }
2957
2958   std::vector<MVT> VTs;
2959   if (I.getType() != Type::VoidTy) {
2960     MVT VT = TLI.getValueType(I.getType());
2961     if (VT.isVector()) {
2962       const VectorType *DestTy = cast<VectorType>(I.getType());
2963       MVT EltVT = TLI.getValueType(DestTy->getElementType());
2964       
2965       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2966       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2967     }
2968     
2969     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2970     VTs.push_back(VT);
2971   }
2972   if (HasChain)
2973     VTs.push_back(MVT::Other);
2974
2975   const MVT *VTList = DAG.getNodeValueTypes(VTs);
2976
2977   // Create the node.
2978   SDOperand Result;
2979   if (!HasChain)
2980     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2981                          &Ops[0], Ops.size());
2982   else if (I.getType() != Type::VoidTy)
2983     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2984                          &Ops[0], Ops.size());
2985   else
2986     Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2987                          &Ops[0], Ops.size());
2988
2989   if (HasChain) {
2990     SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2991     if (OnlyLoad)
2992       PendingLoads.push_back(Chain);
2993     else
2994       DAG.setRoot(Chain);
2995   }
2996   if (I.getType() != Type::VoidTy) {
2997     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2998       MVT VT = TLI.getValueType(PTy);
2999       Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
3000     } 
3001     setValue(&I, Result);
3002   }
3003 }
3004
3005 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3006 static GlobalVariable *ExtractTypeInfo (Value *V) {
3007   V = V->stripPointerCasts();
3008   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3009   assert ((GV || isa<ConstantPointerNull>(V)) &&
3010           "TypeInfo must be a global variable or NULL");
3011   return GV;
3012 }
3013
3014 /// addCatchInfo - Extract the personality and type infos from an eh.selector
3015 /// call, and add them to the specified machine basic block.
3016 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3017                          MachineBasicBlock *MBB) {
3018   // Inform the MachineModuleInfo of the personality for this landing pad.
3019   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3020   assert(CE->getOpcode() == Instruction::BitCast &&
3021          isa<Function>(CE->getOperand(0)) &&
3022          "Personality should be a function");
3023   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3024
3025   // Gather all the type infos for this landing pad and pass them along to
3026   // MachineModuleInfo.
3027   std::vector<GlobalVariable *> TyInfo;
3028   unsigned N = I.getNumOperands();
3029
3030   for (unsigned i = N - 1; i > 2; --i) {
3031     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3032       unsigned FilterLength = CI->getZExtValue();
3033       unsigned FirstCatch = i + FilterLength + !FilterLength;
3034       assert (FirstCatch <= N && "Invalid filter length");
3035
3036       if (FirstCatch < N) {
3037         TyInfo.reserve(N - FirstCatch);
3038         for (unsigned j = FirstCatch; j < N; ++j)
3039           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3040         MMI->addCatchTypeInfo(MBB, TyInfo);
3041         TyInfo.clear();
3042       }
3043
3044       if (!FilterLength) {
3045         // Cleanup.
3046         MMI->addCleanup(MBB);
3047       } else {
3048         // Filter.
3049         TyInfo.reserve(FilterLength - 1);
3050         for (unsigned j = i + 1; j < FirstCatch; ++j)
3051           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052         MMI->addFilterTypeInfo(MBB, TyInfo);
3053         TyInfo.clear();
3054       }
3055
3056       N = i;
3057     }
3058   }
3059
3060   if (N > 3) {
3061     TyInfo.reserve(N - 3);
3062     for (unsigned j = 3; j < N; ++j)
3063       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3064     MMI->addCatchTypeInfo(MBB, TyInfo);
3065   }
3066 }
3067
3068
3069 /// Inlined utility function to implement binary input atomic intrinsics for 
3070 // visitIntrinsicCall: I is a call instruction
3071 //                     Op is the associated NodeType for I
3072 const char *
3073 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3074   SDOperand Root = getRoot();   
3075   SDOperand O2 = getValue(I.getOperand(2));
3076   SDOperand L = DAG.getAtomic(Op, Root, 
3077                               getValue(I.getOperand(1)), 
3078                               O2, O2.getValueType());
3079   setValue(&I, L);
3080   DAG.setRoot(L.getValue(1));
3081   return 0;
3082 }
3083
3084 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3085 /// we want to emit this as a call to a named external function, return the name
3086 /// otherwise lower it and return null.
3087 const char *
3088 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3089   switch (Intrinsic) {
3090   default:
3091     // By default, turn this into a target intrinsic node.
3092     visitTargetIntrinsic(I, Intrinsic);
3093     return 0;
3094   case Intrinsic::vastart:  visitVAStart(I); return 0;
3095   case Intrinsic::vaend:    visitVAEnd(I); return 0;
3096   case Intrinsic::vacopy:   visitVACopy(I); return 0;
3097   case Intrinsic::returnaddress:
3098     setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3099                              getValue(I.getOperand(1))));
3100     return 0;
3101   case Intrinsic::frameaddress:
3102     setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3103                              getValue(I.getOperand(1))));
3104     return 0;
3105   case Intrinsic::setjmp:
3106     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3107     break;
3108   case Intrinsic::longjmp:
3109     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3110     break;
3111   case Intrinsic::memcpy_i32:
3112   case Intrinsic::memcpy_i64: {
3113     SDOperand Op1 = getValue(I.getOperand(1));
3114     SDOperand Op2 = getValue(I.getOperand(2));
3115     SDOperand Op3 = getValue(I.getOperand(3));
3116     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3117     DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3118                               I.getOperand(1), 0, I.getOperand(2), 0));
3119     return 0;
3120   }
3121   case Intrinsic::memset_i32:
3122   case Intrinsic::memset_i64: {
3123     SDOperand Op1 = getValue(I.getOperand(1));
3124     SDOperand Op2 = getValue(I.getOperand(2));
3125     SDOperand Op3 = getValue(I.getOperand(3));
3126     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3127     DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3128                               I.getOperand(1), 0));
3129     return 0;
3130   }
3131   case Intrinsic::memmove_i32:
3132   case Intrinsic::memmove_i64: {
3133     SDOperand Op1 = getValue(I.getOperand(1));
3134     SDOperand Op2 = getValue(I.getOperand(2));
3135     SDOperand Op3 = getValue(I.getOperand(3));
3136     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3137
3138     // If the source and destination are known to not be aliases, we can
3139     // lower memmove as memcpy.
3140     uint64_t Size = -1ULL;
3141     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3142       Size = C->getValue();
3143     if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3144         AliasAnalysis::NoAlias) {
3145       DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3146                                 I.getOperand(1), 0, I.getOperand(2), 0));
3147       return 0;
3148     }
3149
3150     DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3151                                I.getOperand(1), 0, I.getOperand(2), 0));
3152     return 0;
3153   }
3154   case Intrinsic::dbg_stoppoint: {
3155     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3156     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3157     if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3158       SDOperand Ops[5];
3159
3160       Ops[0] = getRoot();
3161       Ops[1] = getValue(SPI.getLineValue());
3162       Ops[2] = getValue(SPI.getColumnValue());
3163
3164       DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3165       assert(DD && "Not a debug information descriptor");
3166       CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
3167       
3168       Ops[3] = DAG.getString(CompileUnit->getFileName());
3169       Ops[4] = DAG.getString(CompileUnit->getDirectory());
3170       
3171       DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
3172     }
3173
3174     return 0;
3175   }
3176   case Intrinsic::dbg_region_start: {
3177     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3178     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3179     if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3180       unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3181       DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3182                               DAG.getConstant(LabelID, MVT::i32),
3183                               DAG.getConstant(0, MVT::i32)));
3184     }
3185
3186     return 0;
3187   }
3188   case Intrinsic::dbg_region_end: {
3189     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3190     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3191     if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3192       unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3193       DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3194                               DAG.getConstant(LabelID, MVT::i32),
3195                               DAG.getConstant(0, MVT::i32)));
3196     }
3197
3198     return 0;
3199   }
3200   case Intrinsic::dbg_func_start: {
3201     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3202     if (!MMI) return 0;
3203     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3204     Value *SP = FSI.getSubprogram();
3205     if (SP && MMI->Verify(SP)) {
3206       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3207       // what (most?) gdb expects.
3208       DebugInfoDesc *DD = MMI->getDescFor(SP);
3209       assert(DD && "Not a debug information descriptor");
3210       SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3211       const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3212       unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3213                                            CompileUnit->getFileName());
3214       // Record the source line but does create a label. It will be emitted
3215       // at asm emission time.
3216       MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3217     }
3218
3219     return 0;
3220   }
3221   case Intrinsic::dbg_declare: {
3222     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3223     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3224     Value *Variable = DI.getVariable();
3225     if (MMI && Variable && MMI->Verify(Variable))
3226       DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3227                               getValue(DI.getAddress()), getValue(Variable)));
3228     return 0;
3229   }
3230     
3231   case Intrinsic::eh_exception: {
3232     if (!CurMBB->isLandingPad()) {
3233       // FIXME: Mark exception register as live in.  Hack for PR1508.
3234       unsigned Reg = TLI.getExceptionAddressRegister();
3235       if (Reg) CurMBB->addLiveIn(Reg);
3236     }
3237     // Insert the EXCEPTIONADDR instruction.
3238     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3239     SDOperand Ops[1];
3240     Ops[0] = DAG.getRoot();
3241     SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3242     setValue(&I, Op);
3243     DAG.setRoot(Op.getValue(1));
3244     return 0;
3245   }
3246
3247   case Intrinsic::eh_selector_i32:
3248   case Intrinsic::eh_selector_i64: {
3249     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3250     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3251                          MVT::i32 : MVT::i64);
3252     
3253     if (MMI) {
3254       if (CurMBB->isLandingPad())
3255         addCatchInfo(I, MMI, CurMBB);
3256       else {
3257 #ifndef NDEBUG
3258         FuncInfo.CatchInfoLost.insert(&I);
3259 #endif
3260         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
3261         unsigned Reg = TLI.getExceptionSelectorRegister();
3262         if (Reg) CurMBB->addLiveIn(Reg);
3263       }
3264
3265       // Insert the EHSELECTION instruction.
3266       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3267       SDOperand Ops[2];
3268       Ops[0] = getValue(I.getOperand(1));
3269       Ops[1] = getRoot();
3270       SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3271       setValue(&I, Op);
3272       DAG.setRoot(Op.getValue(1));
3273     } else {
3274       setValue(&I, DAG.getConstant(0, VT));
3275     }
3276     
3277     return 0;
3278   }
3279
3280   case Intrinsic::eh_typeid_for_i32:
3281   case Intrinsic::eh_typeid_for_i64: {
3282     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3283     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3284                          MVT::i32 : MVT::i64);
3285     
3286     if (MMI) {
3287       // Find the type id for the given typeinfo.
3288       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3289
3290       unsigned TypeID = MMI->getTypeIDFor(GV);
3291       setValue(&I, DAG.getConstant(TypeID, VT));
3292     } else {
3293       // Return something different to eh_selector.
3294       setValue(&I, DAG.getConstant(1, VT));
3295     }
3296
3297     return 0;
3298   }
3299
3300   case Intrinsic::eh_return: {
3301     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3302
3303     if (MMI) {
3304       MMI->setCallsEHReturn(true);
3305       DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3306                               MVT::Other,
3307                               getControlRoot(),
3308                               getValue(I.getOperand(1)),
3309                               getValue(I.getOperand(2))));
3310     } else {
3311       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3312     }
3313
3314     return 0;
3315   }
3316
3317    case Intrinsic::eh_unwind_init: {    
3318      if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3319        MMI->setCallsUnwindInit(true);
3320      }
3321
3322      return 0;
3323    }
3324
3325    case Intrinsic::eh_dwarf_cfa: {
3326      MVT VT = getValue(I.getOperand(1)).getValueType();
3327      SDOperand CfaArg;
3328      if (VT.bitsGT(TLI.getPointerTy()))
3329        CfaArg = DAG.getNode(ISD::TRUNCATE,
3330                             TLI.getPointerTy(), getValue(I.getOperand(1)));
3331      else
3332        CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3333                             TLI.getPointerTy(), getValue(I.getOperand(1)));
3334
3335      SDOperand Offset = DAG.getNode(ISD::ADD,
3336                                     TLI.getPointerTy(),
3337                                     DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3338                                                 TLI.getPointerTy()),
3339                                     CfaArg);
3340      setValue(&I, DAG.getNode(ISD::ADD,
3341                               TLI.getPointerTy(),
3342                               DAG.getNode(ISD::FRAMEADDR,
3343                                           TLI.getPointerTy(),
3344                                           DAG.getConstant(0,
3345                                                           TLI.getPointerTy())),
3346                               Offset));
3347      return 0;
3348   }
3349
3350   case Intrinsic::sqrt:
3351     setValue(&I, DAG.getNode(ISD::FSQRT,
3352                              getValue(I.getOperand(1)).getValueType(),
3353                              getValue(I.getOperand(1))));
3354     return 0;
3355   case Intrinsic::powi:
3356     setValue(&I, DAG.getNode(ISD::FPOWI,
3357                              getValue(I.getOperand(1)).getValueType(),
3358                              getValue(I.getOperand(1)),
3359                              getValue(I.getOperand(2))));
3360     return 0;
3361   case Intrinsic::sin:
3362     setValue(&I, DAG.getNode(ISD::FSIN,
3363                              getValue(I.getOperand(1)).getValueType(),
3364                              getValue(I.getOperand(1))));
3365     return 0;
3366   case Intrinsic::cos:
3367     setValue(&I, DAG.getNode(ISD::FCOS,
3368                              getValue(I.getOperand(1)).getValueType(),
3369                              getValue(I.getOperand(1))));
3370     return 0;
3371   case Intrinsic::pow:
3372     setValue(&I, DAG.getNode(ISD::FPOW,
3373                              getValue(I.getOperand(1)).getValueType(),
3374                              getValue(I.getOperand(1)),
3375                              getValue(I.getOperand(2))));
3376     return 0;
3377   case Intrinsic::pcmarker: {
3378     SDOperand Tmp = getValue(I.getOperand(1));
3379     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3380     return 0;
3381   }
3382   case Intrinsic::readcyclecounter: {
3383     SDOperand Op = getRoot();
3384     SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3385                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3386                                 &Op, 1);
3387     setValue(&I, Tmp);
3388     DAG.setRoot(Tmp.getValue(1));
3389     return 0;
3390   }
3391   case Intrinsic::part_select: {
3392     // Currently not implemented: just abort
3393     assert(0 && "part_select intrinsic not implemented");
3394     abort();
3395   }
3396   case Intrinsic::part_set: {
3397     // Currently not implemented: just abort
3398     assert(0 && "part_set intrinsic not implemented");
3399     abort();
3400   }
3401   case Intrinsic::bswap:
3402     setValue(&I, DAG.getNode(ISD::BSWAP,
3403                              getValue(I.getOperand(1)).getValueType(),
3404                              getValue(I.getOperand(1))));
3405     return 0;
3406   case Intrinsic::cttz: {
3407     SDOperand Arg = getValue(I.getOperand(1));
3408     MVT Ty = Arg.getValueType();
3409     SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3410     setValue(&I, result);
3411     return 0;
3412   }
3413   case Intrinsic::ctlz: {
3414     SDOperand Arg = getValue(I.getOperand(1));
3415     MVT Ty = Arg.getValueType();
3416     SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3417     setValue(&I, result);
3418     return 0;
3419   }
3420   case Intrinsic::ctpop: {
3421     SDOperand Arg = getValue(I.getOperand(1));
3422     MVT Ty = Arg.getValueType();
3423     SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3424     setValue(&I, result);
3425     return 0;
3426   }
3427   case Intrinsic::stacksave: {
3428     SDOperand Op = getRoot();
3429     SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3430               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3431     setValue(&I, Tmp);
3432     DAG.setRoot(Tmp.getValue(1));
3433     return 0;
3434   }
3435   case Intrinsic::stackrestore: {
3436     SDOperand Tmp = getValue(I.getOperand(1));
3437     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3438     return 0;
3439   }
3440   case Intrinsic::var_annotation:
3441     // Discard annotate attributes
3442     return 0;
3443
3444   case Intrinsic::init_trampoline: {
3445     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3446
3447     SDOperand Ops[6];
3448     Ops[0] = getRoot();
3449     Ops[1] = getValue(I.getOperand(1));
3450     Ops[2] = getValue(I.getOperand(2));
3451     Ops[3] = getValue(I.getOperand(3));
3452     Ops[4] = DAG.getSrcValue(I.getOperand(1));
3453     Ops[5] = DAG.getSrcValue(F);
3454
3455     SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3456                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
3457                                                       MVT::Other), 2,
3458                                 Ops, 6);
3459
3460     setValue(&I, Tmp);
3461     DAG.setRoot(Tmp.getValue(1));
3462     return 0;
3463   }
3464
3465   case Intrinsic::gcroot:
3466     if (GCI) {
3467       Value *Alloca = I.getOperand(1);
3468       Constant *TypeMap = cast<Constant>(I.getOperand(2));
3469       
3470       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3471       GCI->addStackRoot(FI->getIndex(), TypeMap);
3472     }
3473     return 0;
3474
3475   case Intrinsic::gcread:
3476   case Intrinsic::gcwrite:
3477     assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3478     return 0;
3479
3480   case Intrinsic::flt_rounds: {
3481     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3482     return 0;
3483   }
3484
3485   case Intrinsic::trap: {
3486     DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3487     return 0;
3488   }
3489   case Intrinsic::prefetch: {
3490     SDOperand Ops[4];
3491     Ops[0] = getRoot();
3492     Ops[1] = getValue(I.getOperand(1));
3493     Ops[2] = getValue(I.getOperand(2));
3494     Ops[3] = getValue(I.getOperand(3));
3495     DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3496     return 0;
3497   }
3498   
3499   case Intrinsic::memory_barrier: {
3500     SDOperand Ops[6];
3501     Ops[0] = getRoot();
3502     for (int x = 1; x < 6; ++x)
3503       Ops[x] = getValue(I.getOperand(x));
3504
3505     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3506     return 0;
3507   }
3508   case Intrinsic::atomic_lcs: {
3509     SDOperand Root = getRoot();   
3510     SDOperand O3 = getValue(I.getOperand(3));
3511     SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root, 
3512                                 getValue(I.getOperand(1)), 
3513                                 getValue(I.getOperand(2)),
3514                                 O3, O3.getValueType());
3515     setValue(&I, L);
3516     DAG.setRoot(L.getValue(1));
3517     return 0;
3518   }
3519   case Intrinsic::atomic_las:
3520     return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3521   case Intrinsic::atomic_lss:
3522     return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3523   case Intrinsic::atomic_load_and:
3524     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3525   case Intrinsic::atomic_load_or:
3526     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3527   case Intrinsic::atomic_load_xor:
3528     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3529   case Intrinsic::atomic_load_nand:
3530     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
3531   case Intrinsic::atomic_load_min:
3532     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3533   case Intrinsic::atomic_load_max:
3534     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3535   case Intrinsic::atomic_load_umin:
3536     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3537   case Intrinsic::atomic_load_umax:
3538       return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);                                              
3539   case Intrinsic::atomic_swap:
3540     return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3541   }
3542 }
3543
3544
3545 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3546                                        bool IsTailCall,
3547                                        MachineBasicBlock *LandingPad) {
3548   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3549   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3550   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3551   unsigned BeginLabel = 0, EndLabel = 0;
3552
3553   TargetLowering::ArgListTy Args;
3554   TargetLowering::ArgListEntry Entry;
3555   Args.reserve(CS.arg_size());
3556   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3557        i != e; ++i) {
3558     SDOperand ArgNode = getValue(*i);
3559     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3560
3561     unsigned attrInd = i - CS.arg_begin() + 1;
3562     Entry.isSExt  = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3563     Entry.isZExt  = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3564     Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3565     Entry.isSRet  = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3566     Entry.isNest  = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3567     Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3568     Entry.Alignment = CS.getParamAlignment(attrInd);
3569     Args.push_back(Entry);
3570   }
3571
3572   if (LandingPad && MMI) {
3573     // Insert a label before the invoke call to mark the try range.  This can be
3574     // used to detect deletion of the invoke via the MachineModuleInfo.
3575     BeginLabel = MMI->NextLabelID();
3576     // Both PendingLoads and PendingExports must be flushed here;
3577     // this call might not return.
3578     (void)getRoot();
3579     DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3580                             DAG.getConstant(BeginLabel, MVT::i32),
3581                             DAG.getConstant(1, MVT::i32)));
3582   }
3583
3584   std::pair<SDOperand,SDOperand> Result =
3585     TLI.LowerCallTo(getRoot(), CS.getType(),
3586                     CS.paramHasAttr(0, ParamAttr::SExt),
3587                     CS.paramHasAttr(0, ParamAttr::ZExt),
3588                     FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3589                     Callee, Args, DAG);
3590   if (CS.getType() != Type::VoidTy)
3591     setValue(CS.getInstruction(), Result.first);
3592   DAG.setRoot(Result.second);
3593
3594   if (LandingPad && MMI) {
3595     // Insert a label at the end of the invoke call to mark the try range.  This
3596     // can be used to detect deletion of the invoke via the MachineModuleInfo.
3597     EndLabel = MMI->NextLabelID();
3598     DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3599                             DAG.getConstant(EndLabel, MVT::i32),
3600                             DAG.getConstant(1, MVT::i32)));
3601
3602     // Inform MachineModuleInfo of range.
3603     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3604   }
3605 }
3606
3607
3608 void SelectionDAGLowering::visitCall(CallInst &I) {
3609   const char *RenameFn = 0;
3610   if (Function *F = I.getCalledFunction()) {
3611     if (F->isDeclaration()) {
3612       if (unsigned IID = F->getIntrinsicID()) {
3613         RenameFn = visitIntrinsicCall(I, IID);
3614         if (!RenameFn)
3615           return;
3616       }
3617     }
3618
3619     // Check for well-known libc/libm calls.  If the function is internal, it
3620     // can't be a library call.
3621     unsigned NameLen = F->getNameLen();
3622     if (!F->hasInternalLinkage() && NameLen) {
3623       const char *NameStr = F->getNameStart();
3624       if (NameStr[0] == 'c' &&
3625           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3626            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3627         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
3628             I.getOperand(1)->getType()->isFloatingPoint() &&
3629             I.getType() == I.getOperand(1)->getType() &&
3630             I.getType() == I.getOperand(2)->getType()) {
3631           SDOperand LHS = getValue(I.getOperand(1));
3632           SDOperand RHS = getValue(I.getOperand(2));
3633           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3634                                    LHS, RHS));
3635           return;
3636         }
3637       } else if (NameStr[0] == 'f' &&
3638                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3639                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3640                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3641         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3642             I.getOperand(1)->getType()->isFloatingPoint() &&
3643             I.getType() == I.getOperand(1)->getType()) {
3644           SDOperand Tmp = getValue(I.getOperand(1));
3645           setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3646           return;
3647         }
3648       } else if (NameStr[0] == 's' && 
3649                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3650                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3651                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3652         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3653             I.getOperand(1)->getType()->isFloatingPoint() &&
3654             I.getType() == I.getOperand(1)->getType()) {
3655           SDOperand Tmp = getValue(I.getOperand(1));
3656           setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3657           return;
3658         }
3659       } else if (NameStr[0] == 'c' &&
3660                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3661                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3662                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3663         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3664             I.getOperand(1)->getType()->isFloatingPoint() &&
3665             I.getType() == I.getOperand(1)->getType()) {
3666           SDOperand Tmp = getValue(I.getOperand(1));
3667           setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3668           return;
3669         }
3670       }
3671     }
3672   } else if (isa<InlineAsm>(I.getOperand(0))) {
3673     visitInlineAsm(&I);
3674     return;
3675   }
3676
3677   SDOperand Callee;
3678   if (!RenameFn)
3679     Callee = getValue(I.getOperand(0));
3680   else
3681     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3682
3683   LowerCallTo(&I, Callee, I.isTailCall());
3684 }
3685
3686
3687 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3688   if (isa<UndefValue>(I.getOperand(0))) {
3689     SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3690     setValue(&I, Undef);
3691     return;
3692   }
3693   
3694   // To add support for individual return values with aggregate types,
3695   // we'd need a way to take a getresult index and determine which
3696   // values of the Call SDNode are associated with it.
3697   assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3698          "Individual return values must not be aggregates!");
3699
3700   SDOperand Call = getValue(I.getOperand(0));
3701   setValue(&I, SDOperand(Call.Val, I.getIndex()));
3702 }
3703
3704
3705 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3706 /// this value and returns the result as a ValueVT value.  This uses 
3707 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3708 /// If the Flag pointer is NULL, no flag is used.
3709 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3710                                         SDOperand &Chain,
3711                                         SDOperand *Flag) const {
3712   // Assemble the legal parts into the final values.
3713   SmallVector<SDOperand, 4> Values(ValueVTs.size());
3714   SmallVector<SDOperand, 8> Parts;
3715   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3716     // Copy the legal parts from the registers.
3717     MVT ValueVT = ValueVTs[Value];
3718     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3719     MVT RegisterVT = RegVTs[Value];
3720
3721     Parts.resize(NumRegs);
3722     for (unsigned i = 0; i != NumRegs; ++i) {
3723       SDOperand P;
3724       if (Flag == 0)
3725         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3726       else {
3727         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3728         *Flag = P.getValue(2);
3729       }
3730       Chain = P.getValue(1);
3731       Parts[Part+i] = P;
3732     }
3733   
3734     Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3735                                      ValueVT);
3736     Part += NumRegs;
3737   }
3738   
3739   if (ValueVTs.size() == 1)
3740     return Values[0];
3741     
3742   return DAG.getNode(ISD::MERGE_VALUES,
3743                      DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3744                      &Values[0], ValueVTs.size());
3745 }
3746
3747 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3748 /// specified value into the registers specified by this object.  This uses 
3749 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3750 /// If the Flag pointer is NULL, no flag is used.
3751 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3752                                  SDOperand &Chain, SDOperand *Flag) const {
3753   // Get the list of the values's legal parts.
3754   unsigned NumRegs = Regs.size();
3755   SmallVector<SDOperand, 8> Parts(NumRegs);
3756   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3757     MVT ValueVT = ValueVTs[Value];
3758     unsigned NumParts = TLI->getNumRegisters(ValueVT);
3759     MVT RegisterVT = RegVTs[Value];
3760
3761     getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3762                    &Parts[Part], NumParts, RegisterVT);
3763     Part += NumParts;
3764   }
3765
3766   // Copy the parts into the registers.
3767   SmallVector<SDOperand, 8> Chains(NumRegs);
3768   for (unsigned i = 0; i != NumRegs; ++i) {
3769     SDOperand Part;
3770     if (Flag == 0)
3771       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3772     else {
3773       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3774       *Flag = Part.getValue(1);
3775     }
3776     Chains[i] = Part.getValue(0);
3777   }
3778   
3779   if (NumRegs == 1 || Flag)
3780     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 
3781     // flagged to it. That is the CopyToReg nodes and the user are considered
3782     // a single scheduling unit. If we create a TokenFactor and return it as
3783     // chain, then the TokenFactor is both a predecessor (operand) of the
3784     // user as well as a successor (the TF operands are flagged to the user).
3785     // c1, f1 = CopyToReg
3786     // c2, f2 = CopyToReg
3787     // c3     = TokenFactor c1, c2
3788     // ...
3789     //        = op c3, ..., f2
3790     Chain = Chains[NumRegs-1];
3791   else
3792     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3793 }
3794
3795 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3796 /// operand list.  This adds the code marker and includes the number of 
3797 /// values added into it.
3798 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3799                                         std::vector<SDOperand> &Ops) const {
3800   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3801   Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3802   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3803     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3804     MVT RegisterVT = RegVTs[Value];
3805     for (unsigned i = 0; i != NumRegs; ++i)
3806       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3807   }
3808 }
3809
3810 /// isAllocatableRegister - If the specified register is safe to allocate, 
3811 /// i.e. it isn't a stack pointer or some other special register, return the
3812 /// register class for the register.  Otherwise, return null.
3813 static const TargetRegisterClass *
3814 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3815                       const TargetLowering &TLI,
3816                       const TargetRegisterInfo *TRI) {
3817   MVT FoundVT = MVT::Other;
3818   const TargetRegisterClass *FoundRC = 0;
3819   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3820        E = TRI->regclass_end(); RCI != E; ++RCI) {
3821     MVT ThisVT = MVT::Other;
3822
3823     const TargetRegisterClass *RC = *RCI;
3824     // If none of the the value types for this register class are valid, we 
3825     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
3826     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3827          I != E; ++I) {
3828       if (TLI.isTypeLegal(*I)) {
3829         // If we have already found this register in a different register class,
3830         // choose the one with the largest VT specified.  For example, on
3831         // PowerPC, we favor f64 register classes over f32.
3832         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3833           ThisVT = *I;
3834           break;
3835         }
3836       }
3837     }
3838     
3839     if (ThisVT == MVT::Other) continue;
3840     
3841     // NOTE: This isn't ideal.  In particular, this might allocate the
3842     // frame pointer in functions that need it (due to them not being taken
3843     // out of allocation, because a variable sized allocation hasn't been seen
3844     // yet).  This is a slight code pessimization, but should still work.
3845     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3846          E = RC->allocation_order_end(MF); I != E; ++I)
3847       if (*I == Reg) {
3848         // We found a matching register class.  Keep looking at others in case
3849         // we find one with larger registers that this physreg is also in.
3850         FoundRC = RC;
3851         FoundVT = ThisVT;
3852         break;
3853       }
3854   }
3855   return FoundRC;
3856 }    
3857
3858
3859 namespace {
3860 /// AsmOperandInfo - This contains information for each constraint that we are
3861 /// lowering.
3862 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3863   /// CallOperand - If this is the result output operand or a clobber
3864   /// this is null, otherwise it is the incoming operand to the CallInst.
3865   /// This gets modified as the asm is processed.
3866   SDOperand CallOperand;
3867
3868   /// AssignedRegs - If this is a register or register class operand, this
3869   /// contains the set of register corresponding to the operand.
3870   RegsForValue AssignedRegs;
3871   
3872   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3873     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3874   }
3875   
3876   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3877   /// busy in OutputRegs/InputRegs.
3878   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3879                          std::set<unsigned> &OutputRegs, 
3880                          std::set<unsigned> &InputRegs,
3881                          const TargetRegisterInfo &TRI) const {
3882     if (isOutReg) {
3883       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3884         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3885     }
3886     if (isInReg) {
3887       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3888         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3889     }
3890   }
3891   
3892 private:
3893   /// MarkRegAndAliases - Mark the specified register and all aliases in the
3894   /// specified set.
3895   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 
3896                                 const TargetRegisterInfo &TRI) {
3897     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3898     Regs.insert(Reg);
3899     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3900       for (; *Aliases; ++Aliases)
3901         Regs.insert(*Aliases);
3902   }
3903 };
3904 } // end anon namespace.
3905
3906
3907 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3908 /// specified operand.  We prefer to assign virtual registers, to allow the
3909 /// register allocator handle the assignment process.  However, if the asm uses
3910 /// features that we can't model on machineinstrs, we have SDISel do the
3911 /// allocation.  This produces generally horrible, but correct, code.
3912 ///
3913 ///   OpInfo describes the operand.
3914 ///   HasEarlyClobber is true if there are any early clobber constraints (=&r)
3915 ///     or any explicitly clobbered registers.
3916 ///   Input and OutputRegs are the set of already allocated physical registers.
3917 ///
3918 void SelectionDAGLowering::
3919 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3920                      std::set<unsigned> &OutputRegs, 
3921                      std::set<unsigned> &InputRegs) {
3922   // Compute whether this value requires an input register, an output register,
3923   // or both.
3924   bool isOutReg = false;
3925   bool isInReg = false;
3926   switch (OpInfo.Type) {
3927   case InlineAsm::isOutput:
3928     isOutReg = true;
3929     
3930     // If this is an early-clobber output, or if there is an input
3931     // constraint that matches this, we need to reserve the input register
3932     // so no other inputs allocate to it.
3933     isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3934     break;
3935   case InlineAsm::isInput:
3936     isInReg = true;
3937     isOutReg = false;
3938     break;
3939   case InlineAsm::isClobber:
3940     isOutReg = true;
3941     isInReg = true;
3942     break;
3943   }
3944   
3945   
3946   MachineFunction &MF = DAG.getMachineFunction();
3947   SmallVector<unsigned, 4> Regs;
3948   
3949   // If this is a constraint for a single physreg, or a constraint for a
3950   // register class, find it.
3951   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
3952     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3953                                      OpInfo.ConstraintVT);
3954
3955   unsigned NumRegs = 1;
3956   if (OpInfo.ConstraintVT != MVT::Other)
3957     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3958   MVT RegVT;
3959   MVT ValueVT = OpInfo.ConstraintVT;
3960   
3961
3962   // If this is a constraint for a specific physical register, like {r17},
3963   // assign it now.
3964   if (PhysReg.first) {
3965     if (OpInfo.ConstraintVT == MVT::Other)
3966       ValueVT = *PhysReg.second->vt_begin();
3967     
3968     // Get the actual register value type.  This is important, because the user
3969     // may have asked for (e.g.) the AX register in i32 type.  We need to
3970     // remember that AX is actually i16 to get the right extension.
3971     RegVT = *PhysReg.second->vt_begin();
3972     
3973     // This is a explicit reference to a physical register.
3974     Regs.push_back(PhysReg.first);
3975
3976     // If this is an expanded reference, add the rest of the regs to Regs.
3977     if (NumRegs != 1) {
3978       TargetRegisterClass::iterator I = PhysReg.second->begin();
3979       for (; *I != PhysReg.first; ++I)
3980         assert(I != PhysReg.second->end() && "Didn't find reg!"); 
3981       
3982       // Already added the first reg.
3983       --NumRegs; ++I;
3984       for (; NumRegs; --NumRegs, ++I) {
3985         assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
3986         Regs.push_back(*I);
3987       }
3988     }
3989     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3990     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3991     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3992     return;
3993   }
3994   
3995   // Otherwise, if this was a reference to an LLVM register class, create vregs
3996   // for this reference.
3997   std::vector<unsigned> RegClassRegs;
3998   const TargetRegisterClass *RC = PhysReg.second;
3999   if (RC) {
4000     // If this is an early clobber or tied register, our regalloc doesn't know
4001     // how to maintain the constraint.  If it isn't, go ahead and create vreg
4002     // and let the regalloc do the right thing.
4003     if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4004         // If there is some other early clobber and this is an input register,
4005         // then we are forced to pre-allocate the input reg so it doesn't
4006         // conflict with the earlyclobber.
4007         !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4008       RegVT = *PhysReg.second->vt_begin();
4009       
4010       if (OpInfo.ConstraintVT == MVT::Other)
4011         ValueVT = RegVT;
4012
4013       // Create the appropriate number of virtual registers.
4014       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4015       for (; NumRegs; --NumRegs)
4016         Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4017       
4018       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4019       return;
4020     }
4021     
4022     // Otherwise, we can't allocate it.  Let the code below figure out how to
4023     // maintain these constraints.
4024     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4025     
4026   } else {
4027     // This is a reference to a register class that doesn't directly correspond
4028     // to an LLVM register class.  Allocate NumRegs consecutive, available,
4029     // registers from the class.
4030     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4031                                                          OpInfo.ConstraintVT);
4032   }
4033   
4034   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4035   unsigned NumAllocated = 0;
4036   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4037     unsigned Reg = RegClassRegs[i];
4038     // See if this register is available.
4039     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
4040         (isInReg  && InputRegs.count(Reg))) {    // Already used.
4041       // Make sure we find consecutive registers.
4042       NumAllocated = 0;
4043       continue;
4044     }
4045     
4046     // Check to see if this register is allocatable (i.e. don't give out the
4047     // stack pointer).
4048     if (RC == 0) {
4049       RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4050       if (!RC) {        // Couldn't allocate this register.
4051         // Reset NumAllocated to make sure we return consecutive registers.
4052         NumAllocated = 0;
4053         continue;
4054       }
4055     }
4056     
4057     // Okay, this register is good, we can use it.
4058     ++NumAllocated;
4059
4060     // If we allocated enough consecutive registers, succeed.
4061     if (NumAllocated == NumRegs) {
4062       unsigned RegStart = (i-NumAllocated)+1;
4063       unsigned RegEnd   = i+1;
4064       // Mark all of the allocated registers used.
4065       for (unsigned i = RegStart; i != RegEnd; ++i)
4066         Regs.push_back(RegClassRegs[i]);
4067       
4068       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 
4069                                          OpInfo.ConstraintVT);
4070       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4071       return;
4072     }
4073   }
4074   
4075   // Otherwise, we couldn't allocate enough registers for this.
4076 }
4077
4078
4079 /// visitInlineAsm - Handle a call to an InlineAsm object.
4080 ///
4081 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4082   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4083
4084   /// ConstraintOperands - Information about all of the constraints.
4085   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4086   
4087   SDOperand Chain = getRoot();
4088   SDOperand Flag;
4089   
4090   std::set<unsigned> OutputRegs, InputRegs;
4091
4092   // Do a prepass over the constraints, canonicalizing them, and building up the
4093   // ConstraintOperands list.
4094   std::vector<InlineAsm::ConstraintInfo>
4095     ConstraintInfos = IA->ParseConstraints();
4096
4097   // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4098   // constraint.  If so, we can't let the register allocator allocate any input
4099   // registers, because it will not know to avoid the earlyclobbered output reg.
4100   bool SawEarlyClobber = false;
4101   
4102   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
4103   unsigned ResNo = 0;   // ResNo - The result number of the next output.
4104   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4105     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4106     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4107     
4108     MVT OpVT = MVT::Other;
4109
4110     // Compute the value type for each operand.
4111     switch (OpInfo.Type) {
4112     case InlineAsm::isOutput:
4113       // Indirect outputs just consume an argument.
4114       if (OpInfo.isIndirect) {
4115         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4116         break;
4117       }
4118       // The return value of the call is this value.  As such, there is no
4119       // corresponding argument.
4120       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4121       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4122         OpVT = TLI.getValueType(STy->getElementType(ResNo));
4123       } else {
4124         assert(ResNo == 0 && "Asm only has one result!");
4125         OpVT = TLI.getValueType(CS.getType());
4126       }
4127       ++ResNo;
4128       break;
4129     case InlineAsm::isInput:
4130       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4131       break;
4132     case InlineAsm::isClobber:
4133       // Nothing to do.
4134       break;
4135     }
4136
4137     // If this is an input or an indirect output, process the call argument.
4138     // BasicBlocks are labels, currently appearing only in asm's.
4139     if (OpInfo.CallOperandVal) {
4140       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4141         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4142       else {
4143         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4144         const Type *OpTy = OpInfo.CallOperandVal->getType();
4145         // If this is an indirect operand, the operand is a pointer to the
4146         // accessed type.
4147         if (OpInfo.isIndirect)
4148           OpTy = cast<PointerType>(OpTy)->getElementType();
4149
4150         // If OpTy is not a single value, it may be a struct/union that we
4151         // can tile with integers.
4152         if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4153           unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4154           switch (BitSize) {
4155           default: break;
4156           case 1:
4157           case 8:
4158           case 16:
4159           case 32:
4160           case 64:
4161             OpTy = IntegerType::get(BitSize);
4162             break;
4163           }
4164         }
4165
4166         OpVT = TLI.getValueType(OpTy, true);
4167       }
4168     }
4169     
4170     OpInfo.ConstraintVT = OpVT;
4171     
4172     // Compute the constraint code and ConstraintType to use.
4173     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4174
4175     // Keep track of whether we see an earlyclobber.
4176     SawEarlyClobber |= OpInfo.isEarlyClobber;
4177     
4178     // If we see a clobber of a register, it is an early clobber.
4179     if (!SawEarlyClobber &&
4180         OpInfo.Type == InlineAsm::isClobber &&
4181         OpInfo.ConstraintType == TargetLowering::C_Register) {
4182       // Note that we want to ignore things that we don't trick here, like
4183       // dirflag, fpsr, flags, etc.
4184       std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
4185         TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4186                                          OpInfo.ConstraintVT);
4187       if (PhysReg.first || PhysReg.second) {
4188         // This is a register we know of.
4189         SawEarlyClobber = true;
4190       }
4191     }
4192     
4193     // If this is a memory input, and if the operand is not indirect, do what we
4194     // need to to provide an address for the memory input.
4195     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4196         !OpInfo.isIndirect) {
4197       assert(OpInfo.Type == InlineAsm::isInput &&
4198              "Can only indirectify direct input operands!");
4199       
4200       // Memory operands really want the address of the value.  If we don't have
4201       // an indirect input, put it in the constpool if we can, otherwise spill
4202       // it to a stack slot.
4203       
4204       // If the operand is a float, integer, or vector constant, spill to a
4205       // constant pool entry to get its address.
4206       Value *OpVal = OpInfo.CallOperandVal;
4207       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4208           isa<ConstantVector>(OpVal)) {
4209         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4210                                                  TLI.getPointerTy());
4211       } else {
4212         // Otherwise, create a stack slot and emit a store to it before the
4213         // asm.
4214         const Type *Ty = OpVal->getType();
4215         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4216         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4217         MachineFunction &MF = DAG.getMachineFunction();
4218         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4219         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4220         Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4221         OpInfo.CallOperand = StackSlot;
4222       }
4223      
4224       // There is no longer a Value* corresponding to this operand.
4225       OpInfo.CallOperandVal = 0;
4226       // It is now an indirect operand.
4227       OpInfo.isIndirect = true;
4228     }
4229     
4230     // If this constraint is for a specific register, allocate it before
4231     // anything else.
4232     if (OpInfo.ConstraintType == TargetLowering::C_Register)
4233       GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4234   }
4235   ConstraintInfos.clear();
4236   
4237   
4238   // Second pass - Loop over all of the operands, assigning virtual or physregs
4239   // to registerclass operands.
4240   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4241     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4242     
4243     // C_Register operands have already been allocated, Other/Memory don't need
4244     // to be.
4245     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4246       GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4247   }    
4248   
4249   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4250   std::vector<SDOperand> AsmNodeOperands;
4251   AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
4252   AsmNodeOperands.push_back(
4253           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4254   
4255   
4256   // Loop over all of the inputs, copying the operand values into the
4257   // appropriate registers and processing the output regs.
4258   RegsForValue RetValRegs;
4259  
4260   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4261   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4262   
4263   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4264     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4265
4266     switch (OpInfo.Type) {
4267     case InlineAsm::isOutput: {
4268       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4269           OpInfo.ConstraintType != TargetLowering::C_Register) {
4270         // Memory output, or 'other' output (e.g. 'X' constraint).
4271         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4272
4273         // Add information to the INLINEASM node to know about this output.
4274         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4275         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
4276                                                         TLI.getPointerTy()));
4277         AsmNodeOperands.push_back(OpInfo.CallOperand);
4278         break;
4279       }
4280
4281       // Otherwise, this is a register or register class output.
4282
4283       // Copy the output from the appropriate register.  Find a register that
4284       // we can use.
4285       if (OpInfo.AssignedRegs.Regs.empty()) {
4286         cerr << "Couldn't allocate output reg for constraint '"
4287              << OpInfo.ConstraintCode << "'!\n";
4288         exit(1);
4289       }
4290
4291       // If this is an indirect operand, store through the pointer after the
4292       // asm.
4293       if (OpInfo.isIndirect) {
4294         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4295                                                       OpInfo.CallOperandVal));
4296       } else {
4297         // This is the result value of the call.
4298         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4299         // Concatenate this output onto the outputs list.
4300         RetValRegs.append(OpInfo.AssignedRegs);
4301       }
4302       
4303       // Add information to the INLINEASM node to know that this register is
4304       // set.
4305       OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4306                                                AsmNodeOperands);
4307       break;
4308     }
4309     case InlineAsm::isInput: {
4310       SDOperand InOperandVal = OpInfo.CallOperand;
4311       
4312       if (isdigit(OpInfo.ConstraintCode[0])) {    // Matching constraint?
4313         // If this is required to match an output register we have already set,
4314         // just use its register.
4315         unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4316         
4317         // Scan until we find the definition we already emitted of this operand.
4318         // When we find it, create a RegsForValue operand.
4319         unsigned CurOp = 2;  // The first operand.
4320         for (; OperandNo; --OperandNo) {
4321           // Advance to the next operand.
4322           unsigned NumOps = 
4323             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4324           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4325                   (NumOps & 7) == 4 /*MEM*/) &&
4326                  "Skipped past definitions?");
4327           CurOp += (NumOps>>3)+1;
4328         }
4329
4330         unsigned NumOps = 
4331           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4332         if ((NumOps & 7) == 2 /*REGDEF*/) {
4333           // Add NumOps>>3 registers to MatchedRegs.
4334           RegsForValue MatchedRegs;
4335           MatchedRegs.TLI = &TLI;
4336           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4337           MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4338           for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4339             unsigned Reg =
4340               cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4341             MatchedRegs.Regs.push_back(Reg);
4342           }
4343         
4344           // Use the produced MatchedRegs object to 
4345           MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4346           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4347           break;
4348         } else {
4349           assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4350           assert((NumOps >> 3) == 1 && "Unexpected number of operands"); 
4351           // Add information to the INLINEASM node to know about this input.
4352           unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4353           AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4354                                                           TLI.getPointerTy()));
4355           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4356           break;
4357         }
4358       }
4359       
4360       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4361         assert(!OpInfo.isIndirect && 
4362                "Don't know how to handle indirect other inputs yet!");
4363         
4364         std::vector<SDOperand> Ops;
4365         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4366                                          Ops, DAG);
4367         if (Ops.empty()) {
4368           cerr << "Invalid operand for inline asm constraint '"
4369                << OpInfo.ConstraintCode << "'!\n";
4370           exit(1);
4371         }
4372         
4373         // Add information to the INLINEASM node to know about this input.
4374         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4375         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
4376                                                         TLI.getPointerTy()));
4377         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4378         break;
4379       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4380         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4381         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4382                "Memory operands expect pointer values");
4383                
4384         // Add information to the INLINEASM node to know about this input.
4385         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4386         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4387                                                         TLI.getPointerTy()));
4388         AsmNodeOperands.push_back(InOperandVal);
4389         break;
4390       }
4391         
4392       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4393               OpInfo.ConstraintType == TargetLowering::C_Register) &&
4394              "Unknown constraint type!");
4395       assert(!OpInfo.isIndirect && 
4396              "Don't know how to handle indirect register inputs yet!");
4397
4398       // Copy the input into the appropriate registers.
4399       assert(!OpInfo.AssignedRegs.Regs.empty() &&
4400              "Couldn't allocate input reg!");
4401
4402       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4403       
4404       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4405                                                AsmNodeOperands);
4406       break;
4407     }
4408     case InlineAsm::isClobber: {
4409       // Add the clobbered value to the operand list, so that the register
4410       // allocator is aware that the physreg got clobbered.
4411       if (!OpInfo.AssignedRegs.Regs.empty())
4412         OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4413                                                  AsmNodeOperands);
4414       break;
4415     }
4416     }
4417   }
4418   
4419   // Finish up input operands.
4420   AsmNodeOperands[0] = Chain;
4421   if (Flag.Val) AsmNodeOperands.push_back(Flag);
4422   
4423   Chain = DAG.getNode(ISD::INLINEASM, 
4424                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4425                       &AsmNodeOperands[0], AsmNodeOperands.size());
4426   Flag = Chain.getValue(1);
4427
4428   // If this asm returns a register value, copy the result from that register
4429   // and set it as the value of the call.
4430   if (!RetValRegs.Regs.empty()) {
4431     SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4432
4433     // If any of the results of the inline asm is a vector, it may have the
4434     // wrong width/num elts.  This can happen for register classes that can
4435     // contain multiple different value types.  The preg or vreg allocated may
4436     // not have the same VT as was expected.  Convert it to the right type with
4437     // bit_convert.
4438     if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4439       for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4440         if (Val.Val->getValueType(i).isVector())
4441           Val = DAG.getNode(ISD::BIT_CONVERT,
4442                             TLI.getValueType(ResSTy->getElementType(i)), Val);
4443       }
4444     } else {
4445       if (Val.getValueType().isVector())
4446         Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4447                           Val);
4448     }
4449
4450     setValue(CS.getInstruction(), Val);
4451   }
4452   
4453   std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4454   
4455   // Process indirect outputs, first output all of the flagged copies out of
4456   // physregs.
4457   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4458     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4459     Value *Ptr = IndirectStoresToEmit[i].second;
4460     SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4461     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4462   }
4463   
4464   // Emit the non-flagged stores from the physregs.
4465   SmallVector<SDOperand, 8> OutChains;
4466   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4467     OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4468                                     getValue(StoresToEmit[i].second),
4469                                     StoresToEmit[i].second, 0));
4470   if (!OutChains.empty())
4471     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4472                         &OutChains[0], OutChains.size());
4473   DAG.setRoot(Chain);
4474 }
4475
4476
4477 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4478   SDOperand Src = getValue(I.getOperand(0));
4479
4480   MVT IntPtr = TLI.getPointerTy();
4481
4482   if (IntPtr.bitsLT(Src.getValueType()))
4483     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4484   else if (IntPtr.bitsGT(Src.getValueType()))
4485     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4486
4487   // Scale the source by the type size.
4488   uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4489   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4490                     Src, DAG.getIntPtrConstant(ElementSize));
4491
4492   TargetLowering::ArgListTy Args;
4493   TargetLowering::ArgListEntry Entry;
4494   Entry.Node = Src;
4495   Entry.Ty = TLI.getTargetData()->getIntPtrType();
4496   Args.push_back(Entry);
4497
4498   std::pair<SDOperand,SDOperand> Result =
4499     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4500                     true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4501   setValue(&I, Result.first);  // Pointers always fit in registers
4502   DAG.setRoot(Result.second);
4503 }
4504
4505 void SelectionDAGLowering::visitFree(FreeInst &I) {
4506   TargetLowering::ArgListTy Args;
4507   TargetLowering::ArgListEntry Entry;
4508   Entry.Node = getValue(I.getOperand(0));
4509   Entry.Ty = TLI.getTargetData()->getIntPtrType();
4510   Args.push_back(Entry);
4511   MVT IntPtr = TLI.getPointerTy();
4512   std::pair<SDOperand,SDOperand> Result =
4513     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4514                     CallingConv::C, true,
4515                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4516   DAG.setRoot(Result.second);
4517 }
4518
4519 // EmitInstrWithCustomInserter - This method should be implemented by targets
4520 // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
4521 // instructions are special in various ways, which require special support to
4522 // insert.  The specified MachineInstr is created but not inserted into any
4523 // basic blocks, and the scheduler passes ownership of it to this method.
4524 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4525                                                        MachineBasicBlock *MBB) {
4526   cerr << "If a target marks an instruction with "
4527        << "'usesCustomDAGSchedInserter', it must implement "
4528        << "TargetLowering::EmitInstrWithCustomInserter!\n";
4529   abort();
4530   return 0;  
4531 }
4532
4533 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4534   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
4535                           getValue(I.getOperand(1)), 
4536                           DAG.getSrcValue(I.getOperand(1))));
4537 }
4538
4539 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4540   SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4541                              getValue(I.getOperand(0)),
4542                              DAG.getSrcValue(I.getOperand(0)));
4543   setValue(&I, V);
4544   DAG.setRoot(V.getValue(1));
4545 }
4546
4547 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4548   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4549                           getValue(I.getOperand(1)), 
4550                           DAG.getSrcValue(I.getOperand(1))));
4551 }
4552
4553 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4554   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
4555                           getValue(I.getOperand(1)), 
4556                           getValue(I.getOperand(2)),
4557                           DAG.getSrcValue(I.getOperand(1)),
4558                           DAG.getSrcValue(I.getOperand(2))));
4559 }
4560
4561 /// TargetLowering::LowerArguments - This is the default LowerArguments
4562 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
4563 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 
4564 /// integrated into SDISel.
4565 std::vector<SDOperand> 
4566 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4567   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4568   std::vector<SDOperand> Ops;
4569   Ops.push_back(DAG.getRoot());
4570   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4571   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4572
4573   // Add one result value for each formal argument.
4574   std::vector<MVT> RetVals;
4575   unsigned j = 1;
4576   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4577        I != E; ++I, ++j) {
4578     SmallVector<MVT, 4> ValueVTs;
4579     ComputeValueVTs(*this, I->getType(), ValueVTs);
4580     for (unsigned Value = 0, NumValues = ValueVTs.size();
4581          Value != NumValues; ++Value) {
4582       MVT VT = ValueVTs[Value];
4583       const Type *ArgTy = VT.getTypeForMVT();
4584       ISD::ArgFlagsTy Flags;
4585       unsigned OriginalAlignment =
4586         getTargetData()->getABITypeAlignment(ArgTy);
4587
4588       if (F.paramHasAttr(j, ParamAttr::ZExt))
4589         Flags.setZExt();
4590       if (F.paramHasAttr(j, ParamAttr::SExt))
4591         Flags.setSExt();
4592       if (F.paramHasAttr(j, ParamAttr::InReg))
4593         Flags.setInReg();
4594       if (F.paramHasAttr(j, ParamAttr::StructRet))
4595         Flags.setSRet();
4596       if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4597         Flags.setByVal();
4598         const PointerType *Ty = cast<PointerType>(I->getType());
4599         const Type *ElementTy = Ty->getElementType();
4600         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4601         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4602         // For ByVal, alignment should be passed from FE.  BE will guess if
4603         // this info is not there but there are cases it cannot get right.
4604         if (F.getParamAlignment(j))
4605           FrameAlign = F.getParamAlignment(j);
4606         Flags.setByValAlign(FrameAlign);
4607         Flags.setByValSize(FrameSize);
4608       }
4609       if (F.paramHasAttr(j, ParamAttr::Nest))
4610         Flags.setNest();
4611       Flags.setOrigAlign(OriginalAlignment);
4612
4613       MVT RegisterVT = getRegisterType(VT);
4614       unsigned NumRegs = getNumRegisters(VT);
4615       for (unsigned i = 0; i != NumRegs; ++i) {
4616         RetVals.push_back(RegisterVT);
4617         ISD::ArgFlagsTy MyFlags = Flags;
4618         if (NumRegs > 1 && i == 0)
4619           MyFlags.setSplit();
4620         // if it isn't first piece, alignment must be 1
4621         else if (i > 0)
4622           MyFlags.setOrigAlign(1);
4623         Ops.push_back(DAG.getArgFlags(MyFlags));
4624       }
4625     }
4626   }
4627
4628   RetVals.push_back(MVT::Other);
4629   
4630   // Create the node.
4631   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4632                                DAG.getVTList(&RetVals[0], RetVals.size()),
4633                                &Ops[0], Ops.size()).Val;
4634   
4635   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
4636   // allows exposing the loads that may be part of the argument access to the
4637   // first DAGCombiner pass.
4638   SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4639   
4640   // The number of results should match up, except that the lowered one may have
4641   // an extra flag result.
4642   assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4643           (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4644            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4645          && "Lowering produced unexpected number of results!");
4646   Result = TmpRes.Val;
4647   
4648   unsigned NumArgRegs = Result->getNumValues() - 1;
4649   DAG.setRoot(SDOperand(Result, NumArgRegs));
4650
4651   // Set up the return result vector.
4652   Ops.clear();
4653   unsigned i = 0;
4654   unsigned Idx = 1;
4655   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 
4656       ++I, ++Idx) {
4657     SmallVector<MVT, 4> ValueVTs;
4658     ComputeValueVTs(*this, I->getType(), ValueVTs);
4659     for (unsigned Value = 0, NumValues = ValueVTs.size();
4660          Value != NumValues; ++Value) {
4661       MVT VT = ValueVTs[Value];
4662       MVT PartVT = getRegisterType(VT);
4663
4664       unsigned NumParts = getNumRegisters(VT);
4665       SmallVector<SDOperand, 4> Parts(NumParts);
4666       for (unsigned j = 0; j != NumParts; ++j)
4667         Parts[j] = SDOperand(Result, i++);
4668
4669       ISD::NodeType AssertOp = ISD::DELETED_NODE;
4670       if (F.paramHasAttr(Idx, ParamAttr::SExt))
4671         AssertOp = ISD::AssertSext;
4672       else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4673         AssertOp = ISD::AssertZext;
4674
4675       Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4676                                      AssertOp));
4677     }
4678   }
4679   assert(i == NumArgRegs && "Argument register count mismatch!");
4680   return Ops;
4681 }
4682
4683
4684 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4685 /// implementation, which just inserts an ISD::CALL node, which is later custom
4686 /// lowered by the target to something concrete.  FIXME: When all targets are
4687 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4688 std::pair<SDOperand, SDOperand>
4689 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4690                             bool RetSExt, bool RetZExt, bool isVarArg,
4691                             unsigned CallingConv, bool isTailCall,
4692                             SDOperand Callee,
4693                             ArgListTy &Args, SelectionDAG &DAG) {
4694   SmallVector<SDOperand, 32> Ops;
4695   Ops.push_back(Chain);   // Op#0 - Chain
4696   Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4697   Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
4698   Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
4699   Ops.push_back(Callee);
4700   
4701   // Handle all of the outgoing arguments.
4702   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4703     SmallVector<MVT, 4> ValueVTs;
4704     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4705     for (unsigned Value = 0, NumValues = ValueVTs.size();
4706          Value != NumValues; ++Value) {
4707       MVT VT = ValueVTs[Value];
4708       const Type *ArgTy = VT.getTypeForMVT();
4709       SDOperand Op = SDOperand(Args[i].Node.Val, Args[i].Node.ResNo + Value);
4710       ISD::ArgFlagsTy Flags;
4711       unsigned OriginalAlignment =
4712         getTargetData()->getABITypeAlignment(ArgTy);
4713
4714       if (Args[i].isZExt)
4715         Flags.setZExt();
4716       if (Args[i].isSExt)
4717         Flags.setSExt();
4718       if (Args[i].isInReg)
4719         Flags.setInReg();
4720       if (Args[i].isSRet)
4721         Flags.setSRet();
4722       if (Args[i].isByVal) {
4723         Flags.setByVal();
4724         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4725         const Type *ElementTy = Ty->getElementType();
4726         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4727         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4728         // For ByVal, alignment should come from FE.  BE will guess if this
4729         // info is not there but there are cases it cannot get right.
4730         if (Args[i].Alignment)
4731           FrameAlign = Args[i].Alignment;
4732         Flags.setByValAlign(FrameAlign);
4733         Flags.setByValSize(FrameSize);
4734       }
4735       if (Args[i].isNest)
4736         Flags.setNest();
4737       Flags.setOrigAlign(OriginalAlignment);
4738
4739       MVT PartVT = getRegisterType(VT);
4740       unsigned NumParts = getNumRegisters(VT);
4741       SmallVector<SDOperand, 4> Parts(NumParts);
4742       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4743
4744       if (Args[i].isSExt)
4745         ExtendKind = ISD::SIGN_EXTEND;
4746       else if (Args[i].isZExt)
4747         ExtendKind = ISD::ZERO_EXTEND;
4748
4749       getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4750
4751       for (unsigned i = 0; i != NumParts; ++i) {
4752         // if it isn't first piece, alignment must be 1
4753         ISD::ArgFlagsTy MyFlags = Flags;
4754         if (NumParts > 1 && i == 0)
4755           MyFlags.setSplit();
4756         else if (i != 0)
4757           MyFlags.setOrigAlign(1);
4758
4759         Ops.push_back(Parts[i]);
4760         Ops.push_back(DAG.getArgFlags(MyFlags));
4761       }
4762     }
4763   }
4764   
4765   // Figure out the result value types. We start by making a list of
4766   // the potentially illegal return value types.
4767   SmallVector<MVT, 4> LoweredRetTys;
4768   SmallVector<MVT, 4> RetTys;
4769   ComputeValueVTs(*this, RetTy, RetTys);
4770
4771   // Then we translate that to a list of legal types.
4772   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4773     MVT VT = RetTys[I];
4774     MVT RegisterVT = getRegisterType(VT);
4775     unsigned NumRegs = getNumRegisters(VT);
4776     for (unsigned i = 0; i != NumRegs; ++i)
4777       LoweredRetTys.push_back(RegisterVT);
4778   }
4779   
4780   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
4781   
4782   // Create the CALL node.
4783   SDOperand Res = DAG.getNode(ISD::CALL,
4784                               DAG.getVTList(&LoweredRetTys[0],
4785                                             LoweredRetTys.size()),
4786                               &Ops[0], Ops.size());
4787   Chain = Res.getValue(LoweredRetTys.size() - 1);
4788
4789   // Gather up the call result into a single value.
4790   if (RetTy != Type::VoidTy) {
4791     ISD::NodeType AssertOp = ISD::DELETED_NODE;
4792
4793     if (RetSExt)
4794       AssertOp = ISD::AssertSext;
4795     else if (RetZExt)
4796       AssertOp = ISD::AssertZext;
4797
4798     SmallVector<SDOperand, 4> ReturnValues;
4799     unsigned RegNo = 0;
4800     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4801       MVT VT = RetTys[I];
4802       MVT RegisterVT = getRegisterType(VT);
4803       unsigned NumRegs = getNumRegisters(VT);
4804       unsigned RegNoEnd = NumRegs + RegNo;
4805       SmallVector<SDOperand, 4> Results;
4806       for (; RegNo != RegNoEnd; ++RegNo)
4807         Results.push_back(Res.getValue(RegNo));
4808       SDOperand ReturnValue =
4809         getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4810                          AssertOp);
4811       ReturnValues.push_back(ReturnValue);
4812     }
4813     Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4814           DAG.getNode(ISD::MERGE_VALUES,
4815                       DAG.getVTList(&RetTys[0], RetTys.size()),
4816                       &ReturnValues[0], ReturnValues.size());
4817   }
4818
4819   return std::make_pair(Res, Chain);
4820 }
4821
4822 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4823   assert(0 && "LowerOperation not implemented for this target!");
4824   abort();
4825   return SDOperand();
4826 }
4827
4828 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4829                                                  SelectionDAG &DAG) {
4830   assert(0 && "CustomPromoteOperation not implemented for this target!");
4831   abort();
4832   return SDOperand();
4833 }
4834
4835 //===----------------------------------------------------------------------===//
4836 // SelectionDAGISel code
4837 //===----------------------------------------------------------------------===//
4838
4839 unsigned SelectionDAGISel::MakeReg(MVT VT) {
4840   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4841 }
4842
4843 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4844   AU.addRequired<AliasAnalysis>();
4845   AU.addRequired<CollectorModuleMetadata>();
4846   AU.setPreservesAll();
4847 }
4848
4849 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4850   // Get alias analysis for load/store combining.
4851   AA = &getAnalysis<AliasAnalysis>();
4852
4853   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4854   if (MF.getFunction()->hasCollector())
4855     GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4856   else
4857     GCI = 0;
4858   RegInfo = &MF.getRegInfo();
4859   DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4860
4861   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4862
4863   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4864     if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4865       // Mark landing pad.
4866       FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4867
4868   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4869     SelectBasicBlock(I, MF, FuncInfo);
4870
4871   // Add function live-ins to entry block live-in set.
4872   BasicBlock *EntryBB = &Fn.getEntryBlock();
4873   BB = FuncInfo.MBBMap[EntryBB];
4874   if (!RegInfo->livein_empty())
4875     for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4876            E = RegInfo->livein_end(); I != E; ++I)
4877       BB->addLiveIn(I->first);
4878
4879 #ifndef NDEBUG
4880   assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4881          "Not all catch info was assigned to a landing pad!");
4882 #endif
4883
4884   return true;
4885 }
4886
4887 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4888   SDOperand Op = getValue(V);
4889   assert((Op.getOpcode() != ISD::CopyFromReg ||
4890           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4891          "Copy from a reg to the same reg!");
4892   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4893
4894   RegsForValue RFV(TLI, Reg, V->getType());
4895   SDOperand Chain = DAG.getEntryNode();
4896   RFV.getCopyToRegs(Op, DAG, Chain, 0);
4897   PendingExports.push_back(Chain);
4898 }
4899
4900 void SelectionDAGISel::
4901 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4902   // If this is the entry block, emit arguments.
4903   Function &F = *LLVMBB->getParent();
4904   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4905   SDOperand OldRoot = SDL.DAG.getRoot();
4906   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4907
4908   unsigned a = 0;
4909   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4910        AI != E; ++AI) {
4911     SmallVector<MVT, 4> ValueVTs;
4912     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4913     unsigned NumValues = ValueVTs.size();
4914     if (!AI->use_empty()) {
4915       SmallVector<MVT, 4> LegalValueVTs(NumValues);
4916       for (unsigned VI = 0; VI != NumValues; ++VI) 
4917         LegalValueVTs[VI] = Args[a + VI].getValueType();
4918       SDL.setValue(AI, SDL.DAG.getNode(ISD::MERGE_VALUES,
4919                                        SDL.DAG.getVTList(&LegalValueVTs[0],
4920                                                          NumValues),
4921                                        &Args[a], NumValues));
4922       // If this argument is live outside of the entry block, insert a copy from
4923       // whereever we got it to the vreg that other BB's will reference it as.
4924       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4925       if (VMI != FuncInfo.ValueMap.end()) {
4926         SDL.CopyValueToVirtualRegister(AI, VMI->second);
4927       }
4928     }
4929     a += NumValues;
4930   }
4931
4932   // Finally, if the target has anything special to do, allow it to do so.
4933   // FIXME: this should insert code into the DAG!
4934   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4935 }
4936
4937 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4938                           MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4939   for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4940     if (isSelector(I)) {
4941       // Apply the catch info to DestBB.
4942       addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4943 #ifndef NDEBUG
4944       if (!FLI.MBBMap[SrcBB]->isLandingPad())
4945         FLI.CatchInfoFound.insert(I);
4946 #endif
4947     }
4948 }
4949
4950 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4951 /// whether object offset >= 0.
4952 static bool
4953 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4954   if (!isa<FrameIndexSDNode>(Op)) return false;
4955
4956   FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4957   int FrameIdx =  FrameIdxNode->getIndex();
4958   return MFI->isFixedObjectIndex(FrameIdx) &&
4959     MFI->getObjectOffset(FrameIdx) >= 0;
4960 }
4961
4962 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4963 /// possibly be overwritten when lowering the outgoing arguments in a tail
4964 /// call. Currently the implementation of this call is very conservative and
4965 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4966 /// virtual registers would be overwritten by direct lowering.
4967 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4968                                                     MachineFrameInfo * MFI) {
4969   RegisterSDNode * OpReg = NULL;
4970   if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4971       (Op.getOpcode()== ISD::CopyFromReg &&
4972        (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4973        (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4974       (Op.getOpcode() == ISD::LOAD &&
4975        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4976       (Op.getOpcode() == ISD::MERGE_VALUES &&
4977        Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4978        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4979                                        getOperand(1))))
4980     return true;
4981   return false;
4982 }
4983
4984 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4985 /// DAG and fixes their tailcall attribute operand.
4986 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 
4987                                            TargetLowering& TLI) {
4988   SDNode * Ret = NULL;
4989   SDOperand Terminator = DAG.getRoot();
4990
4991   // Find RET node.
4992   if (Terminator.getOpcode() == ISD::RET) {
4993     Ret = Terminator.Val;
4994   }
4995  
4996   // Fix tail call attribute of CALL nodes.
4997   for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4998          BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4999     if (BI->getOpcode() == ISD::CALL) {
5000       SDOperand OpRet(Ret, 0);
5001       SDOperand OpCall(static_cast<SDNode*>(BI), 0);
5002       bool isMarkedTailCall = 
5003         cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5004       // If CALL node has tail call attribute set to true and the call is not
5005       // eligible (no RET or the target rejects) the attribute is fixed to
5006       // false. The TargetLowering::IsEligibleForTailCallOptimization function
5007       // must correctly identify tail call optimizable calls.
5008       if (!isMarkedTailCall) continue;
5009       if (Ret==NULL ||
5010           !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5011         // Not eligible. Mark CALL node as non tail call.
5012         SmallVector<SDOperand, 32> Ops;
5013         unsigned idx=0;
5014         for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5015               E = OpCall.Val->op_end(); I != E; I++, idx++) {
5016           if (idx!=3)
5017             Ops.push_back(*I);
5018           else
5019             Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5020         }
5021         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5022       } else {
5023         // Look for tail call clobbered arguments. Emit a series of
5024         // copyto/copyfrom virtual register nodes to protect them.
5025         SmallVector<SDOperand, 32> Ops;
5026         SDOperand Chain = OpCall.getOperand(0), InFlag;
5027         unsigned idx=0;
5028         for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5029               E = OpCall.Val->op_end(); I != E; I++, idx++) {
5030           SDOperand Arg = *I;
5031           if (idx > 4 && (idx % 2)) {
5032             bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5033               getArgFlags().isByVal();
5034             MachineFunction &MF = DAG.getMachineFunction();
5035             MachineFrameInfo *MFI = MF.getFrameInfo();
5036             if (!isByVal &&
5037                 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
5038               MVT VT = Arg.getValueType();
5039               unsigned VReg = MF.getRegInfo().
5040                 createVirtualRegister(TLI.getRegClassFor(VT));
5041               Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5042               InFlag = Chain.getValue(1);
5043               Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5044               Chain = Arg.getValue(1);
5045               InFlag = Arg.getValue(2);
5046             }
5047           }
5048           Ops.push_back(Arg);
5049         }
5050         // Link in chain of CopyTo/CopyFromReg.
5051         Ops[0] = Chain;
5052         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5053       }
5054     }
5055   }
5056 }
5057
5058 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5059        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5060                                          FunctionLoweringInfo &FuncInfo) {
5061   SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
5062
5063   // Lower any arguments needed in this block if this is the entry block.
5064   if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
5065     LowerArguments(LLVMBB, SDL);
5066
5067   BB = FuncInfo.MBBMap[LLVMBB];
5068   SDL.setCurrentBasicBlock(BB);
5069
5070   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
5071
5072   if (MMI && BB->isLandingPad()) {
5073     // Add a label to mark the beginning of the landing pad.  Deletion of the
5074     // landing pad can thus be detected via the MachineModuleInfo.
5075     unsigned LabelID = MMI->addLandingPad(BB);
5076     DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
5077                             DAG.getConstant(LabelID, MVT::i32),
5078                             DAG.getConstant(1, MVT::i32)));
5079
5080     // Mark exception register as live in.
5081     unsigned Reg = TLI.getExceptionAddressRegister();
5082     if (Reg) BB->addLiveIn(Reg);
5083
5084     // Mark exception selector register as live in.
5085     Reg = TLI.getExceptionSelectorRegister();
5086     if (Reg) BB->addLiveIn(Reg);
5087
5088     // FIXME: Hack around an exception handling flaw (PR1508): the personality
5089     // function and list of typeids logically belong to the invoke (or, if you
5090     // like, the basic block containing the invoke), and need to be associated
5091     // with it in the dwarf exception handling tables.  Currently however the
5092     // information is provided by an intrinsic (eh.selector) that can be moved
5093     // to unexpected places by the optimizers: if the unwind edge is critical,
5094     // then breaking it can result in the intrinsics being in the successor of
5095     // the landing pad, not the landing pad itself.  This results in exceptions
5096     // not being caught because no typeids are associated with the invoke.
5097     // This may not be the only way things can go wrong, but it is the only way
5098     // we try to work around for the moment.
5099     BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5100
5101     if (Br && Br->isUnconditional()) { // Critical edge?
5102       BasicBlock::iterator I, E;
5103       for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5104         if (isSelector(I))
5105           break;
5106
5107       if (I == E)
5108         // No catch info found - try to extract some from the successor.
5109         copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
5110     }
5111   }
5112
5113   // Lower all of the non-terminator instructions.
5114   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5115        I != E; ++I)
5116     SDL.visit(*I);
5117
5118   // Ensure that all instructions which are used outside of their defining
5119   // blocks are available as virtual registers.  Invoke is handled elsewhere.
5120   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
5121     if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5122       DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
5123       if (VMI != FuncInfo.ValueMap.end())
5124         SDL.CopyValueToVirtualRegister(I, VMI->second);
5125     }
5126
5127   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5128   // ensure constants are generated when needed.  Remember the virtual registers
5129   // that need to be added to the Machine PHI nodes as input.  We cannot just
5130   // directly add them, because expansion might result in multiple MBB's for one
5131   // BB.  As such, the start of the BB might correspond to a different MBB than
5132   // the end.
5133   //
5134   TerminatorInst *TI = LLVMBB->getTerminator();
5135
5136   // Emit constants only once even if used by multiple PHI nodes.
5137   std::map<Constant*, unsigned> ConstantsOut;
5138   
5139   // Vector bool would be better, but vector<bool> is really slow.
5140   std::vector<unsigned char> SuccsHandled;
5141   if (TI->getNumSuccessors())
5142     SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5143     
5144   // Check successor nodes' PHI nodes that expect a constant to be available
5145   // from this block.
5146   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5147     BasicBlock *SuccBB = TI->getSuccessor(succ);
5148     if (!isa<PHINode>(SuccBB->begin())) continue;
5149     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
5150     
5151     // If this terminator has multiple identical successors (common for
5152     // switches), only handle each succ once.
5153     unsigned SuccMBBNo = SuccMBB->getNumber();
5154     if (SuccsHandled[SuccMBBNo]) continue;
5155     SuccsHandled[SuccMBBNo] = true;
5156     
5157     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5158     PHINode *PN;
5159
5160     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5161     // nodes and Machine PHI nodes, but the incoming operands have not been
5162     // emitted yet.
5163     for (BasicBlock::iterator I = SuccBB->begin();
5164          (PN = dyn_cast<PHINode>(I)); ++I) {
5165       // Ignore dead phi's.
5166       if (PN->use_empty()) continue;
5167       
5168       unsigned Reg;
5169       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5170       
5171       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5172         unsigned &RegOut = ConstantsOut[C];
5173         if (RegOut == 0) {
5174           RegOut = FuncInfo.CreateRegForValue(C);
5175           SDL.CopyValueToVirtualRegister(C, RegOut);
5176         }
5177         Reg = RegOut;
5178       } else {
5179         Reg = FuncInfo.ValueMap[PHIOp];
5180         if (Reg == 0) {
5181           assert(isa<AllocaInst>(PHIOp) &&
5182                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5183                  "Didn't codegen value into a register!??");
5184           Reg = FuncInfo.CreateRegForValue(PHIOp);
5185           SDL.CopyValueToVirtualRegister(PHIOp, Reg);
5186         }
5187       }
5188
5189       // Remember that this register needs to added to the machine PHI node as
5190       // the input for this MBB.
5191       MVT VT = TLI.getValueType(PN->getType());
5192       unsigned NumRegisters = TLI.getNumRegisters(VT);
5193       for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5194         PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5195     }
5196   }
5197   ConstantsOut.clear();
5198
5199   // Lower the terminator after the copies are emitted.
5200   SDL.visit(*LLVMBB->getTerminator());
5201
5202   // Copy over any CaseBlock records that may now exist due to SwitchInst
5203   // lowering, as well as any jump table information.
5204   SwitchCases.clear();
5205   SwitchCases = SDL.SwitchCases;
5206   JTCases.clear();
5207   JTCases = SDL.JTCases;
5208   BitTestCases.clear();
5209   BitTestCases = SDL.BitTestCases;
5210     
5211   // Make sure the root of the DAG is up-to-date.
5212   DAG.setRoot(SDL.getControlRoot());
5213
5214   // Check whether calls in this block are real tail calls. Fix up CALL nodes
5215   // with correct tailcall attribute so that the target can rely on the tailcall
5216   // attribute indicating whether the call is really eligible for tail call
5217   // optimization.
5218   CheckDAGForTailCallsAndFixThem(DAG, TLI);
5219 }
5220
5221 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
5222   DOUT << "Lowered selection DAG:\n";
5223   DEBUG(DAG.dump());
5224
5225   // Run the DAG combiner in pre-legalize mode.
5226   DAG.Combine(false, *AA);
5227   
5228   DOUT << "Optimized lowered selection DAG:\n";
5229   DEBUG(DAG.dump());
5230   
5231   // Second step, hack on the DAG until it only uses operations and types that
5232   // the target supports.
5233 #if 0  // Enable this some day.
5234   DAG.LegalizeTypes();
5235   // Someday even later, enable a dag combine pass here.
5236 #endif
5237   DAG.Legalize();
5238   
5239   DOUT << "Legalized selection DAG:\n";
5240   DEBUG(DAG.dump());
5241   
5242   // Run the DAG combiner in post-legalize mode.
5243   DAG.Combine(true, *AA);
5244   
5245   DOUT << "Optimized legalized selection DAG:\n";
5246   DEBUG(DAG.dump());
5247
5248   if (ViewISelDAGs) DAG.viewGraph();
5249
5250   // Third, instruction select all of the operations to machine code, adding the
5251   // code to the MachineBasicBlock.
5252   InstructionSelectBasicBlock(DAG);
5253   
5254   DOUT << "Selected machine code:\n";
5255   DEBUG(BB->dump());
5256 }  
5257
5258 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5259                                         FunctionLoweringInfo &FuncInfo) {
5260   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5261   {
5262     SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5263     CurDAG = &DAG;
5264   
5265     // First step, lower LLVM code to some DAG.  This DAG may use operations and
5266     // types that are not supported by the target.
5267     BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5268
5269     // Second step, emit the lowered DAG as machine code.
5270     CodeGenAndEmitDAG(DAG);
5271   }
5272
5273   DOUT << "Total amount of phi nodes to update: "
5274        << PHINodesToUpdate.size() << "\n";
5275   DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5276           DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5277                << ", " << PHINodesToUpdate[i].second << ")\n";);
5278   
5279   // Next, now that we know what the last MBB the LLVM BB expanded is, update
5280   // PHI nodes in successors.
5281   if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
5282     for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5283       MachineInstr *PHI = PHINodesToUpdate[i].first;
5284       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5285              "This is not a machine PHI node that we are updating!");
5286       PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5287                                                 false));
5288       PHI->addOperand(MachineOperand::CreateMBB(BB));
5289     }
5290     return;
5291   }
5292
5293   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5294     // Lower header first, if it wasn't already lowered
5295     if (!BitTestCases[i].Emitted) {
5296       SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5297       CurDAG = &HSDAG;
5298       SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5299       // Set the current basic block to the mbb we wish to insert the code into
5300       BB = BitTestCases[i].Parent;
5301       HSDL.setCurrentBasicBlock(BB);
5302       // Emit the code
5303       HSDL.visitBitTestHeader(BitTestCases[i]);
5304       HSDAG.setRoot(HSDL.getRoot());
5305       CodeGenAndEmitDAG(HSDAG);
5306     }    
5307
5308     for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5309       SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5310       CurDAG = &BSDAG;
5311       SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5312       // Set the current basic block to the mbb we wish to insert the code into
5313       BB = BitTestCases[i].Cases[j].ThisBB;
5314       BSDL.setCurrentBasicBlock(BB);
5315       // Emit the code
5316       if (j+1 != ej)
5317         BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5318                               BitTestCases[i].Reg,
5319                               BitTestCases[i].Cases[j]);
5320       else
5321         BSDL.visitBitTestCase(BitTestCases[i].Default,
5322                               BitTestCases[i].Reg,
5323                               BitTestCases[i].Cases[j]);
5324         
5325         
5326       BSDAG.setRoot(BSDL.getRoot());
5327       CodeGenAndEmitDAG(BSDAG);
5328     }
5329
5330     // Update PHI Nodes
5331     for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5332       MachineInstr *PHI = PHINodesToUpdate[pi].first;
5333       MachineBasicBlock *PHIBB = PHI->getParent();
5334       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5335              "This is not a machine PHI node that we are updating!");
5336       // This is "default" BB. We have two jumps to it. From "header" BB and
5337       // from last "case" BB.
5338       if (PHIBB == BitTestCases[i].Default) {
5339         PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5340                                                   false));
5341         PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5342         PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5343                                                   false));
5344         PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5345                                                   back().ThisBB));
5346       }
5347       // One of "cases" BB.
5348       for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5349         MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5350         if (cBB->succ_end() !=
5351             std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5352           PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5353                                                     false));
5354           PHI->addOperand(MachineOperand::CreateMBB(cBB));
5355         }
5356       }
5357     }
5358   }
5359
5360   // If the JumpTable record is filled in, then we need to emit a jump table.
5361   // Updating the PHI nodes is tricky in this case, since we need to determine
5362   // whether the PHI is a successor of the range check MBB or the jump table MBB
5363   for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5364     // Lower header first, if it wasn't already lowered
5365     if (!JTCases[i].first.Emitted) {
5366       SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5367       CurDAG = &HSDAG;
5368       SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5369       // Set the current basic block to the mbb we wish to insert the code into
5370       BB = JTCases[i].first.HeaderBB;
5371       HSDL.setCurrentBasicBlock(BB);
5372       // Emit the code
5373       HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5374       HSDAG.setRoot(HSDL.getRoot());
5375       CodeGenAndEmitDAG(HSDAG);
5376     }
5377     
5378     SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5379     CurDAG = &JSDAG;
5380     SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5381     // Set the current basic block to the mbb we wish to insert the code into
5382     BB = JTCases[i].second.MBB;
5383     JSDL.setCurrentBasicBlock(BB);
5384     // Emit the code
5385     JSDL.visitJumpTable(JTCases[i].second);
5386     JSDAG.setRoot(JSDL.getRoot());
5387     CodeGenAndEmitDAG(JSDAG);
5388     
5389     // Update PHI Nodes
5390     for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5391       MachineInstr *PHI = PHINodesToUpdate[pi].first;
5392       MachineBasicBlock *PHIBB = PHI->getParent();
5393       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5394              "This is not a machine PHI node that we are updating!");
5395       // "default" BB. We can go there only from header BB.
5396       if (PHIBB == JTCases[i].second.Default) {
5397         PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5398                                                   false));
5399         PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5400       }
5401       // JT BB. Just iterate over successors here
5402       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5403         PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5404                                                   false));
5405         PHI->addOperand(MachineOperand::CreateMBB(BB));
5406       }
5407     }
5408   }
5409   
5410   // If the switch block involved a branch to one of the actual successors, we
5411   // need to update PHI nodes in that block.
5412   for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5413     MachineInstr *PHI = PHINodesToUpdate[i].first;
5414     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5415            "This is not a machine PHI node that we are updating!");
5416     if (BB->isSuccessor(PHI->getParent())) {
5417       PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5418                                                 false));
5419       PHI->addOperand(MachineOperand::CreateMBB(BB));
5420     }
5421   }
5422   
5423   // If we generated any switch lowering information, build and codegen any
5424   // additional DAGs necessary.
5425   for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5426     SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5427     CurDAG = &SDAG;
5428     SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5429     
5430     // Set the current basic block to the mbb we wish to insert the code into
5431     BB = SwitchCases[i].ThisBB;
5432     SDL.setCurrentBasicBlock(BB);
5433     
5434     // Emit the code
5435     SDL.visitSwitchCase(SwitchCases[i]);
5436     SDAG.setRoot(SDL.getRoot());
5437     CodeGenAndEmitDAG(SDAG);
5438     
5439     // Handle any PHI nodes in successors of this chunk, as if we were coming
5440     // from the original BB before switch expansion.  Note that PHI nodes can
5441     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
5442     // handle them the right number of times.
5443     while ((BB = SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
5444       for (MachineBasicBlock::iterator Phi = BB->begin();
5445            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5446         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5447         for (unsigned pn = 0; ; ++pn) {
5448           assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5449           if (PHINodesToUpdate[pn].first == Phi) {
5450             Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5451                                                       second, false));
5452             Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5453             break;
5454           }
5455         }
5456       }
5457       
5458       // Don't process RHS if same block as LHS.
5459       if (BB == SwitchCases[i].FalseBB)
5460         SwitchCases[i].FalseBB = 0;
5461       
5462       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
5463       SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5464       SwitchCases[i].FalseBB = 0;
5465     }
5466     assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5467   }
5468 }
5469
5470
5471 //===----------------------------------------------------------------------===//
5472 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5473 /// target node in the graph.
5474 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5475   if (ViewSchedDAGs) DAG.viewGraph();
5476
5477   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5478   
5479   if (!Ctor) {
5480     Ctor = ISHeuristic;
5481     RegisterScheduler::setDefault(Ctor);
5482   }
5483   
5484   ScheduleDAG *SL = Ctor(this, &DAG, BB);
5485   BB = SL->Run();
5486
5487   if (ViewSUnitDAGs) SL->viewGraph();
5488
5489   delete SL;
5490 }
5491
5492
5493 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5494   return new HazardRecognizer();
5495 }
5496
5497 //===----------------------------------------------------------------------===//
5498 // Helper functions used by the generated instruction selector.
5499 //===----------------------------------------------------------------------===//
5500 // Calls to these methods are generated by tblgen.
5501
5502 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
5503 /// the dag combiner simplified the 255, we still want to match.  RHS is the
5504 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5505 /// specified in the .td file (e.g. 255).
5506 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS, 
5507                                     int64_t DesiredMaskS) const {
5508   const APInt &ActualMask = RHS->getAPIntValue();
5509   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5510   
5511   // If the actual mask exactly matches, success!
5512   if (ActualMask == DesiredMask)
5513     return true;
5514   
5515   // If the actual AND mask is allowing unallowed bits, this doesn't match.
5516   if (ActualMask.intersects(~DesiredMask))
5517     return false;
5518   
5519   // Otherwise, the DAG Combiner may have proven that the value coming in is
5520   // either already zero or is not demanded.  Check for known zero input bits.
5521   APInt NeededMask = DesiredMask & ~ActualMask;
5522   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5523     return true;
5524   
5525   // TODO: check to see if missing bits are just not demanded.
5526
5527   // Otherwise, this pattern doesn't match.
5528   return false;
5529 }
5530
5531 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
5532 /// the dag combiner simplified the 255, we still want to match.  RHS is the
5533 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5534 /// specified in the .td file (e.g. 255).
5535 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS, 
5536                                    int64_t DesiredMaskS) const {
5537   const APInt &ActualMask = RHS->getAPIntValue();
5538   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5539   
5540   // If the actual mask exactly matches, success!
5541   if (ActualMask == DesiredMask)
5542     return true;
5543   
5544   // If the actual AND mask is allowing unallowed bits, this doesn't match.
5545   if (ActualMask.intersects(~DesiredMask))
5546     return false;
5547   
5548   // Otherwise, the DAG Combiner may have proven that the value coming in is
5549   // either already zero or is not demanded.  Check for known zero input bits.
5550   APInt NeededMask = DesiredMask & ~ActualMask;
5551   
5552   APInt KnownZero, KnownOne;
5553   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5554   
5555   // If all the missing bits in the or are already known to be set, match!
5556   if ((NeededMask & KnownOne) == NeededMask)
5557     return true;
5558   
5559   // TODO: check to see if missing bits are just not demanded.
5560   
5561   // Otherwise, this pattern doesn't match.
5562   return false;
5563 }
5564
5565
5566 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5567 /// by tblgen.  Others should not call it.
5568 void SelectionDAGISel::
5569 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5570   std::vector<SDOperand> InOps;
5571   std::swap(InOps, Ops);
5572
5573   Ops.push_back(InOps[0]);  // input chain.
5574   Ops.push_back(InOps[1]);  // input asm string.
5575
5576   unsigned i = 2, e = InOps.size();
5577   if (InOps[e-1].getValueType() == MVT::Flag)
5578     --e;  // Don't process a flag operand if it is here.
5579   
5580   while (i != e) {
5581     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5582     if ((Flags & 7) != 4 /*MEM*/) {
5583       // Just skip over this operand, copying the operands verbatim.
5584       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5585       i += (Flags >> 3) + 1;
5586     } else {
5587       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5588       // Otherwise, this is a memory operand.  Ask the target to select it.
5589       std::vector<SDOperand> SelOps;
5590       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5591         cerr << "Could not match memory address.  Inline asm failure!\n";
5592         exit(1);
5593       }
5594       
5595       // Add this to the output node.
5596       MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5597       Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5598                                           IntPtrTy));
5599       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5600       i += 2;
5601     }
5602   }
5603   
5604   // Add the flag input back if present.
5605   if (e != InOps.size())
5606     Ops.push_back(InOps.back());
5607 }
5608
5609 char SelectionDAGISel::ID = 0;