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