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