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