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