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