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