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