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