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