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