SelectionDAGISel.cpp revision a844126c43976387a66dafbe5137a762169f1f34
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/CodeGen/SelectionDAGISel.h"
16#include "llvm/CodeGen/ScheduleDAG.h"
17#include "llvm/CallingConv.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/InlineAsm.h"
23#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/IntrinsicInst.h"
26#include "llvm/CodeGen/IntrinsicLowering.h"
27#include "llvm/CodeGen/MachineDebugInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineJumpTableInfo.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/CodeGen/SSARegMap.h"
34#include "llvm/Target/MRegisterInfo.h"
35#include "llvm/Target/TargetData.h"
36#include "llvm/Target/TargetFrameInfo.h"
37#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetOptions.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Debug.h"
45#include <map>
46#include <set>
47#include <iostream>
48#include <algorithm>
49using namespace llvm;
50
51#ifndef NDEBUG
52static cl::opt<bool>
53ViewISelDAGs("view-isel-dags", cl::Hidden,
54          cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57          cl::desc("Pop up a window to show sched dags as they are processed"));
58#else
59static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
60#endif
61
62// Scheduling heuristics
63enum SchedHeuristics {
64  defaultScheduling,      // Let the target specify its preference.
65  noScheduling,           // No scheduling, emit breadth first sequence.
66  simpleScheduling,       // Two pass, min. critical path, max. utilization.
67  simpleNoItinScheduling, // Same as above exact using generic latency.
68  listSchedulingBURR,     // Bottom-up reg reduction list scheduling.
69  listSchedulingTDRR,     // Top-down reg reduction list scheduling.
70  listSchedulingTD        // Top-down list scheduler.
71};
72
73namespace {
74  cl::opt<SchedHeuristics>
75  ISHeuristic(
76    "sched",
77    cl::desc("Choose scheduling style"),
78    cl::init(defaultScheduling),
79    cl::values(
80      clEnumValN(defaultScheduling, "default",
81                 "Target preferred scheduling style"),
82      clEnumValN(noScheduling, "none",
83                 "No scheduling: breadth first sequencing"),
84      clEnumValN(simpleScheduling, "simple",
85                 "Simple two pass scheduling: minimize critical path "
86                 "and maximize processor utilization"),
87      clEnumValN(simpleNoItinScheduling, "simple-noitin",
88                 "Simple two pass scheduling: Same as simple "
89                 "except using generic latency"),
90      clEnumValN(listSchedulingBURR, "list-burr",
91                 "Bottom-up register reduction list scheduling"),
92      clEnumValN(listSchedulingTDRR, "list-tdrr",
93                 "Top-down register reduction list scheduling"),
94      clEnumValN(listSchedulingTD, "list-td",
95                 "Top-down list scheduler"),
96      clEnumValEnd));
97} // namespace
98
99namespace {
100  /// RegsForValue - This struct represents the physical registers that a
101  /// particular value is assigned and the type information about the value.
102  /// This is needed because values can be promoted into larger registers and
103  /// expanded into multiple smaller registers than the value.
104  struct RegsForValue {
105    /// Regs - This list hold the register (for legal and promoted values)
106    /// or register set (for expanded values) that the value should be assigned
107    /// to.
108    std::vector<unsigned> Regs;
109
110    /// RegVT - The value type of each register.
111    ///
112    MVT::ValueType RegVT;
113
114    /// ValueVT - The value type of the LLVM value, which may be promoted from
115    /// RegVT or made from merging the two expanded parts.
116    MVT::ValueType ValueVT;
117
118    RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
119
120    RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
121      : RegVT(regvt), ValueVT(valuevt) {
122        Regs.push_back(Reg);
123    }
124    RegsForValue(const std::vector<unsigned> &regs,
125                 MVT::ValueType regvt, MVT::ValueType valuevt)
126      : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
127    }
128
129    /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
130    /// this value and returns the result as a ValueVT value.  This uses
131    /// Chain/Flag as the input and updates them for the output Chain/Flag.
132    SDOperand getCopyFromRegs(SelectionDAG &DAG,
133                              SDOperand &Chain, SDOperand &Flag) const;
134
135    /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
136    /// specified value into the registers specified by this object.  This uses
137    /// Chain/Flag as the input and updates them for the output Chain/Flag.
138    void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
139                       SDOperand &Chain, SDOperand &Flag,
140                       MVT::ValueType PtrVT) const;
141
142    /// AddInlineAsmOperands - Add this value to the specified inlineasm node
143    /// operand list.  This adds the code marker and includes the number of
144    /// values added into it.
145    void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
146                              std::vector<SDOperand> &Ops) const;
147  };
148}
149
150namespace llvm {
151  //===--------------------------------------------------------------------===//
152  /// FunctionLoweringInfo - This contains information that is global to a
153  /// function that is used when lowering a region of the function.
154  class FunctionLoweringInfo {
155  public:
156    TargetLowering &TLI;
157    Function &Fn;
158    MachineFunction &MF;
159    SSARegMap *RegMap;
160
161    FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
162
163    /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
164    std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
165
166    /// ValueMap - Since we emit code for the function a basic block at a time,
167    /// we must remember which virtual registers hold the values for
168    /// cross-basic-block values.
169    std::map<const Value*, unsigned> ValueMap;
170
171    /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
172    /// the entry block.  This allows the allocas to be efficiently referenced
173    /// anywhere in the function.
174    std::map<const AllocaInst*, int> StaticAllocaMap;
175
176    unsigned MakeReg(MVT::ValueType VT) {
177      return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
178    }
179
180    unsigned CreateRegForValue(const Value *V);
181
182    unsigned InitializeRegForValue(const Value *V) {
183      unsigned &R = ValueMap[V];
184      assert(R == 0 && "Already initialized this value register!");
185      return R = CreateRegForValue(V);
186    }
187  };
188}
189
190/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
191/// PHI nodes or outside of the basic block that defines it, or used by a
192/// switch instruction, which may expand to multiple basic blocks.
193static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
194  if (isa<PHINode>(I)) return true;
195  BasicBlock *BB = I->getParent();
196  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
197    if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
198        isa<SwitchInst>(*UI))
199      return true;
200  return false;
201}
202
203/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
204/// entry block, return true.  This includes arguments used by switches, since
205/// the switch may expand into multiple basic blocks.
206static bool isOnlyUsedInEntryBlock(Argument *A) {
207  BasicBlock *Entry = A->getParent()->begin();
208  for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
209    if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
210      return false;  // Use not in entry block.
211  return true;
212}
213
214FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
215                                           Function &fn, MachineFunction &mf)
216    : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
217
218  // Create a vreg for each argument register that is not dead and is used
219  // outside of the entry block for the function.
220  for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
221       AI != E; ++AI)
222    if (!isOnlyUsedInEntryBlock(AI))
223      InitializeRegForValue(AI);
224
225  // Initialize the mapping of values to registers.  This is only set up for
226  // instruction values that are used outside of the block that defines
227  // them.
228  Function::iterator BB = Fn.begin(), EB = Fn.end();
229  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
230    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
231      if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
232        const Type *Ty = AI->getAllocatedType();
233        uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
234        unsigned Align =
235          std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
236                   AI->getAlignment());
237
238        // If the alignment of the value is smaller than the size of the value,
239        // and if the size of the value is particularly small (<= 8 bytes),
240        // round up to the size of the value for potentially better performance.
241        //
242        // FIXME: This could be made better with a preferred alignment hook in
243        // TargetData.  It serves primarily to 8-byte align doubles for X86.
244        if (Align < TySize && TySize <= 8) Align = TySize;
245        TySize *= CUI->getValue();   // Get total allocated size.
246        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
247        StaticAllocaMap[AI] =
248          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
249      }
250
251  for (; BB != EB; ++BB)
252    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
253      if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
254        if (!isa<AllocaInst>(I) ||
255            !StaticAllocaMap.count(cast<AllocaInst>(I)))
256          InitializeRegForValue(I);
257
258  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
259  // also creates the initial PHI MachineInstrs, though none of the input
260  // operands are populated.
261  for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
262    MachineBasicBlock *MBB = new MachineBasicBlock(BB);
263    MBBMap[BB] = MBB;
264    MF.getBasicBlockList().push_back(MBB);
265
266    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
267    // appropriate.
268    PHINode *PN;
269    for (BasicBlock::iterator I = BB->begin();
270         (PN = dyn_cast<PHINode>(I)); ++I)
271      if (!PN->use_empty()) {
272        MVT::ValueType VT = TLI.getValueType(PN->getType());
273        unsigned NumElements;
274        if (VT != MVT::Vector)
275          NumElements = TLI.getNumElements(VT);
276        else {
277          MVT::ValueType VT1,VT2;
278          NumElements =
279            TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
280                                       VT1, VT2);
281        }
282        unsigned PHIReg = ValueMap[PN];
283        assert(PHIReg &&"PHI node does not have an assigned virtual register!");
284        for (unsigned i = 0; i != NumElements; ++i)
285          BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
286      }
287  }
288}
289
290/// CreateRegForValue - Allocate the appropriate number of virtual registers of
291/// the correctly promoted or expanded types.  Assign these registers
292/// consecutive vreg numbers and return the first assigned number.
293unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
294  MVT::ValueType VT = TLI.getValueType(V->getType());
295
296  // The number of multiples of registers that we need, to, e.g., split up
297  // a <2 x int64> -> 4 x i32 registers.
298  unsigned NumVectorRegs = 1;
299
300  // If this is a packed type, figure out what type it will decompose into
301  // and how many of the elements it will use.
302  if (VT == MVT::Vector) {
303    const PackedType *PTy = cast<PackedType>(V->getType());
304    unsigned NumElts = PTy->getNumElements();
305    MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
306
307    // Divide the input until we get to a supported size.  This will always
308    // end with a scalar if the target doesn't support vectors.
309    while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
310      NumElts >>= 1;
311      NumVectorRegs <<= 1;
312    }
313    if (NumElts == 1)
314      VT = EltTy;
315    else
316      VT = getVectorType(EltTy, NumElts);
317  }
318
319  // The common case is that we will only create one register for this
320  // value.  If we have that case, create and return the virtual register.
321  unsigned NV = TLI.getNumElements(VT);
322  if (NV == 1) {
323    // If we are promoting this value, pick the next largest supported type.
324    MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
325    unsigned Reg = MakeReg(PromotedType);
326    // If this is a vector of supported or promoted types (e.g. 4 x i16),
327    // create all of the registers.
328    for (unsigned i = 1; i != NumVectorRegs; ++i)
329      MakeReg(PromotedType);
330    return Reg;
331  }
332
333  // If this value is represented with multiple target registers, make sure
334  // to create enough consecutive registers of the right (smaller) type.
335  unsigned NT = VT-1;  // Find the type to use.
336  while (TLI.getNumElements((MVT::ValueType)NT) != 1)
337    --NT;
338
339  unsigned R = MakeReg((MVT::ValueType)NT);
340  for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
341    MakeReg((MVT::ValueType)NT);
342  return R;
343}
344
345//===----------------------------------------------------------------------===//
346/// SelectionDAGLowering - This is the common target-independent lowering
347/// implementation that is parameterized by a TargetLowering object.
348/// Also, targets can overload any lowering method.
349///
350namespace llvm {
351class SelectionDAGLowering {
352  MachineBasicBlock *CurMBB;
353
354  std::map<const Value*, SDOperand> NodeMap;
355
356  /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
357  /// them up and then emit token factor nodes when possible.  This allows us to
358  /// get simple disambiguation between loads without worrying about alias
359  /// analysis.
360  std::vector<SDOperand> PendingLoads;
361
362  /// Case - A pair of values to record the Value for a switch case, and the
363  /// case's target basic block.
364  typedef std::pair<Constant*, MachineBasicBlock*> Case;
365  typedef std::vector<Case>::iterator              CaseItr;
366  typedef std::pair<CaseItr, CaseItr>              CaseRange;
367
368  /// CaseRec - A struct with ctor used in lowering switches to a binary tree
369  /// of conditional branches.
370  struct CaseRec {
371    CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
372    CaseBB(bb), LT(lt), GE(ge), Range(r) {}
373
374    /// CaseBB - The MBB in which to emit the compare and branch
375    MachineBasicBlock *CaseBB;
376    /// LT, GE - If nonzero, we know the current case value must be less-than or
377    /// greater-than-or-equal-to these Constants.
378    Constant *LT;
379    Constant *GE;
380    /// Range - A pair of iterators representing the range of case values to be
381    /// processed at this point in the binary search tree.
382    CaseRange Range;
383  };
384
385  /// The comparison function for sorting Case values.
386  struct CaseCmp {
387    bool operator () (const Case& C1, const Case& C2) {
388      if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
389        return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
390
391      const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
392      return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
393    }
394  };
395
396public:
397  // TLI - This is information that describes the available target features we
398  // need for lowering.  This indicates when operations are unavailable,
399  // implemented with a libcall, etc.
400  TargetLowering &TLI;
401  SelectionDAG &DAG;
402  const TargetData *TD;
403
404  /// SwitchCases - Vector of CaseBlock structures used to communicate
405  /// SwitchInst code generation information.
406  std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
407  SelectionDAGISel::JumpTable JT;
408
409  /// FuncInfo - Information about the function as a whole.
410  ///
411  FunctionLoweringInfo &FuncInfo;
412
413  SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
414                       FunctionLoweringInfo &funcinfo)
415    : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
416      JT(0,0,0,0), FuncInfo(funcinfo) {
417  }
418
419  /// getRoot - Return the current virtual root of the Selection DAG.
420  ///
421  SDOperand getRoot() {
422    if (PendingLoads.empty())
423      return DAG.getRoot();
424
425    if (PendingLoads.size() == 1) {
426      SDOperand Root = PendingLoads[0];
427      DAG.setRoot(Root);
428      PendingLoads.clear();
429      return Root;
430    }
431
432    // Otherwise, we have to make a token factor node.
433    SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
434    PendingLoads.clear();
435    DAG.setRoot(Root);
436    return Root;
437  }
438
439  void visit(Instruction &I) { visit(I.getOpcode(), I); }
440
441  void visit(unsigned Opcode, User &I) {
442    switch (Opcode) {
443    default: assert(0 && "Unknown instruction type encountered!");
444             abort();
445      // Build the switch statement using the Instruction.def file.
446#define HANDLE_INST(NUM, OPCODE, CLASS) \
447    case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
448#include "llvm/Instruction.def"
449    }
450  }
451
452  void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
453
454  SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
455                        SDOperand SrcValue, SDOperand Root,
456                        bool isVolatile);
457
458  SDOperand getIntPtrConstant(uint64_t Val) {
459    return DAG.getConstant(Val, TLI.getPointerTy());
460  }
461
462  SDOperand getValue(const Value *V);
463
464  const SDOperand &setValue(const Value *V, SDOperand NewN) {
465    SDOperand &N = NodeMap[V];
466    assert(N.Val == 0 && "Already set a value for this node!");
467    return N = NewN;
468  }
469
470  RegsForValue GetRegistersForValue(const std::string &ConstrCode,
471                                    MVT::ValueType VT,
472                                    bool OutReg, bool InReg,
473                                    std::set<unsigned> &OutputRegs,
474                                    std::set<unsigned> &InputRegs);
475
476  // Terminator instructions.
477  void visitRet(ReturnInst &I);
478  void visitBr(BranchInst &I);
479  void visitSwitch(SwitchInst &I);
480  void visitUnreachable(UnreachableInst &I) { /* noop */ }
481
482  // Helper for visitSwitch
483  void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
484  void visitJumpTable(SelectionDAGISel::JumpTable &JT);
485
486  // These all get lowered before this pass.
487  void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
488  void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
489
490  void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
491  void visitShift(User &I, unsigned Opcode);
492  void visitAdd(User &I) {
493    visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
494  }
495  void visitSub(User &I);
496  void visitMul(User &I) {
497    visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
498  }
499  void visitDiv(User &I) {
500    const Type *Ty = I.getType();
501    visitBinary(I,
502                Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
503                Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
504  }
505  void visitRem(User &I) {
506    const Type *Ty = I.getType();
507    visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
508  }
509  void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
510  void visitOr (User &I) { visitBinary(I, ISD::OR,  0, ISD::VOR); }
511  void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
512  void visitShl(User &I) { visitShift(I, ISD::SHL); }
513  void visitShr(User &I) {
514    visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
515  }
516
517  void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
518                  ISD::CondCode FPOpc);
519  void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
520                                        ISD::SETOEQ); }
521  void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
522                                        ISD::SETUNE); }
523  void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
524                                        ISD::SETOLE); }
525  void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
526                                        ISD::SETOGE); }
527  void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
528                                        ISD::SETOLT); }
529  void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
530                                        ISD::SETOGT); }
531
532  void visitExtractElement(User &I);
533  void visitInsertElement(User &I);
534  void visitShuffleVector(User &I);
535
536  void visitGetElementPtr(User &I);
537  void visitCast(User &I);
538  void visitSelect(User &I);
539
540  void visitMalloc(MallocInst &I);
541  void visitFree(FreeInst &I);
542  void visitAlloca(AllocaInst &I);
543  void visitLoad(LoadInst &I);
544  void visitStore(StoreInst &I);
545  void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
546  void visitCall(CallInst &I);
547  void visitInlineAsm(CallInst &I);
548  const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
549  void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
550
551  void visitVAStart(CallInst &I);
552  void visitVAArg(VAArgInst &I);
553  void visitVAEnd(CallInst &I);
554  void visitVACopy(CallInst &I);
555  void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
556
557  void visitMemIntrinsic(CallInst &I, unsigned Op);
558
559  void visitUserOp1(Instruction &I) {
560    assert(0 && "UserOp1 should not exist at instruction selection time!");
561    abort();
562  }
563  void visitUserOp2(Instruction &I) {
564    assert(0 && "UserOp2 should not exist at instruction selection time!");
565    abort();
566  }
567};
568} // end namespace llvm
569
570SDOperand SelectionDAGLowering::getValue(const Value *V) {
571  SDOperand &N = NodeMap[V];
572  if (N.Val) return N;
573
574  const Type *VTy = V->getType();
575  MVT::ValueType VT = TLI.getValueType(VTy);
576  if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
577    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
578      visit(CE->getOpcode(), *CE);
579      assert(N.Val && "visit didn't populate the ValueMap!");
580      return N;
581    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
582      return N = DAG.getGlobalAddress(GV, VT);
583    } else if (isa<ConstantPointerNull>(C)) {
584      return N = DAG.getConstant(0, TLI.getPointerTy());
585    } else if (isa<UndefValue>(C)) {
586      if (!isa<PackedType>(VTy))
587        return N = DAG.getNode(ISD::UNDEF, VT);
588
589      // Create a VBUILD_VECTOR of undef nodes.
590      const PackedType *PTy = cast<PackedType>(VTy);
591      unsigned NumElements = PTy->getNumElements();
592      MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
593
594      std::vector<SDOperand> Ops;
595      Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
596
597      // Create a VConstant node with generic Vector type.
598      Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
599      Ops.push_back(DAG.getValueType(PVT));
600      return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
601    } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
602      return N = DAG.getConstantFP(CFP->getValue(), VT);
603    } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
604      unsigned NumElements = PTy->getNumElements();
605      MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
606
607      // Now that we know the number and type of the elements, push a
608      // Constant or ConstantFP node onto the ops list for each element of
609      // the packed constant.
610      std::vector<SDOperand> Ops;
611      if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
612        for (unsigned i = 0; i != NumElements; ++i)
613          Ops.push_back(getValue(CP->getOperand(i)));
614      } else {
615        assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
616        SDOperand Op;
617        if (MVT::isFloatingPoint(PVT))
618          Op = DAG.getConstantFP(0, PVT);
619        else
620          Op = DAG.getConstant(0, PVT);
621        Ops.assign(NumElements, Op);
622      }
623
624      // Create a VBUILD_VECTOR node with generic Vector type.
625      Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
626      Ops.push_back(DAG.getValueType(PVT));
627      return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
628    } else {
629      // Canonicalize all constant ints to be unsigned.
630      return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
631    }
632  }
633
634  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
635    std::map<const AllocaInst*, int>::iterator SI =
636    FuncInfo.StaticAllocaMap.find(AI);
637    if (SI != FuncInfo.StaticAllocaMap.end())
638      return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
639  }
640
641  std::map<const Value*, unsigned>::const_iterator VMI =
642      FuncInfo.ValueMap.find(V);
643  assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
644
645  unsigned InReg = VMI->second;
646
647  // If this type is not legal, make it so now.
648  if (VT != MVT::Vector) {
649    MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
650
651    N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
652    if (DestVT < VT) {
653      // Source must be expanded.  This input value is actually coming from the
654      // register pair VMI->second and VMI->second+1.
655      N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
656                      DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
657    } else if (DestVT > VT) { // Promotion case
658      if (MVT::isFloatingPoint(VT))
659        N = DAG.getNode(ISD::FP_ROUND, VT, N);
660      else
661        N = DAG.getNode(ISD::TRUNCATE, VT, N);
662    }
663  } else {
664    // Otherwise, if this is a vector, make it available as a generic vector
665    // here.
666    MVT::ValueType PTyElementVT, PTyLegalElementVT;
667    const PackedType *PTy = cast<PackedType>(VTy);
668    unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
669                                             PTyLegalElementVT);
670
671    // Build a VBUILD_VECTOR with the input registers.
672    std::vector<SDOperand> Ops;
673    if (PTyElementVT == PTyLegalElementVT) {
674      // If the value types are legal, just VBUILD the CopyFromReg nodes.
675      for (unsigned i = 0; i != NE; ++i)
676        Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
677                                         PTyElementVT));
678    } else if (PTyElementVT < PTyLegalElementVT) {
679      // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
680      for (unsigned i = 0; i != NE; ++i) {
681        SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
682                                          PTyElementVT);
683        if (MVT::isFloatingPoint(PTyElementVT))
684          Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
685        else
686          Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
687        Ops.push_back(Op);
688      }
689    } else {
690      // If the register was expanded, use BUILD_PAIR.
691      assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
692      for (unsigned i = 0; i != NE/2; ++i) {
693        SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
694                                           PTyElementVT);
695        SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
696                                           PTyElementVT);
697        Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
698      }
699    }
700
701    Ops.push_back(DAG.getConstant(NE, MVT::i32));
702    Ops.push_back(DAG.getValueType(PTyLegalElementVT));
703    N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
704
705    // Finally, use a VBIT_CONVERT to make this available as the appropriate
706    // vector type.
707    N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
708                    DAG.getConstant(PTy->getNumElements(),
709                                    MVT::i32),
710                    DAG.getValueType(TLI.getValueType(PTy->getElementType())));
711  }
712
713  return N;
714}
715
716
717void SelectionDAGLowering::visitRet(ReturnInst &I) {
718  if (I.getNumOperands() == 0) {
719    DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
720    return;
721  }
722  std::vector<SDOperand> NewValues;
723  NewValues.push_back(getRoot());
724  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
725    SDOperand RetOp = getValue(I.getOperand(i));
726    bool isSigned = I.getOperand(i)->getType()->isSigned();
727
728    // If this is an integer return value, we need to promote it ourselves to
729    // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
730    // than sign/zero.
731    // FIXME: C calling convention requires the return type to be promoted to
732    // at least 32-bit. But this is not necessary for non-C calling conventions.
733    if (MVT::isInteger(RetOp.getValueType()) &&
734        RetOp.getValueType() < MVT::i64) {
735      MVT::ValueType TmpVT;
736      if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
737        TmpVT = TLI.getTypeToTransformTo(MVT::i32);
738      else
739        TmpVT = MVT::i32;
740
741      if (isSigned)
742        RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
743      else
744        RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
745    }
746    NewValues.push_back(RetOp);
747    NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
748  }
749  DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
750}
751
752void SelectionDAGLowering::visitBr(BranchInst &I) {
753  // Update machine-CFG edges.
754  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
755  CurMBB->addSuccessor(Succ0MBB);
756
757  // Figure out which block is immediately after the current one.
758  MachineBasicBlock *NextBlock = 0;
759  MachineFunction::iterator BBI = CurMBB;
760  if (++BBI != CurMBB->getParent()->end())
761    NextBlock = BBI;
762
763  if (I.isUnconditional()) {
764    // If this is not a fall-through branch, emit the branch.
765    if (Succ0MBB != NextBlock)
766      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
767                              DAG.getBasicBlock(Succ0MBB)));
768  } else {
769    MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
770    CurMBB->addSuccessor(Succ1MBB);
771
772    SDOperand Cond = getValue(I.getCondition());
773    if (Succ1MBB == NextBlock) {
774      // If the condition is false, fall through.  This means we should branch
775      // if the condition is true to Succ #0.
776      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
777                              Cond, DAG.getBasicBlock(Succ0MBB)));
778    } else if (Succ0MBB == NextBlock) {
779      // If the condition is true, fall through.  This means we should branch if
780      // the condition is false to Succ #1.  Invert the condition first.
781      SDOperand True = DAG.getConstant(1, Cond.getValueType());
782      Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
783      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
784                              Cond, DAG.getBasicBlock(Succ1MBB)));
785    } else {
786      std::vector<SDOperand> Ops;
787      Ops.push_back(getRoot());
788      // If the false case is the current basic block, then this is a self
789      // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
790      // adds an extra instruction in the loop.  Instead, invert the
791      // condition and emit "Loop: ... br!cond Loop; br Out.
792      if (CurMBB == Succ1MBB) {
793        std::swap(Succ0MBB, Succ1MBB);
794        SDOperand True = DAG.getConstant(1, Cond.getValueType());
795        Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
796      }
797      SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
798                                   DAG.getBasicBlock(Succ0MBB));
799      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
800                              DAG.getBasicBlock(Succ1MBB)));
801    }
802  }
803}
804
805/// visitSwitchCase - Emits the necessary code to represent a single node in
806/// the binary search tree resulting from lowering a switch instruction.
807void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
808  SDOperand SwitchOp = getValue(CB.SwitchV);
809  SDOperand CaseOp = getValue(CB.CaseC);
810  SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
811
812  // Set NextBlock to be the MBB immediately after the current one, if any.
813  // This is used to avoid emitting unnecessary branches to the next block.
814  MachineBasicBlock *NextBlock = 0;
815  MachineFunction::iterator BBI = CurMBB;
816  if (++BBI != CurMBB->getParent()->end())
817    NextBlock = BBI;
818
819  // If the lhs block is the next block, invert the condition so that we can
820  // fall through to the lhs instead of the rhs block.
821  if (CB.LHSBB == NextBlock) {
822    std::swap(CB.LHSBB, CB.RHSBB);
823    SDOperand True = DAG.getConstant(1, Cond.getValueType());
824    Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
825  }
826  SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
827                                 DAG.getBasicBlock(CB.LHSBB));
828  if (CB.RHSBB == NextBlock)
829    DAG.setRoot(BrCond);
830  else
831    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
832                            DAG.getBasicBlock(CB.RHSBB)));
833  // Update successor info
834  CurMBB->addSuccessor(CB.LHSBB);
835  CurMBB->addSuccessor(CB.RHSBB);
836}
837
838/// visitSwitchCase - Emits the necessary code to represent a single node in
839/// the binary search tree resulting from lowering a switch instruction.
840void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
841  // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
842  // we need to add the address of the jump table to the value loaded, since
843  // the entries in the jump table will be differences rather than absolute
844  // addresses.
845
846  // Emit the code for the jump table
847  MVT::ValueType PTy = TLI.getPointerTy();
848  unsigned PTyBytes = MVT::getSizeInBits(PTy)/8;
849  SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
850  SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
851                              DAG.getConstant(PTyBytes, PTy));
852  SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, DAG.getJumpTable(JT.JTI,PTy));
853  SDOperand LD  = DAG.getLoad(PTy, Copy.getValue(1), ADD, DAG.getSrcValue(0));
854  DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
855}
856
857void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
858  // Figure out which block is immediately after the current one.
859  MachineBasicBlock *NextBlock = 0;
860  MachineFunction::iterator BBI = CurMBB;
861  if (++BBI != CurMBB->getParent()->end())
862    NextBlock = BBI;
863
864  // If there is only the default destination, branch to it if it is not the
865  // next basic block.  Otherwise, just fall through.
866  if (I.getNumOperands() == 2) {
867    // Update machine-CFG edges.
868    MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
869    // If this is not a fall-through branch, emit the branch.
870    if (DefaultMBB != NextBlock)
871      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
872                              DAG.getBasicBlock(DefaultMBB)));
873    CurMBB->addSuccessor(DefaultMBB);
874    return;
875  }
876
877  // If there are any non-default case statements, create a vector of Cases
878  // representing each one, and sort the vector so that we can efficiently
879  // create a binary search tree from them.
880  std::vector<Case> Cases;
881  for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
882    MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
883    Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
884  }
885  std::sort(Cases.begin(), Cases.end(), CaseCmp());
886
887  // Get the Value to be switched on and default basic blocks, which will be
888  // inserted into CaseBlock records, representing basic blocks in the binary
889  // search tree.
890  Value *SV = I.getOperand(0);
891  MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
892
893  // Get the MachineFunction which holds the current MBB.  This is used during
894  // emission of jump tables, and when inserting any additional MBBs necessary
895  // to represent the switch.
896  MachineFunction *CurMF = CurMBB->getParent();
897  const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
898  Reloc::Model Relocs = TLI.getTargetMachine().getRelocationModel();
899
900  // If the switch has more than 5 blocks, and at least 31.25% dense, and the
901  // target supports indirect branches, then emit a jump table rather than
902  // lowering the switch to a binary tree of conditional branches.
903  // FIXME: Make this work with PIC code
904  if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
905      (Relocs == Reloc::Static || Relocs == Reloc::DynamicNoPIC) &&
906      Cases.size() > 5) {
907    uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
908    uint64_t Last  = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
909    double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
910
911    if (Density >= 0.3125) {
912      // Create a new basic block to hold the code for loading the address
913      // of the jump table, and jumping to it.  Update successor information;
914      // we will either branch to the default case for the switch, or the jump
915      // table.
916      MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
917      CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
918      CurMBB->addSuccessor(Default);
919      CurMBB->addSuccessor(JumpTableBB);
920
921      // Subtract the lowest switch case value from the value being switched on
922      // and conditional branch to default mbb if the result is greater than the
923      // difference between smallest and largest cases.
924      SDOperand SwitchOp = getValue(SV);
925      MVT::ValueType VT = SwitchOp.getValueType();
926      SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
927                                  DAG.getConstant(First, VT));
928
929      // The SDNode we just created, which holds the value being switched on
930      // minus the the smallest case value, needs to be copied to a virtual
931      // register so it can be used as an index into the jump table in a
932      // subsequent basic block.  This value may be smaller or larger than the
933      // target's pointer type, and therefore require extension or truncating.
934      if (VT > TLI.getPointerTy())
935        SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
936      else
937        SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
938      unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
939      SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
940
941      // Emit the range check for the jump table, and branch to the default
942      // block for the switch statement if the value being switched on exceeds
943      // the largest case in the switch.
944      SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
945                                   DAG.getConstant(Last-First,VT), ISD::SETUGT);
946      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
947                              DAG.getBasicBlock(Default)));
948
949      // Build a vector of destination BBs, corresponding to each target
950      // of the jump table.  If the value of the jump table slot corresponds to
951      // a case statement, push the case's BB onto the vector, otherwise, push
952      // the default BB.
953      std::set<MachineBasicBlock*> UniqueBBs;
954      std::vector<MachineBasicBlock*> DestBBs;
955      uint64_t TEI = First;
956      for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI) {
957        if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
958          DestBBs.push_back(ii->second);
959          UniqueBBs.insert(ii->second);
960          ++ii;
961        } else {
962          DestBBs.push_back(Default);
963          UniqueBBs.insert(Default);
964        }
965      }
966
967      // Update successor info
968      for (std::set<MachineBasicBlock*>::iterator ii = UniqueBBs.begin(),
969           ee = UniqueBBs.end(); ii != ee; ++ii)
970        JumpTableBB->addSuccessor(*ii);
971
972      // Create a jump table index for this jump table, or return an existing
973      // one.
974      unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
975
976      // Set the jump table information so that we can codegen it as a second
977      // MachineBasicBlock
978      JT.Reg = JumpTableReg;
979      JT.JTI = JTI;
980      JT.MBB = JumpTableBB;
981      JT.Default = Default;
982      return;
983    }
984  }
985
986  // Push the initial CaseRec onto the worklist
987  std::vector<CaseRec> CaseVec;
988  CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
989
990  while (!CaseVec.empty()) {
991    // Grab a record representing a case range to process off the worklist
992    CaseRec CR = CaseVec.back();
993    CaseVec.pop_back();
994
995    // Size is the number of Cases represented by this range.  If Size is 1,
996    // then we are processing a leaf of the binary search tree.  Otherwise,
997    // we need to pick a pivot, and push left and right ranges onto the
998    // worklist.
999    unsigned Size = CR.Range.second - CR.Range.first;
1000
1001    if (Size == 1) {
1002      // Create a CaseBlock record representing a conditional branch to
1003      // the Case's target mbb if the value being switched on SV is equal
1004      // to C.  Otherwise, branch to default.
1005      Constant *C = CR.Range.first->first;
1006      MachineBasicBlock *Target = CR.Range.first->second;
1007      SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1008                                     CR.CaseBB);
1009      // If the MBB representing the leaf node is the current MBB, then just
1010      // call visitSwitchCase to emit the code into the current block.
1011      // Otherwise, push the CaseBlock onto the vector to be later processed
1012      // by SDISel, and insert the node's MBB before the next MBB.
1013      if (CR.CaseBB == CurMBB)
1014        visitSwitchCase(CB);
1015      else {
1016        SwitchCases.push_back(CB);
1017        CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1018      }
1019    } else {
1020      // split case range at pivot
1021      CaseItr Pivot = CR.Range.first + (Size / 2);
1022      CaseRange LHSR(CR.Range.first, Pivot);
1023      CaseRange RHSR(Pivot, CR.Range.second);
1024      Constant *C = Pivot->first;
1025      MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1026      // We know that we branch to the LHS if the Value being switched on is
1027      // less than the Pivot value, C.  We use this to optimize our binary
1028      // tree a bit, by recognizing that if SV is greater than or equal to the
1029      // LHS's Case Value, and that Case Value is exactly one less than the
1030      // Pivot's Value, then we can branch directly to the LHS's Target,
1031      // rather than creating a leaf node for it.
1032      if ((LHSR.second - LHSR.first) == 1 &&
1033          LHSR.first->first == CR.GE &&
1034          cast<ConstantIntegral>(C)->getRawValue() ==
1035          (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1036        LHSBB = LHSR.first->second;
1037      } else {
1038        LHSBB = new MachineBasicBlock(LLVMBB);
1039        CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1040      }
1041      // Similar to the optimization above, if the Value being switched on is
1042      // known to be less than the Constant CR.LT, and the current Case Value
1043      // is CR.LT - 1, then we can branch directly to the target block for
1044      // the current Case Value, rather than emitting a RHS leaf node for it.
1045      if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1046          cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1047          (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1048        RHSBB = RHSR.first->second;
1049      } else {
1050        RHSBB = new MachineBasicBlock(LLVMBB);
1051        CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1052      }
1053      // Create a CaseBlock record representing a conditional branch to
1054      // the LHS node if the value being switched on SV is less than C.
1055      // Otherwise, branch to LHS.
1056      ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1057      SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1058      if (CR.CaseBB == CurMBB)
1059        visitSwitchCase(CB);
1060      else {
1061        SwitchCases.push_back(CB);
1062        CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1063      }
1064    }
1065  }
1066}
1067
1068void SelectionDAGLowering::visitSub(User &I) {
1069  // -0.0 - X --> fneg
1070  if (I.getType()->isFloatingPoint()) {
1071    if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1072      if (CFP->isExactlyValue(-0.0)) {
1073        SDOperand Op2 = getValue(I.getOperand(1));
1074        setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1075        return;
1076      }
1077  }
1078  visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
1079}
1080
1081void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1082                                       unsigned VecOp) {
1083  const Type *Ty = I.getType();
1084  SDOperand Op1 = getValue(I.getOperand(0));
1085  SDOperand Op2 = getValue(I.getOperand(1));
1086
1087  if (Ty->isIntegral()) {
1088    setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1089  } else if (Ty->isFloatingPoint()) {
1090    setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1091  } else {
1092    const PackedType *PTy = cast<PackedType>(Ty);
1093    SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1094    SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1095    setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1096  }
1097}
1098
1099void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1100  SDOperand Op1 = getValue(I.getOperand(0));
1101  SDOperand Op2 = getValue(I.getOperand(1));
1102
1103  Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1104
1105  setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1106}
1107
1108void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1109                                      ISD::CondCode UnsignedOpcode,
1110                                      ISD::CondCode FPOpcode) {
1111  SDOperand Op1 = getValue(I.getOperand(0));
1112  SDOperand Op2 = getValue(I.getOperand(1));
1113  ISD::CondCode Opcode = SignedOpcode;
1114  if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1115    Opcode = FPOpcode;
1116  else if (I.getOperand(0)->getType()->isUnsigned())
1117    Opcode = UnsignedOpcode;
1118  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1119}
1120
1121void SelectionDAGLowering::visitSelect(User &I) {
1122  SDOperand Cond     = getValue(I.getOperand(0));
1123  SDOperand TrueVal  = getValue(I.getOperand(1));
1124  SDOperand FalseVal = getValue(I.getOperand(2));
1125  if (!isa<PackedType>(I.getType())) {
1126    setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1127                             TrueVal, FalseVal));
1128  } else {
1129    setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1130                             *(TrueVal.Val->op_end()-2),
1131                             *(TrueVal.Val->op_end()-1)));
1132  }
1133}
1134
1135void SelectionDAGLowering::visitCast(User &I) {
1136  SDOperand N = getValue(I.getOperand(0));
1137  MVT::ValueType SrcVT = N.getValueType();
1138  MVT::ValueType DestVT = TLI.getValueType(I.getType());
1139
1140  if (DestVT == MVT::Vector) {
1141    // This is a cast to a vector from something else.  This is always a bit
1142    // convert.  Get information about the input vector.
1143    const PackedType *DestTy = cast<PackedType>(I.getType());
1144    MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1145    setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1146                             DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1147                             DAG.getValueType(EltVT)));
1148  } else if (SrcVT == DestVT) {
1149    setValue(&I, N);  // noop cast.
1150  } else if (DestVT == MVT::i1) {
1151    // Cast to bool is a comparison against zero, not truncation to zero.
1152    SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1153                                       DAG.getConstantFP(0.0, N.getValueType());
1154    setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1155  } else if (isInteger(SrcVT)) {
1156    if (isInteger(DestVT)) {        // Int -> Int cast
1157      if (DestVT < SrcVT)   // Truncating cast?
1158        setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1159      else if (I.getOperand(0)->getType()->isSigned())
1160        setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1161      else
1162        setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1163    } else if (isFloatingPoint(DestVT)) {           // Int -> FP cast
1164      if (I.getOperand(0)->getType()->isSigned())
1165        setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1166      else
1167        setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1168    } else {
1169      assert(0 && "Unknown cast!");
1170    }
1171  } else if (isFloatingPoint(SrcVT)) {
1172    if (isFloatingPoint(DestVT)) {  // FP -> FP cast
1173      if (DestVT < SrcVT)   // Rounding cast?
1174        setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1175      else
1176        setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1177    } else if (isInteger(DestVT)) {        // FP -> Int cast.
1178      if (I.getType()->isSigned())
1179        setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1180      else
1181        setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1182    } else {
1183      assert(0 && "Unknown cast!");
1184    }
1185  } else {
1186    assert(SrcVT == MVT::Vector && "Unknown cast!");
1187    assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1188    // This is a cast from a vector to something else.  This is always a bit
1189    // convert.  Get information about the input vector.
1190    setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1191  }
1192}
1193
1194void SelectionDAGLowering::visitInsertElement(User &I) {
1195  SDOperand InVec = getValue(I.getOperand(0));
1196  SDOperand InVal = getValue(I.getOperand(1));
1197  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1198                                getValue(I.getOperand(2)));
1199
1200  SDOperand Num = *(InVec.Val->op_end()-2);
1201  SDOperand Typ = *(InVec.Val->op_end()-1);
1202  setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1203                           InVec, InVal, InIdx, Num, Typ));
1204}
1205
1206void SelectionDAGLowering::visitExtractElement(User &I) {
1207  SDOperand InVec = getValue(I.getOperand(0));
1208  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1209                                getValue(I.getOperand(1)));
1210  SDOperand Typ = *(InVec.Val->op_end()-1);
1211  setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1212                           TLI.getValueType(I.getType()), InVec, InIdx));
1213}
1214
1215void SelectionDAGLowering::visitShuffleVector(User &I) {
1216  SDOperand V1   = getValue(I.getOperand(0));
1217  SDOperand V2   = getValue(I.getOperand(1));
1218  SDOperand Mask = getValue(I.getOperand(2));
1219
1220  SDOperand Num = *(V1.Val->op_end()-2);
1221  SDOperand Typ = *(V2.Val->op_end()-1);
1222  setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1223                           V1, V2, Mask, Num, Typ));
1224}
1225
1226
1227void SelectionDAGLowering::visitGetElementPtr(User &I) {
1228  SDOperand N = getValue(I.getOperand(0));
1229  const Type *Ty = I.getOperand(0)->getType();
1230
1231  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1232       OI != E; ++OI) {
1233    Value *Idx = *OI;
1234    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1235      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1236      if (Field) {
1237        // N = N + Offset
1238        uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1239        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1240                        getIntPtrConstant(Offset));
1241      }
1242      Ty = StTy->getElementType(Field);
1243    } else {
1244      Ty = cast<SequentialType>(Ty)->getElementType();
1245
1246      // If this is a constant subscript, handle it quickly.
1247      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1248        if (CI->getRawValue() == 0) continue;
1249
1250        uint64_t Offs;
1251        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1252          Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
1253        else
1254          Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1255        N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1256        continue;
1257      }
1258
1259      // N = N + Idx * ElementSize;
1260      uint64_t ElementSize = TD->getTypeSize(Ty);
1261      SDOperand IdxN = getValue(Idx);
1262
1263      // If the index is smaller or larger than intptr_t, truncate or extend
1264      // it.
1265      if (IdxN.getValueType() < N.getValueType()) {
1266        if (Idx->getType()->isSigned())
1267          IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1268        else
1269          IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1270      } else if (IdxN.getValueType() > N.getValueType())
1271        IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1272
1273      // If this is a multiply by a power of two, turn it into a shl
1274      // immediately.  This is a very common case.
1275      if (isPowerOf2_64(ElementSize)) {
1276        unsigned Amt = Log2_64(ElementSize);
1277        IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1278                           DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1279        N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1280        continue;
1281      }
1282
1283      SDOperand Scale = getIntPtrConstant(ElementSize);
1284      IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1285      N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1286    }
1287  }
1288  setValue(&I, N);
1289}
1290
1291void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1292  // If this is a fixed sized alloca in the entry block of the function,
1293  // allocate it statically on the stack.
1294  if (FuncInfo.StaticAllocaMap.count(&I))
1295    return;   // getValue will auto-populate this.
1296
1297  const Type *Ty = I.getAllocatedType();
1298  uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1299  unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1300                            I.getAlignment());
1301
1302  SDOperand AllocSize = getValue(I.getArraySize());
1303  MVT::ValueType IntPtr = TLI.getPointerTy();
1304  if (IntPtr < AllocSize.getValueType())
1305    AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1306  else if (IntPtr > AllocSize.getValueType())
1307    AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1308
1309  AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1310                          getIntPtrConstant(TySize));
1311
1312  // Handle alignment.  If the requested alignment is less than or equal to the
1313  // stack alignment, ignore it and round the size of the allocation up to the
1314  // stack alignment size.  If the size is greater than the stack alignment, we
1315  // note this in the DYNAMIC_STACKALLOC node.
1316  unsigned StackAlign =
1317    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1318  if (Align <= StackAlign) {
1319    Align = 0;
1320    // Add SA-1 to the size.
1321    AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1322                            getIntPtrConstant(StackAlign-1));
1323    // Mask out the low bits for alignment purposes.
1324    AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1325                            getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1326  }
1327
1328  std::vector<MVT::ValueType> VTs;
1329  VTs.push_back(AllocSize.getValueType());
1330  VTs.push_back(MVT::Other);
1331  std::vector<SDOperand> Ops;
1332  Ops.push_back(getRoot());
1333  Ops.push_back(AllocSize);
1334  Ops.push_back(getIntPtrConstant(Align));
1335  SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1336  DAG.setRoot(setValue(&I, DSA).getValue(1));
1337
1338  // Inform the Frame Information that we have just allocated a variable-sized
1339  // object.
1340  CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1341}
1342
1343void SelectionDAGLowering::visitLoad(LoadInst &I) {
1344  SDOperand Ptr = getValue(I.getOperand(0));
1345
1346  SDOperand Root;
1347  if (I.isVolatile())
1348    Root = getRoot();
1349  else {
1350    // Do not serialize non-volatile loads against each other.
1351    Root = DAG.getRoot();
1352  }
1353
1354  setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1355                           Root, I.isVolatile()));
1356}
1357
1358SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1359                                            SDOperand SrcValue, SDOperand Root,
1360                                            bool isVolatile) {
1361  SDOperand L;
1362  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1363    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1364    L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1365  } else {
1366    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1367  }
1368
1369  if (isVolatile)
1370    DAG.setRoot(L.getValue(1));
1371  else
1372    PendingLoads.push_back(L.getValue(1));
1373
1374  return L;
1375}
1376
1377
1378void SelectionDAGLowering::visitStore(StoreInst &I) {
1379  Value *SrcV = I.getOperand(0);
1380  SDOperand Src = getValue(SrcV);
1381  SDOperand Ptr = getValue(I.getOperand(1));
1382  DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1383                          DAG.getSrcValue(I.getOperand(1))));
1384}
1385
1386/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1387/// access memory and has no other side effects at all.
1388static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1389#define GET_NO_MEMORY_INTRINSICS
1390#include "llvm/Intrinsics.gen"
1391#undef GET_NO_MEMORY_INTRINSICS
1392  return false;
1393}
1394
1395// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1396// have any side-effects or if it only reads memory.
1397static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1398#define GET_SIDE_EFFECT_INFO
1399#include "llvm/Intrinsics.gen"
1400#undef GET_SIDE_EFFECT_INFO
1401  return false;
1402}
1403
1404/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1405/// node.
1406void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1407                                                unsigned Intrinsic) {
1408  bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1409  bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1410
1411  // Build the operand list.
1412  std::vector<SDOperand> Ops;
1413  if (HasChain) {  // If this intrinsic has side-effects, chainify it.
1414    if (OnlyLoad) {
1415      // We don't need to serialize loads against other loads.
1416      Ops.push_back(DAG.getRoot());
1417    } else {
1418      Ops.push_back(getRoot());
1419    }
1420  }
1421
1422  // Add the intrinsic ID as an integer operand.
1423  Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1424
1425  // Add all operands of the call to the operand list.
1426  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1427    SDOperand Op = getValue(I.getOperand(i));
1428
1429    // If this is a vector type, force it to the right packed type.
1430    if (Op.getValueType() == MVT::Vector) {
1431      const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1432      MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1433
1434      MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1435      assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1436      Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1437    }
1438
1439    assert(TLI.isTypeLegal(Op.getValueType()) &&
1440           "Intrinsic uses a non-legal type?");
1441    Ops.push_back(Op);
1442  }
1443
1444  std::vector<MVT::ValueType> VTs;
1445  if (I.getType() != Type::VoidTy) {
1446    MVT::ValueType VT = TLI.getValueType(I.getType());
1447    if (VT == MVT::Vector) {
1448      const PackedType *DestTy = cast<PackedType>(I.getType());
1449      MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1450
1451      VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1452      assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1453    }
1454
1455    assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1456    VTs.push_back(VT);
1457  }
1458  if (HasChain)
1459    VTs.push_back(MVT::Other);
1460
1461  // Create the node.
1462  SDOperand Result;
1463  if (!HasChain)
1464    Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1465  else if (I.getType() != Type::VoidTy)
1466    Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1467  else
1468    Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1469
1470  if (HasChain) {
1471    SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1472    if (OnlyLoad)
1473      PendingLoads.push_back(Chain);
1474    else
1475      DAG.setRoot(Chain);
1476  }
1477  if (I.getType() != Type::VoidTy) {
1478    if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1479      MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1480      Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1481                           DAG.getConstant(PTy->getNumElements(), MVT::i32),
1482                           DAG.getValueType(EVT));
1483    }
1484    setValue(&I, Result);
1485  }
1486}
1487
1488/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
1489/// we want to emit this as a call to a named external function, return the name
1490/// otherwise lower it and return null.
1491const char *
1492SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1493  switch (Intrinsic) {
1494  default:
1495    // By default, turn this into a target intrinsic node.
1496    visitTargetIntrinsic(I, Intrinsic);
1497    return 0;
1498  case Intrinsic::vastart:  visitVAStart(I); return 0;
1499  case Intrinsic::vaend:    visitVAEnd(I); return 0;
1500  case Intrinsic::vacopy:   visitVACopy(I); return 0;
1501  case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1502  case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
1503  case Intrinsic::setjmp:
1504    return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1505    break;
1506  case Intrinsic::longjmp:
1507    return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1508    break;
1509  case Intrinsic::memcpy_i32:
1510  case Intrinsic::memcpy_i64:
1511    visitMemIntrinsic(I, ISD::MEMCPY);
1512    return 0;
1513  case Intrinsic::memset_i32:
1514  case Intrinsic::memset_i64:
1515    visitMemIntrinsic(I, ISD::MEMSET);
1516    return 0;
1517  case Intrinsic::memmove_i32:
1518  case Intrinsic::memmove_i64:
1519    visitMemIntrinsic(I, ISD::MEMMOVE);
1520    return 0;
1521
1522  case Intrinsic::dbg_stoppoint: {
1523    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1524    DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1525    if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1526      std::vector<SDOperand> Ops;
1527
1528      Ops.push_back(getRoot());
1529      Ops.push_back(getValue(SPI.getLineValue()));
1530      Ops.push_back(getValue(SPI.getColumnValue()));
1531
1532      DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1533      assert(DD && "Not a debug information descriptor");
1534      CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1535
1536      Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1537      Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1538
1539      DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1540    }
1541
1542    return 0;
1543  }
1544  case Intrinsic::dbg_region_start: {
1545    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1546    DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1547    if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1548      std::vector<SDOperand> Ops;
1549
1550      unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1551
1552      Ops.push_back(getRoot());
1553      Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1554
1555      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1556    }
1557
1558    return 0;
1559  }
1560  case Intrinsic::dbg_region_end: {
1561    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1562    DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1563    if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1564      std::vector<SDOperand> Ops;
1565
1566      unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1567
1568      Ops.push_back(getRoot());
1569      Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1570
1571      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1572    }
1573
1574    return 0;
1575  }
1576  case Intrinsic::dbg_func_start: {
1577    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1578    DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1579    if (DebugInfo && FSI.getSubprogram() &&
1580        DebugInfo->Verify(FSI.getSubprogram())) {
1581      std::vector<SDOperand> Ops;
1582
1583      unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1584
1585      Ops.push_back(getRoot());
1586      Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1587
1588      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1589    }
1590
1591    return 0;
1592  }
1593  case Intrinsic::dbg_declare: {
1594    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1595    DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1596    if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1597      std::vector<SDOperand> Ops;
1598
1599      SDOperand AddressOp  = getValue(DI.getAddress());
1600      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1601        DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1602      }
1603    }
1604
1605    return 0;
1606  }
1607
1608  case Intrinsic::isunordered_f32:
1609  case Intrinsic::isunordered_f64:
1610    setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1611                              getValue(I.getOperand(2)), ISD::SETUO));
1612    return 0;
1613
1614  case Intrinsic::sqrt_f32:
1615  case Intrinsic::sqrt_f64:
1616    setValue(&I, DAG.getNode(ISD::FSQRT,
1617                             getValue(I.getOperand(1)).getValueType(),
1618                             getValue(I.getOperand(1))));
1619    return 0;
1620  case Intrinsic::pcmarker: {
1621    SDOperand Tmp = getValue(I.getOperand(1));
1622    DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1623    return 0;
1624  }
1625  case Intrinsic::readcyclecounter: {
1626    std::vector<MVT::ValueType> VTs;
1627    VTs.push_back(MVT::i64);
1628    VTs.push_back(MVT::Other);
1629    std::vector<SDOperand> Ops;
1630    Ops.push_back(getRoot());
1631    SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1632    setValue(&I, Tmp);
1633    DAG.setRoot(Tmp.getValue(1));
1634    return 0;
1635  }
1636  case Intrinsic::bswap_i16:
1637  case Intrinsic::bswap_i32:
1638  case Intrinsic::bswap_i64:
1639    setValue(&I, DAG.getNode(ISD::BSWAP,
1640                             getValue(I.getOperand(1)).getValueType(),
1641                             getValue(I.getOperand(1))));
1642    return 0;
1643  case Intrinsic::cttz_i8:
1644  case Intrinsic::cttz_i16:
1645  case Intrinsic::cttz_i32:
1646  case Intrinsic::cttz_i64:
1647    setValue(&I, DAG.getNode(ISD::CTTZ,
1648                             getValue(I.getOperand(1)).getValueType(),
1649                             getValue(I.getOperand(1))));
1650    return 0;
1651  case Intrinsic::ctlz_i8:
1652  case Intrinsic::ctlz_i16:
1653  case Intrinsic::ctlz_i32:
1654  case Intrinsic::ctlz_i64:
1655    setValue(&I, DAG.getNode(ISD::CTLZ,
1656                             getValue(I.getOperand(1)).getValueType(),
1657                             getValue(I.getOperand(1))));
1658    return 0;
1659  case Intrinsic::ctpop_i8:
1660  case Intrinsic::ctpop_i16:
1661  case Intrinsic::ctpop_i32:
1662  case Intrinsic::ctpop_i64:
1663    setValue(&I, DAG.getNode(ISD::CTPOP,
1664                             getValue(I.getOperand(1)).getValueType(),
1665                             getValue(I.getOperand(1))));
1666    return 0;
1667  case Intrinsic::stacksave: {
1668    std::vector<MVT::ValueType> VTs;
1669    VTs.push_back(TLI.getPointerTy());
1670    VTs.push_back(MVT::Other);
1671    std::vector<SDOperand> Ops;
1672    Ops.push_back(getRoot());
1673    SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1674    setValue(&I, Tmp);
1675    DAG.setRoot(Tmp.getValue(1));
1676    return 0;
1677  }
1678  case Intrinsic::stackrestore: {
1679    SDOperand Tmp = getValue(I.getOperand(1));
1680    DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1681    return 0;
1682  }
1683  case Intrinsic::prefetch:
1684    // FIXME: Currently discarding prefetches.
1685    return 0;
1686  }
1687}
1688
1689
1690void SelectionDAGLowering::visitCall(CallInst &I) {
1691  const char *RenameFn = 0;
1692  if (Function *F = I.getCalledFunction()) {
1693    if (F->isExternal())
1694      if (unsigned IID = F->getIntrinsicID()) {
1695        RenameFn = visitIntrinsicCall(I, IID);
1696        if (!RenameFn)
1697          return;
1698      } else {    // Not an LLVM intrinsic.
1699        const std::string &Name = F->getName();
1700        if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1701          if (I.getNumOperands() == 3 &&   // Basic sanity checks.
1702              I.getOperand(1)->getType()->isFloatingPoint() &&
1703              I.getType() == I.getOperand(1)->getType() &&
1704              I.getType() == I.getOperand(2)->getType()) {
1705            SDOperand LHS = getValue(I.getOperand(1));
1706            SDOperand RHS = getValue(I.getOperand(2));
1707            setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1708                                     LHS, RHS));
1709            return;
1710          }
1711        } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1712          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1713              I.getOperand(1)->getType()->isFloatingPoint() &&
1714              I.getType() == I.getOperand(1)->getType()) {
1715            SDOperand Tmp = getValue(I.getOperand(1));
1716            setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1717            return;
1718          }
1719        } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1720          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1721              I.getOperand(1)->getType()->isFloatingPoint() &&
1722              I.getType() == I.getOperand(1)->getType()) {
1723            SDOperand Tmp = getValue(I.getOperand(1));
1724            setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1725            return;
1726          }
1727        } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1728          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1729              I.getOperand(1)->getType()->isFloatingPoint() &&
1730              I.getType() == I.getOperand(1)->getType()) {
1731            SDOperand Tmp = getValue(I.getOperand(1));
1732            setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1733            return;
1734          }
1735        }
1736      }
1737  } else if (isa<InlineAsm>(I.getOperand(0))) {
1738    visitInlineAsm(I);
1739    return;
1740  }
1741
1742  SDOperand Callee;
1743  if (!RenameFn)
1744    Callee = getValue(I.getOperand(0));
1745  else
1746    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1747  std::vector<std::pair<SDOperand, const Type*> > Args;
1748  Args.reserve(I.getNumOperands());
1749  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1750    Value *Arg = I.getOperand(i);
1751    SDOperand ArgNode = getValue(Arg);
1752    Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1753  }
1754
1755  const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1756  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1757
1758  std::pair<SDOperand,SDOperand> Result =
1759    TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1760                    I.isTailCall(), Callee, Args, DAG);
1761  if (I.getType() != Type::VoidTy)
1762    setValue(&I, Result.first);
1763  DAG.setRoot(Result.second);
1764}
1765
1766SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1767                                        SDOperand &Chain, SDOperand &Flag)const{
1768  SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1769  Chain = Val.getValue(1);
1770  Flag  = Val.getValue(2);
1771
1772  // If the result was expanded, copy from the top part.
1773  if (Regs.size() > 1) {
1774    assert(Regs.size() == 2 &&
1775           "Cannot expand to more than 2 elts yet!");
1776    SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1777    Chain = Val.getValue(1);
1778    Flag  = Val.getValue(2);
1779    if (DAG.getTargetLoweringInfo().isLittleEndian())
1780      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1781    else
1782      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1783  }
1784
1785  // Otherwise, if the return value was promoted or extended, truncate it to the
1786  // appropriate type.
1787  if (RegVT == ValueVT)
1788    return Val;
1789
1790  if (MVT::isInteger(RegVT)) {
1791    if (ValueVT < RegVT)
1792      return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1793    else
1794      return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1795  } else {
1796    return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1797  }
1798}
1799
1800/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1801/// specified value into the registers specified by this object.  This uses
1802/// Chain/Flag as the input and updates them for the output Chain/Flag.
1803void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1804                                 SDOperand &Chain, SDOperand &Flag,
1805                                 MVT::ValueType PtrVT) const {
1806  if (Regs.size() == 1) {
1807    // If there is a single register and the types differ, this must be
1808    // a promotion.
1809    if (RegVT != ValueVT) {
1810      if (MVT::isInteger(RegVT)) {
1811        if (RegVT < ValueVT)
1812          Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1813        else
1814          Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1815      } else
1816        Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1817    }
1818    Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1819    Flag = Chain.getValue(1);
1820  } else {
1821    std::vector<unsigned> R(Regs);
1822    if (!DAG.getTargetLoweringInfo().isLittleEndian())
1823      std::reverse(R.begin(), R.end());
1824
1825    for (unsigned i = 0, e = R.size(); i != e; ++i) {
1826      SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1827                                   DAG.getConstant(i, PtrVT));
1828      Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1829      Flag = Chain.getValue(1);
1830    }
1831  }
1832}
1833
1834/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1835/// operand list.  This adds the code marker and includes the number of
1836/// values added into it.
1837void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1838                                        std::vector<SDOperand> &Ops) const {
1839  Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1840  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1841    Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1842}
1843
1844/// isAllocatableRegister - If the specified register is safe to allocate,
1845/// i.e. it isn't a stack pointer or some other special register, return the
1846/// register class for the register.  Otherwise, return null.
1847static const TargetRegisterClass *
1848isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1849                      const TargetLowering &TLI, const MRegisterInfo *MRI) {
1850  MVT::ValueType FoundVT = MVT::Other;
1851  const TargetRegisterClass *FoundRC = 0;
1852  for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1853       E = MRI->regclass_end(); RCI != E; ++RCI) {
1854    MVT::ValueType ThisVT = MVT::Other;
1855
1856    const TargetRegisterClass *RC = *RCI;
1857    // If none of the the value types for this register class are valid, we
1858    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1859    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1860         I != E; ++I) {
1861      if (TLI.isTypeLegal(*I)) {
1862        // If we have already found this register in a different register class,
1863        // choose the one with the largest VT specified.  For example, on
1864        // PowerPC, we favor f64 register classes over f32.
1865        if (FoundVT == MVT::Other ||
1866            MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1867          ThisVT = *I;
1868          break;
1869        }
1870      }
1871    }
1872
1873    if (ThisVT == MVT::Other) continue;
1874
1875    // NOTE: This isn't ideal.  In particular, this might allocate the
1876    // frame pointer in functions that need it (due to them not being taken
1877    // out of allocation, because a variable sized allocation hasn't been seen
1878    // yet).  This is a slight code pessimization, but should still work.
1879    for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1880         E = RC->allocation_order_end(MF); I != E; ++I)
1881      if (*I == Reg) {
1882        // We found a matching register class.  Keep looking at others in case
1883        // we find one with larger registers that this physreg is also in.
1884        FoundRC = RC;
1885        FoundVT = ThisVT;
1886        break;
1887      }
1888  }
1889  return FoundRC;
1890}
1891
1892RegsForValue SelectionDAGLowering::
1893GetRegistersForValue(const std::string &ConstrCode,
1894                     MVT::ValueType VT, bool isOutReg, bool isInReg,
1895                     std::set<unsigned> &OutputRegs,
1896                     std::set<unsigned> &InputRegs) {
1897  std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1898    TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1899  std::vector<unsigned> Regs;
1900
1901  unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1902  MVT::ValueType RegVT;
1903  MVT::ValueType ValueVT = VT;
1904
1905  if (PhysReg.first) {
1906    if (VT == MVT::Other)
1907      ValueVT = *PhysReg.second->vt_begin();
1908
1909    // Get the actual register value type.  This is important, because the user
1910    // may have asked for (e.g.) the AX register in i32 type.  We need to
1911    // remember that AX is actually i16 to get the right extension.
1912    RegVT = *PhysReg.second->vt_begin();
1913
1914    // This is a explicit reference to a physical register.
1915    Regs.push_back(PhysReg.first);
1916
1917    // If this is an expanded reference, add the rest of the regs to Regs.
1918    if (NumRegs != 1) {
1919      TargetRegisterClass::iterator I = PhysReg.second->begin();
1920      TargetRegisterClass::iterator E = PhysReg.second->end();
1921      for (; *I != PhysReg.first; ++I)
1922        assert(I != E && "Didn't find reg!");
1923
1924      // Already added the first reg.
1925      --NumRegs; ++I;
1926      for (; NumRegs; --NumRegs, ++I) {
1927        assert(I != E && "Ran out of registers to allocate!");
1928        Regs.push_back(*I);
1929      }
1930    }
1931    return RegsForValue(Regs, RegVT, ValueVT);
1932  }
1933
1934  // This is a reference to a register class.  Allocate NumRegs consecutive,
1935  // available, registers from the class.
1936  std::vector<unsigned> RegClassRegs =
1937    TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1938
1939  const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1940  MachineFunction &MF = *CurMBB->getParent();
1941  unsigned NumAllocated = 0;
1942  for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1943    unsigned Reg = RegClassRegs[i];
1944    // See if this register is available.
1945    if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
1946        (isInReg  && InputRegs.count(Reg))) {    // Already used.
1947      // Make sure we find consecutive registers.
1948      NumAllocated = 0;
1949      continue;
1950    }
1951
1952    // Check to see if this register is allocatable (i.e. don't give out the
1953    // stack pointer).
1954    const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1955    if (!RC) {
1956      // Make sure we find consecutive registers.
1957      NumAllocated = 0;
1958      continue;
1959    }
1960
1961    // Okay, this register is good, we can use it.
1962    ++NumAllocated;
1963
1964    // If we allocated enough consecutive
1965    if (NumAllocated == NumRegs) {
1966      unsigned RegStart = (i-NumAllocated)+1;
1967      unsigned RegEnd   = i+1;
1968      // Mark all of the allocated registers used.
1969      for (unsigned i = RegStart; i != RegEnd; ++i) {
1970        unsigned Reg = RegClassRegs[i];
1971        Regs.push_back(Reg);
1972        if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
1973        if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
1974      }
1975
1976      return RegsForValue(Regs, *RC->vt_begin(), VT);
1977    }
1978  }
1979
1980  // Otherwise, we couldn't allocate enough registers for this.
1981  return RegsForValue();
1982}
1983
1984
1985/// visitInlineAsm - Handle a call to an InlineAsm object.
1986///
1987void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1988  InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1989
1990  SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1991                                                 MVT::Other);
1992
1993  // Note, we treat inline asms both with and without side-effects as the same.
1994  // If an inline asm doesn't have side effects and doesn't access memory, we
1995  // could not choose to not chain it.
1996  bool hasSideEffects = IA->hasSideEffects();
1997
1998  std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1999  std::vector<MVT::ValueType> ConstraintVTs;
2000
2001  /// AsmNodeOperands - A list of pairs.  The first element is a register, the
2002  /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2003  /// if it is a def of that register.
2004  std::vector<SDOperand> AsmNodeOperands;
2005  AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
2006  AsmNodeOperands.push_back(AsmStr);
2007
2008  SDOperand Chain = getRoot();
2009  SDOperand Flag;
2010
2011  // We fully assign registers here at isel time.  This is not optimal, but
2012  // should work.  For register classes that correspond to LLVM classes, we
2013  // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
2014  // over the constraints, collecting fixed registers that we know we can't use.
2015  std::set<unsigned> OutputRegs, InputRegs;
2016  unsigned OpNum = 1;
2017  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2018    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2019    std::string &ConstraintCode = Constraints[i].Codes[0];
2020
2021    MVT::ValueType OpVT;
2022
2023    // Compute the value type for each operand and add it to ConstraintVTs.
2024    switch (Constraints[i].Type) {
2025    case InlineAsm::isOutput:
2026      if (!Constraints[i].isIndirectOutput) {
2027        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2028        OpVT = TLI.getValueType(I.getType());
2029      } else {
2030        const Type *OpTy = I.getOperand(OpNum)->getType();
2031        OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2032        OpNum++;  // Consumes a call operand.
2033      }
2034      break;
2035    case InlineAsm::isInput:
2036      OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2037      OpNum++;  // Consumes a call operand.
2038      break;
2039    case InlineAsm::isClobber:
2040      OpVT = MVT::Other;
2041      break;
2042    }
2043
2044    ConstraintVTs.push_back(OpVT);
2045
2046    if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2047      continue;  // Not assigned a fixed reg.
2048
2049    // Build a list of regs that this operand uses.  This always has a single
2050    // element for promoted/expanded operands.
2051    RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2052                                             false, false,
2053                                             OutputRegs, InputRegs);
2054
2055    switch (Constraints[i].Type) {
2056    case InlineAsm::isOutput:
2057      // We can't assign any other output to this register.
2058      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2059      // If this is an early-clobber output, it cannot be assigned to the same
2060      // value as the input reg.
2061      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2062        InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2063      break;
2064    case InlineAsm::isInput:
2065      // We can't assign any other input to this register.
2066      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2067      break;
2068    case InlineAsm::isClobber:
2069      // Clobbered regs cannot be used as inputs or outputs.
2070      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2071      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2072      break;
2073    }
2074  }
2075
2076  // Loop over all of the inputs, copying the operand values into the
2077  // appropriate registers and processing the output regs.
2078  RegsForValue RetValRegs;
2079  std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2080  OpNum = 1;
2081
2082  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2083    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2084    std::string &ConstraintCode = Constraints[i].Codes[0];
2085
2086    switch (Constraints[i].Type) {
2087    case InlineAsm::isOutput: {
2088      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2089      if (ConstraintCode.size() == 1)   // not a physreg name.
2090        CTy = TLI.getConstraintType(ConstraintCode[0]);
2091
2092      if (CTy == TargetLowering::C_Memory) {
2093        // Memory output.
2094        SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2095
2096        // Check that the operand (the address to store to) isn't a float.
2097        if (!MVT::isInteger(InOperandVal.getValueType()))
2098          assert(0 && "MATCH FAIL!");
2099
2100        if (!Constraints[i].isIndirectOutput)
2101          assert(0 && "MATCH FAIL!");
2102
2103        OpNum++;  // Consumes a call operand.
2104
2105        // Extend/truncate to the right pointer type if needed.
2106        MVT::ValueType PtrType = TLI.getPointerTy();
2107        if (InOperandVal.getValueType() < PtrType)
2108          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2109        else if (InOperandVal.getValueType() > PtrType)
2110          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2111
2112        // Add information to the INLINEASM node to know about this output.
2113        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2114        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2115        AsmNodeOperands.push_back(InOperandVal);
2116        break;
2117      }
2118
2119      // Otherwise, this is a register output.
2120      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2121
2122      // If this is an early-clobber output, or if there is an input
2123      // constraint that matches this, we need to reserve the input register
2124      // so no other inputs allocate to it.
2125      bool UsesInputRegister = false;
2126      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2127        UsesInputRegister = true;
2128
2129      // Copy the output from the appropriate register.  Find a register that
2130      // we can use.
2131      RegsForValue Regs =
2132        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2133                             true, UsesInputRegister,
2134                             OutputRegs, InputRegs);
2135      assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2136
2137      if (!Constraints[i].isIndirectOutput) {
2138        assert(RetValRegs.Regs.empty() &&
2139               "Cannot have multiple output constraints yet!");
2140        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2141        RetValRegs = Regs;
2142      } else {
2143        IndirectStoresToEmit.push_back(std::make_pair(Regs,
2144                                                      I.getOperand(OpNum)));
2145        OpNum++;  // Consumes a call operand.
2146      }
2147
2148      // Add information to the INLINEASM node to know that this register is
2149      // set.
2150      Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2151      break;
2152    }
2153    case InlineAsm::isInput: {
2154      SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2155      OpNum++;  // Consumes a call operand.
2156
2157      if (isdigit(ConstraintCode[0])) {    // Matching constraint?
2158        // If this is required to match an output register we have already set,
2159        // just use its register.
2160        unsigned OperandNo = atoi(ConstraintCode.c_str());
2161
2162        // Scan until we find the definition we already emitted of this operand.
2163        // When we find it, create a RegsForValue operand.
2164        unsigned CurOp = 2;  // The first operand.
2165        for (; OperandNo; --OperandNo) {
2166          // Advance to the next operand.
2167          unsigned NumOps =
2168            cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2169          assert((NumOps & 7) == 2 /*REGDEF*/ &&
2170                 "Skipped past definitions?");
2171          CurOp += (NumOps>>3)+1;
2172        }
2173
2174        unsigned NumOps =
2175          cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2176        assert((NumOps & 7) == 2 /*REGDEF*/ &&
2177               "Skipped past definitions?");
2178
2179        // Add NumOps>>3 registers to MatchedRegs.
2180        RegsForValue MatchedRegs;
2181        MatchedRegs.ValueVT = InOperandVal.getValueType();
2182        MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
2183        for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2184          unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2185          MatchedRegs.Regs.push_back(Reg);
2186        }
2187
2188        // Use the produced MatchedRegs object to
2189        MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2190                                  TLI.getPointerTy());
2191        MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2192        break;
2193      }
2194
2195      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2196      if (ConstraintCode.size() == 1)   // not a physreg name.
2197        CTy = TLI.getConstraintType(ConstraintCode[0]);
2198
2199      if (CTy == TargetLowering::C_Other) {
2200        if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2201          assert(0 && "MATCH FAIL!");
2202
2203        // Add information to the INLINEASM node to know about this input.
2204        unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2205        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2206        AsmNodeOperands.push_back(InOperandVal);
2207        break;
2208      } else if (CTy == TargetLowering::C_Memory) {
2209        // Memory input.
2210
2211        // Check that the operand isn't a float.
2212        if (!MVT::isInteger(InOperandVal.getValueType()))
2213          assert(0 && "MATCH FAIL!");
2214
2215        // Extend/truncate to the right pointer type if needed.
2216        MVT::ValueType PtrType = TLI.getPointerTy();
2217        if (InOperandVal.getValueType() < PtrType)
2218          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2219        else if (InOperandVal.getValueType() > PtrType)
2220          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2221
2222        // Add information to the INLINEASM node to know about this input.
2223        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2224        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2225        AsmNodeOperands.push_back(InOperandVal);
2226        break;
2227      }
2228
2229      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2230
2231      // Copy the input into the appropriate registers.
2232      RegsForValue InRegs =
2233        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2234                             false, true, OutputRegs, InputRegs);
2235      // FIXME: should be match fail.
2236      assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2237
2238      InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2239
2240      InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2241      break;
2242    }
2243    case InlineAsm::isClobber: {
2244      RegsForValue ClobberedRegs =
2245        GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2246                             OutputRegs, InputRegs);
2247      // Add the clobbered value to the operand list, so that the register
2248      // allocator is aware that the physreg got clobbered.
2249      if (!ClobberedRegs.Regs.empty())
2250        ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2251      break;
2252    }
2253    }
2254  }
2255
2256  // Finish up input operands.
2257  AsmNodeOperands[0] = Chain;
2258  if (Flag.Val) AsmNodeOperands.push_back(Flag);
2259
2260  std::vector<MVT::ValueType> VTs;
2261  VTs.push_back(MVT::Other);
2262  VTs.push_back(MVT::Flag);
2263  Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2264  Flag = Chain.getValue(1);
2265
2266  // If this asm returns a register value, copy the result from that register
2267  // and set it as the value of the call.
2268  if (!RetValRegs.Regs.empty())
2269    setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2270
2271  std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2272
2273  // Process indirect outputs, first output all of the flagged copies out of
2274  // physregs.
2275  for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2276    RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2277    Value *Ptr = IndirectStoresToEmit[i].second;
2278    SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2279    StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2280  }
2281
2282  // Emit the non-flagged stores from the physregs.
2283  std::vector<SDOperand> OutChains;
2284  for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2285    OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2286                                    StoresToEmit[i].first,
2287                                    getValue(StoresToEmit[i].second),
2288                                    DAG.getSrcValue(StoresToEmit[i].second)));
2289  if (!OutChains.empty())
2290    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2291  DAG.setRoot(Chain);
2292}
2293
2294
2295void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2296  SDOperand Src = getValue(I.getOperand(0));
2297
2298  MVT::ValueType IntPtr = TLI.getPointerTy();
2299
2300  if (IntPtr < Src.getValueType())
2301    Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2302  else if (IntPtr > Src.getValueType())
2303    Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2304
2305  // Scale the source by the type size.
2306  uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2307  Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2308                    Src, getIntPtrConstant(ElementSize));
2309
2310  std::vector<std::pair<SDOperand, const Type*> > Args;
2311  Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2312
2313  std::pair<SDOperand,SDOperand> Result =
2314    TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2315                    DAG.getExternalSymbol("malloc", IntPtr),
2316                    Args, DAG);
2317  setValue(&I, Result.first);  // Pointers always fit in registers
2318  DAG.setRoot(Result.second);
2319}
2320
2321void SelectionDAGLowering::visitFree(FreeInst &I) {
2322  std::vector<std::pair<SDOperand, const Type*> > Args;
2323  Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2324                                TLI.getTargetData()->getIntPtrType()));
2325  MVT::ValueType IntPtr = TLI.getPointerTy();
2326  std::pair<SDOperand,SDOperand> Result =
2327    TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2328                    DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2329  DAG.setRoot(Result.second);
2330}
2331
2332// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2333// mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
2334// instructions are special in various ways, which require special support to
2335// insert.  The specified MachineInstr is created but not inserted into any
2336// basic blocks, and the scheduler passes ownership of it to this method.
2337MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2338                                                       MachineBasicBlock *MBB) {
2339  std::cerr << "If a target marks an instruction with "
2340               "'usesCustomDAGSchedInserter', it must implement "
2341               "TargetLowering::InsertAtEndOfBasicBlock!\n";
2342  abort();
2343  return 0;
2344}
2345
2346void SelectionDAGLowering::visitVAStart(CallInst &I) {
2347  DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2348                          getValue(I.getOperand(1)),
2349                          DAG.getSrcValue(I.getOperand(1))));
2350}
2351
2352void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2353  SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2354                             getValue(I.getOperand(0)),
2355                             DAG.getSrcValue(I.getOperand(0)));
2356  setValue(&I, V);
2357  DAG.setRoot(V.getValue(1));
2358}
2359
2360void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2361  DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2362                          getValue(I.getOperand(1)),
2363                          DAG.getSrcValue(I.getOperand(1))));
2364}
2365
2366void SelectionDAGLowering::visitVACopy(CallInst &I) {
2367  DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2368                          getValue(I.getOperand(1)),
2369                          getValue(I.getOperand(2)),
2370                          DAG.getSrcValue(I.getOperand(1)),
2371                          DAG.getSrcValue(I.getOperand(2))));
2372}
2373
2374/// TargetLowering::LowerArguments - This is the default LowerArguments
2375/// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
2376/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2377/// integrated into SDISel.
2378std::vector<SDOperand>
2379TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2380  // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2381  std::vector<SDOperand> Ops;
2382  Ops.push_back(DAG.getRoot());
2383  Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2384  Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2385
2386  // Add one result value for each formal argument.
2387  std::vector<MVT::ValueType> RetVals;
2388  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2389    MVT::ValueType VT = getValueType(I->getType());
2390
2391    switch (getTypeAction(VT)) {
2392    default: assert(0 && "Unknown type action!");
2393    case Legal:
2394      RetVals.push_back(VT);
2395      break;
2396    case Promote:
2397      RetVals.push_back(getTypeToTransformTo(VT));
2398      break;
2399    case Expand:
2400      if (VT != MVT::Vector) {
2401        // If this is a large integer, it needs to be broken up into small
2402        // integers.  Figure out what the destination type is and how many small
2403        // integers it turns into.
2404        MVT::ValueType NVT = getTypeToTransformTo(VT);
2405        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2406        for (unsigned i = 0; i != NumVals; ++i)
2407          RetVals.push_back(NVT);
2408      } else {
2409        // Otherwise, this is a vector type.  We only support legal vectors
2410        // right now.
2411        unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2412        const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2413
2414        // Figure out if there is a Packed type corresponding to this Vector
2415        // type.  If so, convert to the packed type.
2416        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2417        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2418          RetVals.push_back(TVT);
2419        } else {
2420          assert(0 && "Don't support illegal by-val vector arguments yet!");
2421        }
2422      }
2423      break;
2424    }
2425  }
2426
2427  RetVals.push_back(MVT::Other);
2428
2429  // Create the node.
2430  SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2431
2432  DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2433
2434  // Set up the return result vector.
2435  Ops.clear();
2436  unsigned i = 0;
2437  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2438    MVT::ValueType VT = getValueType(I->getType());
2439
2440    switch (getTypeAction(VT)) {
2441    default: assert(0 && "Unknown type action!");
2442    case Legal:
2443      Ops.push_back(SDOperand(Result, i++));
2444      break;
2445    case Promote: {
2446      SDOperand Op(Result, i++);
2447      if (MVT::isInteger(VT)) {
2448        unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2449                                                     : ISD::AssertZext;
2450        Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2451        Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2452      } else {
2453        assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2454        Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2455      }
2456      Ops.push_back(Op);
2457      break;
2458    }
2459    case Expand:
2460      if (VT != MVT::Vector) {
2461        // If this is a large integer, it needs to be reassembled from small
2462        // integers.  Figure out what the source elt type is and how many small
2463        // integers it is.
2464        MVT::ValueType NVT = getTypeToTransformTo(VT);
2465        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2466        if (NumVals == 2) {
2467          SDOperand Lo = SDOperand(Result, i++);
2468          SDOperand Hi = SDOperand(Result, i++);
2469
2470          if (!isLittleEndian())
2471            std::swap(Lo, Hi);
2472
2473          Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2474        } else {
2475          // Value scalarized into many values.  Unimp for now.
2476          assert(0 && "Cannot expand i64 -> i16 yet!");
2477        }
2478      } else {
2479        // Otherwise, this is a vector type.  We only support legal vectors
2480        // right now.
2481        const PackedType *PTy = cast<PackedType>(I->getType());
2482        unsigned NumElems = PTy->getNumElements();
2483        const Type *EltTy = PTy->getElementType();
2484
2485        // Figure out if there is a Packed type corresponding to this Vector
2486        // type.  If so, convert to the packed type.
2487        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2488        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2489          SDOperand N = SDOperand(Result, i++);
2490          // Handle copies from generic vectors to registers.
2491          N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2492                          DAG.getConstant(NumElems, MVT::i32),
2493                          DAG.getValueType(getValueType(EltTy)));
2494          Ops.push_back(N);
2495        } else {
2496          assert(0 && "Don't support illegal by-val vector arguments yet!");
2497          abort();
2498        }
2499      }
2500      break;
2501    }
2502  }
2503  return Ops;
2504}
2505
2506
2507/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2508/// implementation, which just inserts an ISD::CALL node, which is later custom
2509/// lowered by the target to something concrete.  FIXME: When all targets are
2510/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2511std::pair<SDOperand, SDOperand>
2512TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2513                            unsigned CallingConv, bool isTailCall,
2514                            SDOperand Callee,
2515                            ArgListTy &Args, SelectionDAG &DAG) {
2516  std::vector<SDOperand> Ops;
2517  Ops.push_back(Chain);   // Op#0 - Chain
2518  Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2519  Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
2520  Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
2521  Ops.push_back(Callee);
2522
2523  // Handle all of the outgoing arguments.
2524  for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2525    MVT::ValueType VT = getValueType(Args[i].second);
2526    SDOperand Op = Args[i].first;
2527    bool isSigned = Args[i].second->isSigned();
2528    switch (getTypeAction(VT)) {
2529    default: assert(0 && "Unknown type action!");
2530    case Legal:
2531      Ops.push_back(Op);
2532      Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2533      break;
2534    case Promote:
2535      if (MVT::isInteger(VT)) {
2536        unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2537        Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2538      } else {
2539        assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2540        Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2541      }
2542      Ops.push_back(Op);
2543      Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2544      break;
2545    case Expand:
2546      if (VT != MVT::Vector) {
2547        // If this is a large integer, it needs to be broken down into small
2548        // integers.  Figure out what the source elt type is and how many small
2549        // integers it is.
2550        MVT::ValueType NVT = getTypeToTransformTo(VT);
2551        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2552        if (NumVals == 2) {
2553          SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2554                                     DAG.getConstant(0, getPointerTy()));
2555          SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2556                                     DAG.getConstant(1, getPointerTy()));
2557          if (!isLittleEndian())
2558            std::swap(Lo, Hi);
2559
2560          Ops.push_back(Lo);
2561          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2562          Ops.push_back(Hi);
2563          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2564        } else {
2565          // Value scalarized into many values.  Unimp for now.
2566          assert(0 && "Cannot expand i64 -> i16 yet!");
2567        }
2568      } else {
2569        // Otherwise, this is a vector type.  We only support legal vectors
2570        // right now.
2571        const PackedType *PTy = cast<PackedType>(Args[i].second);
2572        unsigned NumElems = PTy->getNumElements();
2573        const Type *EltTy = PTy->getElementType();
2574
2575        // Figure out if there is a Packed type corresponding to this Vector
2576        // type.  If so, convert to the packed type.
2577        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2578        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2579          // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2580          Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2581          Ops.push_back(Op);
2582          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2583        } else {
2584          assert(0 && "Don't support illegal by-val vector call args yet!");
2585          abort();
2586        }
2587      }
2588      break;
2589    }
2590  }
2591
2592  // Figure out the result value types.
2593  std::vector<MVT::ValueType> RetTys;
2594
2595  if (RetTy != Type::VoidTy) {
2596    MVT::ValueType VT = getValueType(RetTy);
2597    switch (getTypeAction(VT)) {
2598    default: assert(0 && "Unknown type action!");
2599    case Legal:
2600      RetTys.push_back(VT);
2601      break;
2602    case Promote:
2603      RetTys.push_back(getTypeToTransformTo(VT));
2604      break;
2605    case Expand:
2606      if (VT != MVT::Vector) {
2607        // If this is a large integer, it needs to be reassembled from small
2608        // integers.  Figure out what the source elt type is and how many small
2609        // integers it is.
2610        MVT::ValueType NVT = getTypeToTransformTo(VT);
2611        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2612        for (unsigned i = 0; i != NumVals; ++i)
2613          RetTys.push_back(NVT);
2614      } else {
2615        // Otherwise, this is a vector type.  We only support legal vectors
2616        // right now.
2617        const PackedType *PTy = cast<PackedType>(RetTy);
2618        unsigned NumElems = PTy->getNumElements();
2619        const Type *EltTy = PTy->getElementType();
2620
2621        // Figure out if there is a Packed type corresponding to this Vector
2622        // type.  If so, convert to the packed type.
2623        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2624        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2625          RetTys.push_back(TVT);
2626        } else {
2627          assert(0 && "Don't support illegal by-val vector call results yet!");
2628          abort();
2629        }
2630      }
2631    }
2632  }
2633
2634  RetTys.push_back(MVT::Other);  // Always has a chain.
2635
2636  // Finally, create the CALL node.
2637  SDOperand Res = DAG.getNode(ISD::CALL, RetTys, Ops);
2638
2639  // This returns a pair of operands.  The first element is the
2640  // return value for the function (if RetTy is not VoidTy).  The second
2641  // element is the outgoing token chain.
2642  SDOperand ResVal;
2643  if (RetTys.size() != 1) {
2644    MVT::ValueType VT = getValueType(RetTy);
2645    if (RetTys.size() == 2) {
2646      ResVal = Res;
2647
2648      // If this value was promoted, truncate it down.
2649      if (ResVal.getValueType() != VT) {
2650        if (VT == MVT::Vector) {
2651          // Insert a VBITCONVERT to convert from the packed result type to the
2652          // MVT::Vector type.
2653          unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2654          const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2655
2656          // Figure out if there is a Packed type corresponding to this Vector
2657          // type.  If so, convert to the packed type.
2658          MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2659          if (TVT != MVT::Other && isTypeLegal(TVT)) {
2660            // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2661            // "N x PTyElementVT" MVT::Vector type.
2662            ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
2663                                 DAG.getConstant(NumElems, MVT::i32),
2664                                 DAG.getValueType(getValueType(EltTy)));
2665          } else {
2666            abort();
2667          }
2668        } else if (MVT::isInteger(VT)) {
2669          unsigned AssertOp = RetTy->isSigned() ?
2670                                  ISD::AssertSext : ISD::AssertZext;
2671          ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2672                               DAG.getValueType(VT));
2673          ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2674        } else {
2675          assert(MVT::isFloatingPoint(VT));
2676          ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2677        }
2678      }
2679    } else if (RetTys.size() == 3) {
2680      ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2681                           Res.getValue(0), Res.getValue(1));
2682
2683    } else {
2684      assert(0 && "Case not handled yet!");
2685    }
2686  }
2687
2688  return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2689}
2690
2691
2692
2693// It is always conservatively correct for llvm.returnaddress and
2694// llvm.frameaddress to return 0.
2695//
2696// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2697// expanded to 0 if the target wants.
2698std::pair<SDOperand, SDOperand>
2699TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2700                                        unsigned Depth, SelectionDAG &DAG) {
2701  return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2702}
2703
2704SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2705  assert(0 && "LowerOperation not implemented for this target!");
2706  abort();
2707  return SDOperand();
2708}
2709
2710SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2711                                                 SelectionDAG &DAG) {
2712  assert(0 && "CustomPromoteOperation not implemented for this target!");
2713  abort();
2714  return SDOperand();
2715}
2716
2717void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2718  unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2719  std::pair<SDOperand,SDOperand> Result =
2720    TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2721  setValue(&I, Result.first);
2722  DAG.setRoot(Result.second);
2723}
2724
2725/// getMemsetValue - Vectorized representation of the memset value
2726/// operand.
2727static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2728                                SelectionDAG &DAG) {
2729  MVT::ValueType CurVT = VT;
2730  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2731    uint64_t Val   = C->getValue() & 255;
2732    unsigned Shift = 8;
2733    while (CurVT != MVT::i8) {
2734      Val = (Val << Shift) | Val;
2735      Shift <<= 1;
2736      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2737    }
2738    return DAG.getConstant(Val, VT);
2739  } else {
2740    Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2741    unsigned Shift = 8;
2742    while (CurVT != MVT::i8) {
2743      Value =
2744        DAG.getNode(ISD::OR, VT,
2745                    DAG.getNode(ISD::SHL, VT, Value,
2746                                DAG.getConstant(Shift, MVT::i8)), Value);
2747      Shift <<= 1;
2748      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2749    }
2750
2751    return Value;
2752  }
2753}
2754
2755/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2756/// used when a memcpy is turned into a memset when the source is a constant
2757/// string ptr.
2758static SDOperand getMemsetStringVal(MVT::ValueType VT,
2759                                    SelectionDAG &DAG, TargetLowering &TLI,
2760                                    std::string &Str, unsigned Offset) {
2761  MVT::ValueType CurVT = VT;
2762  uint64_t Val = 0;
2763  unsigned MSB = getSizeInBits(VT) / 8;
2764  if (TLI.isLittleEndian())
2765    Offset = Offset + MSB - 1;
2766  for (unsigned i = 0; i != MSB; ++i) {
2767    Val = (Val << 8) | Str[Offset];
2768    Offset += TLI.isLittleEndian() ? -1 : 1;
2769  }
2770  return DAG.getConstant(Val, VT);
2771}
2772
2773/// getMemBasePlusOffset - Returns base and offset node for the
2774static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2775                                      SelectionDAG &DAG, TargetLowering &TLI) {
2776  MVT::ValueType VT = Base.getValueType();
2777  return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2778}
2779
2780/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2781/// to replace the memset / memcpy is below the threshold. It also returns the
2782/// types of the sequence of  memory ops to perform memset / memcpy.
2783static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2784                                     unsigned Limit, uint64_t Size,
2785                                     unsigned Align, TargetLowering &TLI) {
2786  MVT::ValueType VT;
2787
2788  if (TLI.allowsUnalignedMemoryAccesses()) {
2789    VT = MVT::i64;
2790  } else {
2791    switch (Align & 7) {
2792    case 0:
2793      VT = MVT::i64;
2794      break;
2795    case 4:
2796      VT = MVT::i32;
2797      break;
2798    case 2:
2799      VT = MVT::i16;
2800      break;
2801    default:
2802      VT = MVT::i8;
2803      break;
2804    }
2805  }
2806
2807  MVT::ValueType LVT = MVT::i64;
2808  while (!TLI.isTypeLegal(LVT))
2809    LVT = (MVT::ValueType)((unsigned)LVT - 1);
2810  assert(MVT::isInteger(LVT));
2811
2812  if (VT > LVT)
2813    VT = LVT;
2814
2815  unsigned NumMemOps = 0;
2816  while (Size != 0) {
2817    unsigned VTSize = getSizeInBits(VT) / 8;
2818    while (VTSize > Size) {
2819      VT = (MVT::ValueType)((unsigned)VT - 1);
2820      VTSize >>= 1;
2821    }
2822    assert(MVT::isInteger(VT));
2823
2824    if (++NumMemOps > Limit)
2825      return false;
2826    MemOps.push_back(VT);
2827    Size -= VTSize;
2828  }
2829
2830  return true;
2831}
2832
2833void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2834  SDOperand Op1 = getValue(I.getOperand(1));
2835  SDOperand Op2 = getValue(I.getOperand(2));
2836  SDOperand Op3 = getValue(I.getOperand(3));
2837  SDOperand Op4 = getValue(I.getOperand(4));
2838  unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2839  if (Align == 0) Align = 1;
2840
2841  if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2842    std::vector<MVT::ValueType> MemOps;
2843
2844    // Expand memset / memcpy to a series of load / store ops
2845    // if the size operand falls below a certain threshold.
2846    std::vector<SDOperand> OutChains;
2847    switch (Op) {
2848    default: break;  // Do nothing for now.
2849    case ISD::MEMSET: {
2850      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2851                                   Size->getValue(), Align, TLI)) {
2852        unsigned NumMemOps = MemOps.size();
2853        unsigned Offset = 0;
2854        for (unsigned i = 0; i < NumMemOps; i++) {
2855          MVT::ValueType VT = MemOps[i];
2856          unsigned VTSize = getSizeInBits(VT) / 8;
2857          SDOperand Value = getMemsetValue(Op2, VT, DAG);
2858          SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2859                                        Value,
2860                                    getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2861                                      DAG.getSrcValue(I.getOperand(1), Offset));
2862          OutChains.push_back(Store);
2863          Offset += VTSize;
2864        }
2865      }
2866      break;
2867    }
2868    case ISD::MEMCPY: {
2869      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2870                                   Size->getValue(), Align, TLI)) {
2871        unsigned NumMemOps = MemOps.size();
2872        unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2873        GlobalAddressSDNode *G = NULL;
2874        std::string Str;
2875        bool CopyFromStr = false;
2876
2877        if (Op2.getOpcode() == ISD::GlobalAddress)
2878          G = cast<GlobalAddressSDNode>(Op2);
2879        else if (Op2.getOpcode() == ISD::ADD &&
2880                 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2881                 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2882          G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2883          SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2884        }
2885        if (G) {
2886          GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2887          if (GV) {
2888            Str = GV->getStringValue(false);
2889            if (!Str.empty()) {
2890              CopyFromStr = true;
2891              SrcOff += SrcDelta;
2892            }
2893          }
2894        }
2895
2896        for (unsigned i = 0; i < NumMemOps; i++) {
2897          MVT::ValueType VT = MemOps[i];
2898          unsigned VTSize = getSizeInBits(VT) / 8;
2899          SDOperand Value, Chain, Store;
2900
2901          if (CopyFromStr) {
2902            Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2903            Chain = getRoot();
2904            Store =
2905              DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2906                          getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2907                          DAG.getSrcValue(I.getOperand(1), DstOff));
2908          } else {
2909            Value = DAG.getLoad(VT, getRoot(),
2910                        getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2911                        DAG.getSrcValue(I.getOperand(2), SrcOff));
2912            Chain = Value.getValue(1);
2913            Store =
2914              DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2915                          getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2916                          DAG.getSrcValue(I.getOperand(1), DstOff));
2917          }
2918          OutChains.push_back(Store);
2919          SrcOff += VTSize;
2920          DstOff += VTSize;
2921        }
2922      }
2923      break;
2924    }
2925    }
2926
2927    if (!OutChains.empty()) {
2928      DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2929      return;
2930    }
2931  }
2932
2933  std::vector<SDOperand> Ops;
2934  Ops.push_back(getRoot());
2935  Ops.push_back(Op1);
2936  Ops.push_back(Op2);
2937  Ops.push_back(Op3);
2938  Ops.push_back(Op4);
2939  DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2940}
2941
2942//===----------------------------------------------------------------------===//
2943// SelectionDAGISel code
2944//===----------------------------------------------------------------------===//
2945
2946unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2947  return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2948}
2949
2950void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2951  // FIXME: we only modify the CFG to split critical edges.  This
2952  // updates dom and loop info.
2953}
2954
2955
2956/// OptimizeNoopCopyExpression - We have determined that the specified cast
2957/// instruction is a noop copy (e.g. it's casting from one pointer type to
2958/// another, int->uint, or int->sbyte on PPC.
2959///
2960/// Return true if any changes are made.
2961static bool OptimizeNoopCopyExpression(CastInst *CI) {
2962  BasicBlock *DefBB = CI->getParent();
2963
2964  /// InsertedCasts - Only insert a cast in each block once.
2965  std::map<BasicBlock*, CastInst*> InsertedCasts;
2966
2967  bool MadeChange = false;
2968  for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2969       UI != E; ) {
2970    Use &TheUse = UI.getUse();
2971    Instruction *User = cast<Instruction>(*UI);
2972
2973    // Figure out which BB this cast is used in.  For PHI's this is the
2974    // appropriate predecessor block.
2975    BasicBlock *UserBB = User->getParent();
2976    if (PHINode *PN = dyn_cast<PHINode>(User)) {
2977      unsigned OpVal = UI.getOperandNo()/2;
2978      UserBB = PN->getIncomingBlock(OpVal);
2979    }
2980
2981    // Preincrement use iterator so we don't invalidate it.
2982    ++UI;
2983
2984    // If this user is in the same block as the cast, don't change the cast.
2985    if (UserBB == DefBB) continue;
2986
2987    // If we have already inserted a cast into this block, use it.
2988    CastInst *&InsertedCast = InsertedCasts[UserBB];
2989
2990    if (!InsertedCast) {
2991      BasicBlock::iterator InsertPt = UserBB->begin();
2992      while (isa<PHINode>(InsertPt)) ++InsertPt;
2993
2994      InsertedCast =
2995        new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2996      MadeChange = true;
2997    }
2998
2999    // Replace a use of the cast with a use of the new casat.
3000    TheUse = InsertedCast;
3001  }
3002
3003  // If we removed all uses, nuke the cast.
3004  if (CI->use_empty())
3005    CI->eraseFromParent();
3006
3007  return MadeChange;
3008}
3009
3010/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3011/// casting to the type of GEPI.
3012static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3013                                         Instruction *GEPI, Value *Ptr,
3014                                         Value *PtrOffset) {
3015  if (V) return V;   // Already computed.
3016
3017  BasicBlock::iterator InsertPt;
3018  if (BB == GEPI->getParent()) {
3019    // If insert into the GEP's block, insert right after the GEP.
3020    InsertPt = GEPI;
3021    ++InsertPt;
3022  } else {
3023    // Otherwise, insert at the top of BB, after any PHI nodes
3024    InsertPt = BB->begin();
3025    while (isa<PHINode>(InsertPt)) ++InsertPt;
3026  }
3027
3028  // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3029  // BB so that there is only one value live across basic blocks (the cast
3030  // operand).
3031  if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3032    if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3033      Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3034
3035  // Add the offset, cast it to the right type.
3036  Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3037  return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3038}
3039
3040/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3041/// compute its value.  The RepPtr value can be computed with Ptr+PtrOffset. One
3042/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3043/// block, then ReplaceAllUsesWith'ing everything.  However, we would prefer to
3044/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3045/// the constant add into a load or store instruction.  Additionally, if a user
3046/// is a pointer-pointer cast, we look through it to find its users.
3047static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3048                                 Constant *PtrOffset, BasicBlock *DefBB,
3049                                 GetElementPtrInst *GEPI,
3050                           std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3051  while (!RepPtr->use_empty()) {
3052    Instruction *User = cast<Instruction>(RepPtr->use_back());
3053
3054    // If the user is a Pointer-Pointer cast, recurse.
3055    if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3056      ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3057
3058      // Drop the use of RepPtr. The cast is dead.  Don't delete it now, else we
3059      // could invalidate an iterator.
3060      User->setOperand(0, UndefValue::get(RepPtr->getType()));
3061      continue;
3062    }
3063
3064    // If this is a load of the pointer, or a store through the pointer, emit
3065    // the increment into the load/store block.
3066    Instruction *NewVal;
3067    if (isa<LoadInst>(User) ||
3068        (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3069      NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3070                                    User->getParent(), GEPI,
3071                                    Ptr, PtrOffset);
3072    } else {
3073      // If this use is not foldable into the addressing mode, use a version
3074      // emitted in the GEP block.
3075      NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3076                                    Ptr, PtrOffset);
3077    }
3078
3079    if (GEPI->getType() != RepPtr->getType()) {
3080      BasicBlock::iterator IP = NewVal;
3081      ++IP;
3082      NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3083    }
3084    User->replaceUsesOfWith(RepPtr, NewVal);
3085  }
3086}
3087
3088
3089/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3090/// selection, we want to be a bit careful about some things.  In particular, if
3091/// we have a GEP instruction that is used in a different block than it is
3092/// defined, the addressing expression of the GEP cannot be folded into loads or
3093/// stores that use it.  In this case, decompose the GEP and move constant
3094/// indices into blocks that use it.
3095static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3096                                  const TargetData *TD) {
3097  // If this GEP is only used inside the block it is defined in, there is no
3098  // need to rewrite it.
3099  bool isUsedOutsideDefBB = false;
3100  BasicBlock *DefBB = GEPI->getParent();
3101  for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3102       UI != E; ++UI) {
3103    if (cast<Instruction>(*UI)->getParent() != DefBB) {
3104      isUsedOutsideDefBB = true;
3105      break;
3106    }
3107  }
3108  if (!isUsedOutsideDefBB) return false;
3109
3110  // If this GEP has no non-zero constant indices, there is nothing we can do,
3111  // ignore it.
3112  bool hasConstantIndex = false;
3113  bool hasVariableIndex = false;
3114  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3115       E = GEPI->op_end(); OI != E; ++OI) {
3116    if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3117      if (CI->getRawValue()) {
3118        hasConstantIndex = true;
3119        break;
3120      }
3121    } else {
3122      hasVariableIndex = true;
3123    }
3124  }
3125
3126  // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3127  if (!hasConstantIndex && !hasVariableIndex) {
3128    Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3129                             GEPI->getName(), GEPI);
3130    GEPI->replaceAllUsesWith(NC);
3131    GEPI->eraseFromParent();
3132    return true;
3133  }
3134
3135  // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3136  if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3137    return false;
3138
3139  // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
3140  // constant offset (which we now know is non-zero) and deal with it later.
3141  uint64_t ConstantOffset = 0;
3142  const Type *UIntPtrTy = TD->getIntPtrType();
3143  Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3144  const Type *Ty = GEPI->getOperand(0)->getType();
3145
3146  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3147       E = GEPI->op_end(); OI != E; ++OI) {
3148    Value *Idx = *OI;
3149    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3150      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
3151      if (Field)
3152        ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3153      Ty = StTy->getElementType(Field);
3154    } else {
3155      Ty = cast<SequentialType>(Ty)->getElementType();
3156
3157      // Handle constant subscripts.
3158      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3159        if (CI->getRawValue() == 0) continue;
3160
3161        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
3162          ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
3163        else
3164          ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
3165        continue;
3166      }
3167
3168      // Ptr = Ptr + Idx * ElementSize;
3169
3170      // Cast Idx to UIntPtrTy if needed.
3171      Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3172
3173      uint64_t ElementSize = TD->getTypeSize(Ty);
3174      // Mask off bits that should not be set.
3175      ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3176      Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
3177
3178      // Multiply by the element size and add to the base.
3179      Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3180      Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3181    }
3182  }
3183
3184  // Make sure that the offset fits in uintptr_t.
3185  ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3186  Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
3187
3188  // Okay, we have now emitted all of the variable index parts to the BB that
3189  // the GEP is defined in.  Loop over all of the using instructions, inserting
3190  // an "add Ptr, ConstantOffset" into each block that uses it and update the
3191  // instruction to use the newly computed value, making GEPI dead.  When the
3192  // user is a load or store instruction address, we emit the add into the user
3193  // block, otherwise we use a canonical version right next to the gep (these
3194  // won't be foldable as addresses, so we might as well share the computation).
3195
3196  std::map<BasicBlock*,Instruction*> InsertedExprs;
3197  ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3198
3199  // Finally, the GEP is dead, remove it.
3200  GEPI->eraseFromParent();
3201
3202  return true;
3203}
3204
3205bool SelectionDAGISel::runOnFunction(Function &Fn) {
3206  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3207  RegMap = MF.getSSARegMap();
3208  DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3209
3210  // First, split all critical edges for PHI nodes with incoming values that are
3211  // constants, this way the load of the constant into a vreg will not be placed
3212  // into MBBs that are used some other way.
3213  //
3214  // In this pass we also look for GEP and cast instructions that are used
3215  // across basic blocks and rewrite them to improve basic-block-at-a-time
3216  // selection.
3217  //
3218  //
3219  bool MadeChange = true;
3220  while (MadeChange) {
3221    MadeChange = false;
3222  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3223    PHINode *PN;
3224    BasicBlock::iterator BBI;
3225    for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
3226      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3227        if (isa<Constant>(PN->getIncomingValue(i)))
3228          SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3229
3230    for (BasicBlock::iterator E = BB->end(); BBI != E; ) {
3231      Instruction *I = BBI++;
3232      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3233        MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3234      } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3235        // If this is a noop copy, sink it into user blocks to reduce the number
3236        // of virtual registers that must be created and coallesced.
3237        MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3238        MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3239
3240        // This is an fp<->int conversion?
3241        if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3242          continue;
3243
3244        // If this is an extension, it will be a zero or sign extension, which
3245        // isn't a noop.
3246        if (SrcVT < DstVT) continue;
3247
3248        // If these values will be promoted, find out what they will be promoted
3249        // to.  This helps us consider truncates on PPC as noop copies when they
3250        // are.
3251        if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3252          SrcVT = TLI.getTypeToTransformTo(SrcVT);
3253        if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3254          DstVT = TLI.getTypeToTransformTo(DstVT);
3255
3256        // If, after promotion, these are the same types, this is a noop copy.
3257        if (SrcVT == DstVT)
3258          MadeChange |= OptimizeNoopCopyExpression(CI);
3259      }
3260    }
3261  }
3262  }
3263
3264  FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3265
3266  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3267    SelectBasicBlock(I, MF, FuncInfo);
3268
3269  return true;
3270}
3271
3272
3273SDOperand SelectionDAGISel::
3274CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
3275  SDOperand Op = SDL.getValue(V);
3276  assert((Op.getOpcode() != ISD::CopyFromReg ||
3277          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3278         "Copy from a reg to the same reg!");
3279
3280  // If this type is not legal, we must make sure to not create an invalid
3281  // register use.
3282  MVT::ValueType SrcVT = Op.getValueType();
3283  MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3284  SelectionDAG &DAG = SDL.DAG;
3285  if (SrcVT == DestVT) {
3286    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3287  } else if (SrcVT == MVT::Vector) {
3288    // Handle copies from generic vectors to registers.
3289    MVT::ValueType PTyElementVT, PTyLegalElementVT;
3290    unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3291                                             PTyElementVT, PTyLegalElementVT);
3292
3293    // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3294    // MVT::Vector type.
3295    Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3296                     DAG.getConstant(NE, MVT::i32),
3297                     DAG.getValueType(PTyElementVT));
3298
3299    // Loop over all of the elements of the resultant vector,
3300    // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3301    // copying them into output registers.
3302    std::vector<SDOperand> OutChains;
3303    SDOperand Root = SDL.getRoot();
3304    for (unsigned i = 0; i != NE; ++i) {
3305      SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3306                                  Op, DAG.getConstant(i, TLI.getPointerTy()));
3307      if (PTyElementVT == PTyLegalElementVT) {
3308        // Elements are legal.
3309        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3310      } else if (PTyLegalElementVT > PTyElementVT) {
3311        // Elements are promoted.
3312        if (MVT::isFloatingPoint(PTyLegalElementVT))
3313          Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3314        else
3315          Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3316        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3317      } else {
3318        // Elements are expanded.
3319        // The src value is expanded into multiple registers.
3320        SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3321                                   Elt, DAG.getConstant(0, TLI.getPointerTy()));
3322        SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3323                                   Elt, DAG.getConstant(1, TLI.getPointerTy()));
3324        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3325        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3326      }
3327    }
3328    return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
3329  } else if (SrcVT < DestVT) {
3330    // The src value is promoted to the register.
3331    if (MVT::isFloatingPoint(SrcVT))
3332      Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3333    else
3334      Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3335    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3336  } else  {
3337    // The src value is expanded into multiple registers.
3338    SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3339                               Op, DAG.getConstant(0, TLI.getPointerTy()));
3340    SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3341                               Op, DAG.getConstant(1, TLI.getPointerTy()));
3342    Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3343    return DAG.getCopyToReg(Op, Reg+1, Hi);
3344  }
3345}
3346
3347void SelectionDAGISel::
3348LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3349               std::vector<SDOperand> &UnorderedChains) {
3350  // If this is the entry block, emit arguments.
3351  Function &F = *BB->getParent();
3352  FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3353  SDOperand OldRoot = SDL.DAG.getRoot();
3354  std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3355
3356  unsigned a = 0;
3357  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3358       AI != E; ++AI, ++a)
3359    if (!AI->use_empty()) {
3360      SDL.setValue(AI, Args[a]);
3361
3362      // If this argument is live outside of the entry block, insert a copy from
3363      // whereever we got it to the vreg that other BB's will reference it as.
3364      if (FuncInfo.ValueMap.count(AI)) {
3365        SDOperand Copy =
3366          CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3367        UnorderedChains.push_back(Copy);
3368      }
3369    }
3370
3371  // Finally, if the target has anything special to do, allow it to do so.
3372  // FIXME: this should insert code into the DAG!
3373  EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3374}
3375
3376void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3377       std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3378                                         FunctionLoweringInfo &FuncInfo) {
3379  SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3380
3381  std::vector<SDOperand> UnorderedChains;
3382
3383  // Lower any arguments needed in this block if this is the entry block.
3384  if (LLVMBB == &LLVMBB->getParent()->front())
3385    LowerArguments(LLVMBB, SDL, UnorderedChains);
3386
3387  BB = FuncInfo.MBBMap[LLVMBB];
3388  SDL.setCurrentBasicBlock(BB);
3389
3390  // Lower all of the non-terminator instructions.
3391  for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3392       I != E; ++I)
3393    SDL.visit(*I);
3394
3395  // Ensure that all instructions which are used outside of their defining
3396  // blocks are available as virtual registers.
3397  for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3398    if (!I->use_empty() && !isa<PHINode>(I)) {
3399      std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3400      if (VMI != FuncInfo.ValueMap.end())
3401        UnorderedChains.push_back(
3402                           CopyValueToVirtualRegister(SDL, I, VMI->second));
3403    }
3404
3405  // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
3406  // ensure constants are generated when needed.  Remember the virtual registers
3407  // that need to be added to the Machine PHI nodes as input.  We cannot just
3408  // directly add them, because expansion might result in multiple MBB's for one
3409  // BB.  As such, the start of the BB might correspond to a different MBB than
3410  // the end.
3411  //
3412
3413  // Emit constants only once even if used by multiple PHI nodes.
3414  std::map<Constant*, unsigned> ConstantsOut;
3415
3416  // Check successor nodes PHI nodes that expect a constant to be available from
3417  // this block.
3418  TerminatorInst *TI = LLVMBB->getTerminator();
3419  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3420    BasicBlock *SuccBB = TI->getSuccessor(succ);
3421    MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3422    PHINode *PN;
3423
3424    // At this point we know that there is a 1-1 correspondence between LLVM PHI
3425    // nodes and Machine PHI nodes, but the incoming operands have not been
3426    // emitted yet.
3427    for (BasicBlock::iterator I = SuccBB->begin();
3428         (PN = dyn_cast<PHINode>(I)); ++I)
3429      if (!PN->use_empty()) {
3430        unsigned Reg;
3431        Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3432        if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3433          unsigned &RegOut = ConstantsOut[C];
3434          if (RegOut == 0) {
3435            RegOut = FuncInfo.CreateRegForValue(C);
3436            UnorderedChains.push_back(
3437                             CopyValueToVirtualRegister(SDL, C, RegOut));
3438          }
3439          Reg = RegOut;
3440        } else {
3441          Reg = FuncInfo.ValueMap[PHIOp];
3442          if (Reg == 0) {
3443            assert(isa<AllocaInst>(PHIOp) &&
3444                   FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3445                   "Didn't codegen value into a register!??");
3446            Reg = FuncInfo.CreateRegForValue(PHIOp);
3447            UnorderedChains.push_back(
3448                             CopyValueToVirtualRegister(SDL, PHIOp, Reg));
3449          }
3450        }
3451
3452        // Remember that this register needs to added to the machine PHI node as
3453        // the input for this MBB.
3454        MVT::ValueType VT = TLI.getValueType(PN->getType());
3455        unsigned NumElements;
3456        if (VT != MVT::Vector)
3457          NumElements = TLI.getNumElements(VT);
3458        else {
3459          MVT::ValueType VT1,VT2;
3460          NumElements =
3461            TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3462                                       VT1, VT2);
3463        }
3464        for (unsigned i = 0, e = NumElements; i != e; ++i)
3465          PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3466      }
3467  }
3468  ConstantsOut.clear();
3469
3470  // Turn all of the unordered chains into one factored node.
3471  if (!UnorderedChains.empty()) {
3472    SDOperand Root = SDL.getRoot();
3473    if (Root.getOpcode() != ISD::EntryToken) {
3474      unsigned i = 0, e = UnorderedChains.size();
3475      for (; i != e; ++i) {
3476        assert(UnorderedChains[i].Val->getNumOperands() > 1);
3477        if (UnorderedChains[i].Val->getOperand(0) == Root)
3478          break;  // Don't add the root if we already indirectly depend on it.
3479      }
3480
3481      if (i == e)
3482        UnorderedChains.push_back(Root);
3483    }
3484    DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3485  }
3486
3487  // Lower the terminator after the copies are emitted.
3488  SDL.visit(*LLVMBB->getTerminator());
3489
3490  // Copy over any CaseBlock records that may now exist due to SwitchInst
3491  // lowering, as well as any jump table information.
3492  SwitchCases.clear();
3493  SwitchCases = SDL.SwitchCases;
3494  JT = SDL.JT;
3495
3496  // Make sure the root of the DAG is up-to-date.
3497  DAG.setRoot(SDL.getRoot());
3498}
3499
3500void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3501  // Run the DAG combiner in pre-legalize mode.
3502  DAG.Combine(false);
3503
3504  DEBUG(std::cerr << "Lowered selection DAG:\n");
3505  DEBUG(DAG.dump());
3506
3507  // Second step, hack on the DAG until it only uses operations and types that
3508  // the target supports.
3509  DAG.Legalize();
3510
3511  DEBUG(std::cerr << "Legalized selection DAG:\n");
3512  DEBUG(DAG.dump());
3513
3514  // Run the DAG combiner in post-legalize mode.
3515  DAG.Combine(true);
3516
3517  if (ViewISelDAGs) DAG.viewGraph();
3518
3519  // Third, instruction select all of the operations to machine code, adding the
3520  // code to the MachineBasicBlock.
3521  InstructionSelectBasicBlock(DAG);
3522
3523  DEBUG(std::cerr << "Selected machine code:\n");
3524  DEBUG(BB->dump());
3525}
3526
3527void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3528                                        FunctionLoweringInfo &FuncInfo) {
3529  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3530  {
3531    SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3532    CurDAG = &DAG;
3533
3534    // First step, lower LLVM code to some DAG.  This DAG may use operations and
3535    // types that are not supported by the target.
3536    BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3537
3538    // Second step, emit the lowered DAG as machine code.
3539    CodeGenAndEmitDAG(DAG);
3540  }
3541
3542  // Next, now that we know what the last MBB the LLVM BB expanded is, update
3543  // PHI nodes in successors.
3544  if (SwitchCases.empty() && JT.Reg == 0) {
3545    for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3546      MachineInstr *PHI = PHINodesToUpdate[i].first;
3547      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3548             "This is not a machine PHI node that we are updating!");
3549      PHI->addRegOperand(PHINodesToUpdate[i].second);
3550      PHI->addMachineBasicBlockOperand(BB);
3551    }
3552    return;
3553  }
3554
3555  // If the JumpTable record is filled in, then we need to emit a jump table.
3556  // Updating the PHI nodes is tricky in this case, since we need to determine
3557  // whether the PHI is a successor of the range check MBB or the jump table MBB
3558  if (JT.Reg) {
3559    assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3560    SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3561    CurDAG = &SDAG;
3562    SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3563    MachineBasicBlock *RangeBB = BB;
3564    // Set the current basic block to the mbb we wish to insert the code into
3565    BB = JT.MBB;
3566    SDL.setCurrentBasicBlock(BB);
3567    // Emit the code
3568    SDL.visitJumpTable(JT);
3569    SDAG.setRoot(SDL.getRoot());
3570    CodeGenAndEmitDAG(SDAG);
3571    // Update PHI Nodes
3572    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3573      MachineInstr *PHI = PHINodesToUpdate[pi].first;
3574      MachineBasicBlock *PHIBB = PHI->getParent();
3575      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3576             "This is not a machine PHI node that we are updating!");
3577      if (PHIBB == JT.Default) {
3578        PHI->addRegOperand(PHINodesToUpdate[pi].second);
3579        PHI->addMachineBasicBlockOperand(RangeBB);
3580      }
3581      if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3582        PHI->addRegOperand(PHINodesToUpdate[pi].second);
3583        PHI->addMachineBasicBlockOperand(BB);
3584      }
3585    }
3586    return;
3587  }
3588
3589  // If we generated any switch lowering information, build and codegen any
3590  // additional DAGs necessary.
3591  for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3592    SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3593    CurDAG = &SDAG;
3594    SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3595    // Set the current basic block to the mbb we wish to insert the code into
3596    BB = SwitchCases[i].ThisBB;
3597    SDL.setCurrentBasicBlock(BB);
3598    // Emit the code
3599    SDL.visitSwitchCase(SwitchCases[i]);
3600    SDAG.setRoot(SDL.getRoot());
3601    CodeGenAndEmitDAG(SDAG);
3602    // Iterate over the phi nodes, if there is a phi node in a successor of this
3603    // block (for instance, the default block), then add a pair of operands to
3604    // the phi node for this block, as if we were coming from the original
3605    // BB before switch expansion.
3606    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3607      MachineInstr *PHI = PHINodesToUpdate[pi].first;
3608      MachineBasicBlock *PHIBB = PHI->getParent();
3609      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3610             "This is not a machine PHI node that we are updating!");
3611      if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3612        PHI->addRegOperand(PHINodesToUpdate[pi].second);
3613        PHI->addMachineBasicBlockOperand(BB);
3614      }
3615    }
3616  }
3617}
3618
3619//===----------------------------------------------------------------------===//
3620/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3621/// target node in the graph.
3622void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3623  if (ViewSchedDAGs) DAG.viewGraph();
3624  ScheduleDAG *SL = NULL;
3625
3626  switch (ISHeuristic) {
3627  default: assert(0 && "Unrecognized scheduling heuristic");
3628  case defaultScheduling:
3629    if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3630      SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3631    else {
3632      assert(TLI.getSchedulingPreference() ==
3633             TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
3634      SL = createBURRListDAGScheduler(DAG, BB);
3635    }
3636    break;
3637  case noScheduling:
3638    SL = createBFS_DAGScheduler(DAG, BB);
3639    break;
3640  case simpleScheduling:
3641    SL = createSimpleDAGScheduler(false, DAG, BB);
3642    break;
3643  case simpleNoItinScheduling:
3644    SL = createSimpleDAGScheduler(true, DAG, BB);
3645    break;
3646  case listSchedulingBURR:
3647    SL = createBURRListDAGScheduler(DAG, BB);
3648    break;
3649  case listSchedulingTDRR:
3650    SL = createTDRRListDAGScheduler(DAG, BB);
3651    break;
3652  case listSchedulingTD:
3653    SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3654    break;
3655  }
3656  BB = SL->Run();
3657  delete SL;
3658}
3659
3660HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3661  return new HazardRecognizer();
3662}
3663
3664/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3665/// by tblgen.  Others should not call it.
3666void SelectionDAGISel::
3667SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3668  std::vector<SDOperand> InOps;
3669  std::swap(InOps, Ops);
3670
3671  Ops.push_back(InOps[0]);  // input chain.
3672  Ops.push_back(InOps[1]);  // input asm string.
3673
3674  unsigned i = 2, e = InOps.size();
3675  if (InOps[e-1].getValueType() == MVT::Flag)
3676    --e;  // Don't process a flag operand if it is here.
3677
3678  while (i != e) {
3679    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3680    if ((Flags & 7) != 4 /*MEM*/) {
3681      // Just skip over this operand, copying the operands verbatim.
3682      Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3683      i += (Flags >> 3) + 1;
3684    } else {
3685      assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3686      // Otherwise, this is a memory operand.  Ask the target to select it.
3687      std::vector<SDOperand> SelOps;
3688      if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3689        std::cerr << "Could not match memory address.  Inline asm failure!\n";
3690        exit(1);
3691      }
3692
3693      // Add this to the output node.
3694      Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3695      Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3696      i += 2;
3697    }
3698  }
3699
3700  // Add the flag input back if present.
3701  if (e != InOps.size())
3702    Ops.push_back(InOps.back());
3703}
3704