1//===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the X86-specific support for the FastISel class. Much
11// of the target-specific code is generated by tablegen in the file
12// X86GenFastISel.inc, which is #included here.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
17#include "X86ISelLowering.h"
18#include "X86InstrBuilder.h"
19#include "X86RegisterInfo.h"
20#include "X86Subtarget.h"
21#include "X86TargetMachine.h"
22#include "llvm/CodeGen/Analysis.h"
23#include "llvm/CodeGen/FastISel.h"
24#include "llvm/CodeGen/FunctionLoweringInfo.h"
25#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Operator.h"
35#include "llvm/Support/CallSite.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/GetElementPtrTypeIterator.h"
38#include "llvm/Target/TargetOptions.h"
39using namespace llvm;
40
41namespace {
42
43class X86FastISel : public FastISel {
44  /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
45  /// make the right decision when generating code for different targets.
46  const X86Subtarget *Subtarget;
47
48  /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
49  /// floating point ops.
50  /// When SSE is available, use it for f32 operations.
51  /// When SSE2 is available, use it for f64 operations.
52  bool X86ScalarSSEf64;
53  bool X86ScalarSSEf32;
54
55public:
56  explicit X86FastISel(FunctionLoweringInfo &funcInfo,
57                       const TargetLibraryInfo *libInfo)
58    : FastISel(funcInfo, libInfo) {
59    Subtarget = &TM.getSubtarget<X86Subtarget>();
60    X86ScalarSSEf64 = Subtarget->hasSSE2();
61    X86ScalarSSEf32 = Subtarget->hasSSE1();
62  }
63
64  virtual bool TargetSelectInstruction(const Instruction *I);
65
66  /// \brief The specified machine instr operand is a vreg, and that
67  /// vreg is being provided by the specified load instruction.  If possible,
68  /// try to fold the load as an operand to the instruction, returning true if
69  /// possible.
70  virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
71                                   const LoadInst *LI);
72
73  virtual bool FastLowerArguments();
74
75#include "X86GenFastISel.inc"
76
77private:
78  bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
79
80  bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
81
82  bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
83                        bool Aligned = false);
84  bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM,
85                        bool Aligned = false);
86
87  bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
88                         unsigned &ResultReg);
89
90  bool X86SelectAddress(const Value *V, X86AddressMode &AM);
91  bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
92
93  bool X86SelectLoad(const Instruction *I);
94
95  bool X86SelectStore(const Instruction *I);
96
97  bool X86SelectRet(const Instruction *I);
98
99  bool X86SelectCmp(const Instruction *I);
100
101  bool X86SelectZExt(const Instruction *I);
102
103  bool X86SelectBranch(const Instruction *I);
104
105  bool X86SelectShift(const Instruction *I);
106
107  bool X86SelectDivRem(const Instruction *I);
108
109  bool X86SelectSelect(const Instruction *I);
110
111  bool X86SelectTrunc(const Instruction *I);
112
113  bool X86SelectFPExt(const Instruction *I);
114  bool X86SelectFPTrunc(const Instruction *I);
115
116  bool X86VisitIntrinsicCall(const IntrinsicInst &I);
117  bool X86SelectCall(const Instruction *I);
118
119  bool DoSelectCall(const Instruction *I, const char *MemIntName);
120
121  const X86InstrInfo *getInstrInfo() const {
122    return getTargetMachine()->getInstrInfo();
123  }
124  const X86TargetMachine *getTargetMachine() const {
125    return static_cast<const X86TargetMachine *>(&TM);
126  }
127
128  unsigned TargetMaterializeConstant(const Constant *C);
129
130  unsigned TargetMaterializeAlloca(const AllocaInst *C);
131
132  unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
133
134  /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
135  /// computed in an SSE register, not on the X87 floating point stack.
136  bool isScalarFPTypeInSSEReg(EVT VT) const {
137    return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
138      (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
139  }
140
141  bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
142
143  bool IsMemcpySmall(uint64_t Len);
144
145  bool TryEmitSmallMemcpy(X86AddressMode DestAM,
146                          X86AddressMode SrcAM, uint64_t Len);
147};
148
149} // end anonymous namespace.
150
151bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
152  EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
153  if (evt == MVT::Other || !evt.isSimple())
154    // Unhandled type. Halt "fast" selection and bail.
155    return false;
156
157  VT = evt.getSimpleVT();
158  // For now, require SSE/SSE2 for performing floating-point operations,
159  // since x87 requires additional work.
160  if (VT == MVT::f64 && !X86ScalarSSEf64)
161    return false;
162  if (VT == MVT::f32 && !X86ScalarSSEf32)
163    return false;
164  // Similarly, no f80 support yet.
165  if (VT == MVT::f80)
166    return false;
167  // We only handle legal types. For example, on x86-32 the instruction
168  // selector contains all of the 64-bit instructions from x86-64,
169  // under the assumption that i64 won't be used if the target doesn't
170  // support it.
171  return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
172}
173
174#include "X86GenCallingConv.inc"
175
176/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
177/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
178/// Return true and the result register by reference if it is possible.
179bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
180                                  unsigned &ResultReg) {
181  // Get opcode and regclass of the output for the given load instruction.
182  unsigned Opc = 0;
183  const TargetRegisterClass *RC = NULL;
184  switch (VT.getSimpleVT().SimpleTy) {
185  default: return false;
186  case MVT::i1:
187  case MVT::i8:
188    Opc = X86::MOV8rm;
189    RC  = &X86::GR8RegClass;
190    break;
191  case MVT::i16:
192    Opc = X86::MOV16rm;
193    RC  = &X86::GR16RegClass;
194    break;
195  case MVT::i32:
196    Opc = X86::MOV32rm;
197    RC  = &X86::GR32RegClass;
198    break;
199  case MVT::i64:
200    // Must be in x86-64 mode.
201    Opc = X86::MOV64rm;
202    RC  = &X86::GR64RegClass;
203    break;
204  case MVT::f32:
205    if (X86ScalarSSEf32) {
206      Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
207      RC  = &X86::FR32RegClass;
208    } else {
209      Opc = X86::LD_Fp32m;
210      RC  = &X86::RFP32RegClass;
211    }
212    break;
213  case MVT::f64:
214    if (X86ScalarSSEf64) {
215      Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
216      RC  = &X86::FR64RegClass;
217    } else {
218      Opc = X86::LD_Fp64m;
219      RC  = &X86::RFP64RegClass;
220    }
221    break;
222  case MVT::f80:
223    // No f80 support yet.
224    return false;
225  }
226
227  ResultReg = createResultReg(RC);
228  addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
229                         DL, TII.get(Opc), ResultReg), AM);
230  return true;
231}
232
233/// X86FastEmitStore - Emit a machine instruction to store a value Val of
234/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
235/// and a displacement offset, or a GlobalAddress,
236/// i.e. V. Return true if it is possible.
237bool
238X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg,
239                              const X86AddressMode &AM, bool Aligned) {
240  // Get opcode and regclass of the output for the given store instruction.
241  unsigned Opc = 0;
242  switch (VT.getSimpleVT().SimpleTy) {
243  case MVT::f80: // No f80 support yet.
244  default: return false;
245  case MVT::i1: {
246    // Mask out all but lowest bit.
247    unsigned AndResult = createResultReg(&X86::GR8RegClass);
248    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
249            TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1);
250    ValReg = AndResult;
251  }
252  // FALLTHROUGH, handling i1 as i8.
253  case MVT::i8:  Opc = X86::MOV8mr;  break;
254  case MVT::i16: Opc = X86::MOV16mr; break;
255  case MVT::i32: Opc = X86::MOV32mr; break;
256  case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
257  case MVT::f32:
258    Opc = X86ScalarSSEf32 ?
259          (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
260    break;
261  case MVT::f64:
262    Opc = X86ScalarSSEf64 ?
263          (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
264    break;
265  case MVT::v4f32:
266    if (Aligned)
267      Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
268    else
269      Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
270    break;
271  case MVT::v2f64:
272    if (Aligned)
273      Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
274    else
275      Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
276    break;
277  case MVT::v4i32:
278  case MVT::v2i64:
279  case MVT::v8i16:
280  case MVT::v16i8:
281    if (Aligned)
282      Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
283    else
284      Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
285    break;
286  }
287
288  addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
289                         DL, TII.get(Opc)), AM).addReg(ValReg);
290  return true;
291}
292
293bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
294                                   const X86AddressMode &AM, bool Aligned) {
295  // Handle 'null' like i32/i64 0.
296  if (isa<ConstantPointerNull>(Val))
297    Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
298
299  // If this is a store of a simple constant, fold the constant into the store.
300  if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
301    unsigned Opc = 0;
302    bool Signed = true;
303    switch (VT.getSimpleVT().SimpleTy) {
304    default: break;
305    case MVT::i1:  Signed = false;     // FALLTHROUGH to handle as i8.
306    case MVT::i8:  Opc = X86::MOV8mi;  break;
307    case MVT::i16: Opc = X86::MOV16mi; break;
308    case MVT::i32: Opc = X86::MOV32mi; break;
309    case MVT::i64:
310      // Must be a 32-bit sign extended value.
311      if (isInt<32>(CI->getSExtValue()))
312        Opc = X86::MOV64mi32;
313      break;
314    }
315
316    if (Opc) {
317      addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
318                             DL, TII.get(Opc)), AM)
319                             .addImm(Signed ? (uint64_t) CI->getSExtValue() :
320                                              CI->getZExtValue());
321      return true;
322    }
323  }
324
325  unsigned ValReg = getRegForValue(Val);
326  if (ValReg == 0)
327    return false;
328
329  return X86FastEmitStore(VT, ValReg, AM, Aligned);
330}
331
332/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
333/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
334/// ISD::SIGN_EXTEND).
335bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
336                                    unsigned Src, EVT SrcVT,
337                                    unsigned &ResultReg) {
338  unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
339                           Src, /*TODO: Kill=*/false);
340  if (RR == 0)
341    return false;
342
343  ResultReg = RR;
344  return true;
345}
346
347/// X86SelectAddress - Attempt to fill in an address from the given value.
348///
349bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
350  const User *U = NULL;
351  unsigned Opcode = Instruction::UserOp1;
352  if (const Instruction *I = dyn_cast<Instruction>(V)) {
353    // Don't walk into other basic blocks; it's possible we haven't
354    // visited them yet, so the instructions may not yet be assigned
355    // virtual registers.
356    if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
357        FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
358      Opcode = I->getOpcode();
359      U = I;
360    }
361  } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
362    Opcode = C->getOpcode();
363    U = C;
364  }
365
366  if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
367    if (Ty->getAddressSpace() > 255)
368      // Fast instruction selection doesn't support the special
369      // address spaces.
370      return false;
371
372  switch (Opcode) {
373  default: break;
374  case Instruction::BitCast:
375    // Look past bitcasts.
376    return X86SelectAddress(U->getOperand(0), AM);
377
378  case Instruction::IntToPtr:
379    // Look past no-op inttoptrs.
380    if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
381      return X86SelectAddress(U->getOperand(0), AM);
382    break;
383
384  case Instruction::PtrToInt:
385    // Look past no-op ptrtoints.
386    if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
387      return X86SelectAddress(U->getOperand(0), AM);
388    break;
389
390  case Instruction::Alloca: {
391    // Do static allocas.
392    const AllocaInst *A = cast<AllocaInst>(V);
393    DenseMap<const AllocaInst*, int>::iterator SI =
394      FuncInfo.StaticAllocaMap.find(A);
395    if (SI != FuncInfo.StaticAllocaMap.end()) {
396      AM.BaseType = X86AddressMode::FrameIndexBase;
397      AM.Base.FrameIndex = SI->second;
398      return true;
399    }
400    break;
401  }
402
403  case Instruction::Add: {
404    // Adds of constants are common and easy enough.
405    if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
406      uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
407      // They have to fit in the 32-bit signed displacement field though.
408      if (isInt<32>(Disp)) {
409        AM.Disp = (uint32_t)Disp;
410        return X86SelectAddress(U->getOperand(0), AM);
411      }
412    }
413    break;
414  }
415
416  case Instruction::GetElementPtr: {
417    X86AddressMode SavedAM = AM;
418
419    // Pattern-match simple GEPs.
420    uint64_t Disp = (int32_t)AM.Disp;
421    unsigned IndexReg = AM.IndexReg;
422    unsigned Scale = AM.Scale;
423    gep_type_iterator GTI = gep_type_begin(U);
424    // Iterate through the indices, folding what we can. Constants can be
425    // folded, and one dynamic index can be handled, if the scale is supported.
426    for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
427         i != e; ++i, ++GTI) {
428      const Value *Op = *i;
429      if (StructType *STy = dyn_cast<StructType>(*GTI)) {
430        const StructLayout *SL = TD.getStructLayout(STy);
431        Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
432        continue;
433      }
434
435      // A array/variable index is always of the form i*S where S is the
436      // constant scale size.  See if we can push the scale into immediates.
437      uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
438      for (;;) {
439        if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
440          // Constant-offset addressing.
441          Disp += CI->getSExtValue() * S;
442          break;
443        }
444        if (isa<AddOperator>(Op) &&
445            (!isa<Instruction>(Op) ||
446             FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
447               == FuncInfo.MBB) &&
448            isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
449          // An add (in the same block) with a constant operand. Fold the
450          // constant.
451          ConstantInt *CI =
452            cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
453          Disp += CI->getSExtValue() * S;
454          // Iterate on the other operand.
455          Op = cast<AddOperator>(Op)->getOperand(0);
456          continue;
457        }
458        if (IndexReg == 0 &&
459            (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
460            (S == 1 || S == 2 || S == 4 || S == 8)) {
461          // Scaled-index addressing.
462          Scale = S;
463          IndexReg = getRegForGEPIndex(Op).first;
464          if (IndexReg == 0)
465            return false;
466          break;
467        }
468        // Unsupported.
469        goto unsupported_gep;
470      }
471    }
472    // Check for displacement overflow.
473    if (!isInt<32>(Disp))
474      break;
475    // Ok, the GEP indices were covered by constant-offset and scaled-index
476    // addressing. Update the address state and move on to examining the base.
477    AM.IndexReg = IndexReg;
478    AM.Scale = Scale;
479    AM.Disp = (uint32_t)Disp;
480    if (X86SelectAddress(U->getOperand(0), AM))
481      return true;
482
483    // If we couldn't merge the gep value into this addr mode, revert back to
484    // our address and just match the value instead of completely failing.
485    AM = SavedAM;
486    break;
487  unsupported_gep:
488    // Ok, the GEP indices weren't all covered.
489    break;
490  }
491  }
492
493  // Handle constant address.
494  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
495    // Can't handle alternate code models yet.
496    if (TM.getCodeModel() != CodeModel::Small)
497      return false;
498
499    // Can't handle TLS yet.
500    if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
501      if (GVar->isThreadLocal())
502        return false;
503
504    // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
505    // it works...).
506    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
507      if (const GlobalVariable *GVar =
508            dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
509        if (GVar->isThreadLocal())
510          return false;
511
512    // RIP-relative addresses can't have additional register operands, so if
513    // we've already folded stuff into the addressing mode, just force the
514    // global value into its own register, which we can use as the basereg.
515    if (!Subtarget->isPICStyleRIPRel() ||
516        (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
517      // Okay, we've committed to selecting this global. Set up the address.
518      AM.GV = GV;
519
520      // Allow the subtarget to classify the global.
521      unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
522
523      // If this reference is relative to the pic base, set it now.
524      if (isGlobalRelativeToPICBase(GVFlags)) {
525        // FIXME: How do we know Base.Reg is free??
526        AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
527      }
528
529      // Unless the ABI requires an extra load, return a direct reference to
530      // the global.
531      if (!isGlobalStubReference(GVFlags)) {
532        if (Subtarget->isPICStyleRIPRel()) {
533          // Use rip-relative addressing if we can.  Above we verified that the
534          // base and index registers are unused.
535          assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
536          AM.Base.Reg = X86::RIP;
537        }
538        AM.GVOpFlags = GVFlags;
539        return true;
540      }
541
542      // Ok, we need to do a load from a stub.  If we've already loaded from
543      // this stub, reuse the loaded pointer, otherwise emit the load now.
544      DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
545      unsigned LoadReg;
546      if (I != LocalValueMap.end() && I->second != 0) {
547        LoadReg = I->second;
548      } else {
549        // Issue load from stub.
550        unsigned Opc = 0;
551        const TargetRegisterClass *RC = NULL;
552        X86AddressMode StubAM;
553        StubAM.Base.Reg = AM.Base.Reg;
554        StubAM.GV = GV;
555        StubAM.GVOpFlags = GVFlags;
556
557        // Prepare for inserting code in the local-value area.
558        SavePoint SaveInsertPt = enterLocalValueArea();
559
560        if (TLI.getPointerTy() == MVT::i64) {
561          Opc = X86::MOV64rm;
562          RC  = &X86::GR64RegClass;
563
564          if (Subtarget->isPICStyleRIPRel())
565            StubAM.Base.Reg = X86::RIP;
566        } else {
567          Opc = X86::MOV32rm;
568          RC  = &X86::GR32RegClass;
569        }
570
571        LoadReg = createResultReg(RC);
572        MachineInstrBuilder LoadMI =
573          BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
574        addFullAddress(LoadMI, StubAM);
575
576        // Ok, back to normal mode.
577        leaveLocalValueArea(SaveInsertPt);
578
579        // Prevent loading GV stub multiple times in same MBB.
580        LocalValueMap[V] = LoadReg;
581      }
582
583      // Now construct the final address. Note that the Disp, Scale,
584      // and Index values may already be set here.
585      AM.Base.Reg = LoadReg;
586      AM.GV = 0;
587      return true;
588    }
589  }
590
591  // If all else fails, try to materialize the value in a register.
592  if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
593    if (AM.Base.Reg == 0) {
594      AM.Base.Reg = getRegForValue(V);
595      return AM.Base.Reg != 0;
596    }
597    if (AM.IndexReg == 0) {
598      assert(AM.Scale == 1 && "Scale with no index!");
599      AM.IndexReg = getRegForValue(V);
600      return AM.IndexReg != 0;
601    }
602  }
603
604  return false;
605}
606
607/// X86SelectCallAddress - Attempt to fill in an address from the given value.
608///
609bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
610  const User *U = NULL;
611  unsigned Opcode = Instruction::UserOp1;
612  if (const Instruction *I = dyn_cast<Instruction>(V)) {
613    Opcode = I->getOpcode();
614    U = I;
615  } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
616    Opcode = C->getOpcode();
617    U = C;
618  }
619
620  switch (Opcode) {
621  default: break;
622  case Instruction::BitCast:
623    // Look past bitcasts.
624    return X86SelectCallAddress(U->getOperand(0), AM);
625
626  case Instruction::IntToPtr:
627    // Look past no-op inttoptrs.
628    if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
629      return X86SelectCallAddress(U->getOperand(0), AM);
630    break;
631
632  case Instruction::PtrToInt:
633    // Look past no-op ptrtoints.
634    if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
635      return X86SelectCallAddress(U->getOperand(0), AM);
636    break;
637  }
638
639  // Handle constant address.
640  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
641    // Can't handle alternate code models yet.
642    if (TM.getCodeModel() != CodeModel::Small)
643      return false;
644
645    // RIP-relative addresses can't have additional register operands.
646    if (Subtarget->isPICStyleRIPRel() &&
647        (AM.Base.Reg != 0 || AM.IndexReg != 0))
648      return false;
649
650    // Can't handle DLLImport.
651    if (GV->hasDLLImportLinkage())
652      return false;
653
654    // Can't handle TLS.
655    if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
656      if (GVar->isThreadLocal())
657        return false;
658
659    // Okay, we've committed to selecting this global. Set up the basic address.
660    AM.GV = GV;
661
662    // No ABI requires an extra load for anything other than DLLImport, which
663    // we rejected above. Return a direct reference to the global.
664    if (Subtarget->isPICStyleRIPRel()) {
665      // Use rip-relative addressing if we can.  Above we verified that the
666      // base and index registers are unused.
667      assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
668      AM.Base.Reg = X86::RIP;
669    } else if (Subtarget->isPICStyleStubPIC()) {
670      AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
671    } else if (Subtarget->isPICStyleGOT()) {
672      AM.GVOpFlags = X86II::MO_GOTOFF;
673    }
674
675    return true;
676  }
677
678  // If all else fails, try to materialize the value in a register.
679  if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
680    if (AM.Base.Reg == 0) {
681      AM.Base.Reg = getRegForValue(V);
682      return AM.Base.Reg != 0;
683    }
684    if (AM.IndexReg == 0) {
685      assert(AM.Scale == 1 && "Scale with no index!");
686      AM.IndexReg = getRegForValue(V);
687      return AM.IndexReg != 0;
688    }
689  }
690
691  return false;
692}
693
694
695/// X86SelectStore - Select and emit code to implement store instructions.
696bool X86FastISel::X86SelectStore(const Instruction *I) {
697  // Atomic stores need special handling.
698  const StoreInst *S = cast<StoreInst>(I);
699
700  if (S->isAtomic())
701    return false;
702
703  unsigned SABIAlignment =
704    TD.getABITypeAlignment(S->getValueOperand()->getType());
705  bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment;
706
707  MVT VT;
708  if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
709    return false;
710
711  X86AddressMode AM;
712  if (!X86SelectAddress(I->getOperand(1), AM))
713    return false;
714
715  return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned);
716}
717
718/// X86SelectRet - Select and emit code to implement ret instructions.
719bool X86FastISel::X86SelectRet(const Instruction *I) {
720  const ReturnInst *Ret = cast<ReturnInst>(I);
721  const Function &F = *I->getParent()->getParent();
722  const X86MachineFunctionInfo *X86MFInfo =
723      FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
724
725  if (!FuncInfo.CanLowerReturn)
726    return false;
727
728  CallingConv::ID CC = F.getCallingConv();
729  if (CC != CallingConv::C &&
730      CC != CallingConv::Fast &&
731      CC != CallingConv::X86_FastCall &&
732      CC != CallingConv::X86_64_SysV)
733    return false;
734
735  if (Subtarget->isCallingConvWin64(CC))
736    return false;
737
738  // Don't handle popping bytes on return for now.
739  if (X86MFInfo->getBytesToPopOnReturn() != 0)
740    return false;
741
742  // fastcc with -tailcallopt is intended to provide a guaranteed
743  // tail call optimization. Fastisel doesn't know how to do that.
744  if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
745    return false;
746
747  // Let SDISel handle vararg functions.
748  if (F.isVarArg())
749    return false;
750
751  // Build a list of return value registers.
752  SmallVector<unsigned, 4> RetRegs;
753
754  if (Ret->getNumOperands() > 0) {
755    SmallVector<ISD::OutputArg, 4> Outs;
756    GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
757
758    // Analyze operands of the call, assigning locations to each operand.
759    SmallVector<CCValAssign, 16> ValLocs;
760    CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
761                   I->getContext());
762    CCInfo.AnalyzeReturn(Outs, RetCC_X86);
763
764    const Value *RV = Ret->getOperand(0);
765    unsigned Reg = getRegForValue(RV);
766    if (Reg == 0)
767      return false;
768
769    // Only handle a single return value for now.
770    if (ValLocs.size() != 1)
771      return false;
772
773    CCValAssign &VA = ValLocs[0];
774
775    // Don't bother handling odd stuff for now.
776    if (VA.getLocInfo() != CCValAssign::Full)
777      return false;
778    // Only handle register returns for now.
779    if (!VA.isRegLoc())
780      return false;
781
782    // The calling-convention tables for x87 returns don't tell
783    // the whole story.
784    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
785      return false;
786
787    unsigned SrcReg = Reg + VA.getValNo();
788    EVT SrcVT = TLI.getValueType(RV->getType());
789    EVT DstVT = VA.getValVT();
790    // Special handling for extended integers.
791    if (SrcVT != DstVT) {
792      if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
793        return false;
794
795      if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
796        return false;
797
798      assert(DstVT == MVT::i32 && "X86 should always ext to i32");
799
800      if (SrcVT == MVT::i1) {
801        if (Outs[0].Flags.isSExt())
802          return false;
803        SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
804        SrcVT = MVT::i8;
805      }
806      unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
807                                             ISD::SIGN_EXTEND;
808      SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
809                          SrcReg, /*TODO: Kill=*/false);
810    }
811
812    // Make the copy.
813    unsigned DstReg = VA.getLocReg();
814    const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
815    // Avoid a cross-class copy. This is very unlikely.
816    if (!SrcRC->contains(DstReg))
817      return false;
818    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
819            DstReg).addReg(SrcReg);
820
821    // Add register to return instruction.
822    RetRegs.push_back(VA.getLocReg());
823  }
824
825  // The x86-64 ABI for returning structs by value requires that we copy
826  // the sret argument into %rax for the return. We saved the argument into
827  // a virtual register in the entry block, so now we copy the value out
828  // and into %rax. We also do the same with %eax for Win32.
829  if (F.hasStructRetAttr() &&
830      (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
831    unsigned Reg = X86MFInfo->getSRetReturnReg();
832    assert(Reg &&
833           "SRetReturnReg should have been set in LowerFormalArguments()!");
834    unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
835    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
836            RetReg).addReg(Reg);
837    RetRegs.push_back(RetReg);
838  }
839
840  // Now emit the RET.
841  MachineInstrBuilder MIB =
842    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
843  for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
844    MIB.addReg(RetRegs[i], RegState::Implicit);
845  return true;
846}
847
848/// X86SelectLoad - Select and emit code to implement load instructions.
849///
850bool X86FastISel::X86SelectLoad(const Instruction *I)  {
851  // Atomic loads need special handling.
852  if (cast<LoadInst>(I)->isAtomic())
853    return false;
854
855  MVT VT;
856  if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
857    return false;
858
859  X86AddressMode AM;
860  if (!X86SelectAddress(I->getOperand(0), AM))
861    return false;
862
863  unsigned ResultReg = 0;
864  if (X86FastEmitLoad(VT, AM, ResultReg)) {
865    UpdateValueMap(I, ResultReg);
866    return true;
867  }
868  return false;
869}
870
871static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
872  bool HasAVX = Subtarget->hasAVX();
873  bool X86ScalarSSEf32 = Subtarget->hasSSE1();
874  bool X86ScalarSSEf64 = Subtarget->hasSSE2();
875
876  switch (VT.getSimpleVT().SimpleTy) {
877  default:       return 0;
878  case MVT::i8:  return X86::CMP8rr;
879  case MVT::i16: return X86::CMP16rr;
880  case MVT::i32: return X86::CMP32rr;
881  case MVT::i64: return X86::CMP64rr;
882  case MVT::f32:
883    return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
884  case MVT::f64:
885    return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
886  }
887}
888
889/// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
890/// of the comparison, return an opcode that works for the compare (e.g.
891/// CMP32ri) otherwise return 0.
892static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
893  switch (VT.getSimpleVT().SimpleTy) {
894  // Otherwise, we can't fold the immediate into this comparison.
895  default: return 0;
896  case MVT::i8: return X86::CMP8ri;
897  case MVT::i16: return X86::CMP16ri;
898  case MVT::i32: return X86::CMP32ri;
899  case MVT::i64:
900    // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
901    // field.
902    if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
903      return X86::CMP64ri32;
904    return 0;
905  }
906}
907
908bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
909                                     EVT VT) {
910  unsigned Op0Reg = getRegForValue(Op0);
911  if (Op0Reg == 0) return false;
912
913  // Handle 'null' like i32/i64 0.
914  if (isa<ConstantPointerNull>(Op1))
915    Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
916
917  // We have two options: compare with register or immediate.  If the RHS of
918  // the compare is an immediate that we can fold into this compare, use
919  // CMPri, otherwise use CMPrr.
920  if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
921    if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
922      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
923        .addReg(Op0Reg)
924        .addImm(Op1C->getSExtValue());
925      return true;
926    }
927  }
928
929  unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
930  if (CompareOpc == 0) return false;
931
932  unsigned Op1Reg = getRegForValue(Op1);
933  if (Op1Reg == 0) return false;
934  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
935    .addReg(Op0Reg)
936    .addReg(Op1Reg);
937
938  return true;
939}
940
941bool X86FastISel::X86SelectCmp(const Instruction *I) {
942  const CmpInst *CI = cast<CmpInst>(I);
943
944  MVT VT;
945  if (!isTypeLegal(I->getOperand(0)->getType(), VT))
946    return false;
947
948  unsigned ResultReg = createResultReg(&X86::GR8RegClass);
949  unsigned SetCCOpc;
950  bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
951  switch (CI->getPredicate()) {
952  case CmpInst::FCMP_OEQ: {
953    if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
954      return false;
955
956    unsigned EReg = createResultReg(&X86::GR8RegClass);
957    unsigned NPReg = createResultReg(&X86::GR8RegClass);
958    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
959    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
960            TII.get(X86::SETNPr), NPReg);
961    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
962            TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
963    UpdateValueMap(I, ResultReg);
964    return true;
965  }
966  case CmpInst::FCMP_UNE: {
967    if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
968      return false;
969
970    unsigned NEReg = createResultReg(&X86::GR8RegClass);
971    unsigned PReg = createResultReg(&X86::GR8RegClass);
972    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
973    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
974    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
975      .addReg(PReg).addReg(NEReg);
976    UpdateValueMap(I, ResultReg);
977    return true;
978  }
979  case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
980  case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
981  case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
982  case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
983  case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
984  case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
985  case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
986  case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
987  case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
988  case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
989  case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
990  case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
991
992  case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
993  case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
994  case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
995  case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
996  case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
997  case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
998  case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
999  case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
1000  case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
1001  case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
1002  default:
1003    return false;
1004  }
1005
1006  const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1007  if (SwapArgs)
1008    std::swap(Op0, Op1);
1009
1010  // Emit a compare of Op0/Op1.
1011  if (!X86FastEmitCompare(Op0, Op1, VT))
1012    return false;
1013
1014  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
1015  UpdateValueMap(I, ResultReg);
1016  return true;
1017}
1018
1019bool X86FastISel::X86SelectZExt(const Instruction *I) {
1020  EVT DstVT = TLI.getValueType(I->getType());
1021  if (!TLI.isTypeLegal(DstVT))
1022    return false;
1023
1024  unsigned ResultReg = getRegForValue(I->getOperand(0));
1025  if (ResultReg == 0)
1026    return false;
1027
1028  // Handle zero-extension from i1 to i8, which is common.
1029  MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()).getSimpleVT();
1030  if (SrcVT.SimpleTy == MVT::i1) {
1031    // Set the high bits to zero.
1032    ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1033    SrcVT = MVT::i8;
1034
1035    if (ResultReg == 0)
1036      return false;
1037  }
1038
1039  if (DstVT == MVT::i64) {
1040    // Handle extension to 64-bits via sub-register shenanigans.
1041    unsigned MovInst;
1042
1043    switch (SrcVT.SimpleTy) {
1044    case MVT::i8:  MovInst = X86::MOVZX32rr8;  break;
1045    case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1046    case MVT::i32: MovInst = X86::MOV32rr;     break;
1047    default: llvm_unreachable("Unexpected zext to i64 source type");
1048    }
1049
1050    unsigned Result32 = createResultReg(&X86::GR32RegClass);
1051    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32)
1052      .addReg(ResultReg);
1053
1054    ResultReg = createResultReg(&X86::GR64RegClass);
1055    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG),
1056            ResultReg)
1057      .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1058  } else if (DstVT != MVT::i8) {
1059    ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1060                           ResultReg, /*Kill=*/true);
1061    if (ResultReg == 0)
1062      return false;
1063  }
1064
1065  UpdateValueMap(I, ResultReg);
1066  return true;
1067}
1068
1069
1070bool X86FastISel::X86SelectBranch(const Instruction *I) {
1071  // Unconditional branches are selected by tablegen-generated code.
1072  // Handle a conditional branch.
1073  const BranchInst *BI = cast<BranchInst>(I);
1074  MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1075  MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1076
1077  // Fold the common case of a conditional branch with a comparison
1078  // in the same block (values defined on other blocks may not have
1079  // initialized registers).
1080  if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1081    if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1082      EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1083
1084      // Try to take advantage of fallthrough opportunities.
1085      CmpInst::Predicate Predicate = CI->getPredicate();
1086      if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1087        std::swap(TrueMBB, FalseMBB);
1088        Predicate = CmpInst::getInversePredicate(Predicate);
1089      }
1090
1091      bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
1092      unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1093
1094      switch (Predicate) {
1095      case CmpInst::FCMP_OEQ:
1096        std::swap(TrueMBB, FalseMBB);
1097        Predicate = CmpInst::FCMP_UNE;
1098        // FALL THROUGH
1099      case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1100      case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1101      case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1102      case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA_4;  break;
1103      case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE_4; break;
1104      case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1105      case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1106      case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4;  break;
1107      case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4;  break;
1108      case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB_4;  break;
1109      case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE_4; break;
1110      case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1111      case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1112
1113      case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE_4;  break;
1114      case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE_4; break;
1115      case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1116      case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1117      case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1118      case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1119      case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4;  break;
1120      case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1121      case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4;  break;
1122      case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1123      default:
1124        return false;
1125      }
1126
1127      const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1128      if (SwapArgs)
1129        std::swap(Op0, Op1);
1130
1131      // Emit a compare of the LHS and RHS, setting the flags.
1132      if (!X86FastEmitCompare(Op0, Op1, VT))
1133        return false;
1134
1135      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1136        .addMBB(TrueMBB);
1137
1138      if (Predicate == CmpInst::FCMP_UNE) {
1139        // X86 requires a second branch to handle UNE (and OEQ,
1140        // which is mapped to UNE above).
1141        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1142          .addMBB(TrueMBB);
1143      }
1144
1145      FastEmitBranch(FalseMBB, DL);
1146      FuncInfo.MBB->addSuccessor(TrueMBB);
1147      return true;
1148    }
1149  } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1150    // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1151    // typically happen for _Bool and C++ bools.
1152    MVT SourceVT;
1153    if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1154        isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1155      unsigned TestOpc = 0;
1156      switch (SourceVT.SimpleTy) {
1157      default: break;
1158      case MVT::i8:  TestOpc = X86::TEST8ri; break;
1159      case MVT::i16: TestOpc = X86::TEST16ri; break;
1160      case MVT::i32: TestOpc = X86::TEST32ri; break;
1161      case MVT::i64: TestOpc = X86::TEST64ri32; break;
1162      }
1163      if (TestOpc) {
1164        unsigned OpReg = getRegForValue(TI->getOperand(0));
1165        if (OpReg == 0) return false;
1166        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1167          .addReg(OpReg).addImm(1);
1168
1169        unsigned JmpOpc = X86::JNE_4;
1170        if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1171          std::swap(TrueMBB, FalseMBB);
1172          JmpOpc = X86::JE_4;
1173        }
1174
1175        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1176          .addMBB(TrueMBB);
1177        FastEmitBranch(FalseMBB, DL);
1178        FuncInfo.MBB->addSuccessor(TrueMBB);
1179        return true;
1180      }
1181    }
1182  }
1183
1184  // Otherwise do a clumsy setcc and re-test it.
1185  // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1186  // in an explicit cast, so make sure to handle that correctly.
1187  unsigned OpReg = getRegForValue(BI->getCondition());
1188  if (OpReg == 0) return false;
1189
1190  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1191    .addReg(OpReg).addImm(1);
1192  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1193    .addMBB(TrueMBB);
1194  FastEmitBranch(FalseMBB, DL);
1195  FuncInfo.MBB->addSuccessor(TrueMBB);
1196  return true;
1197}
1198
1199bool X86FastISel::X86SelectShift(const Instruction *I) {
1200  unsigned CReg = 0, OpReg = 0;
1201  const TargetRegisterClass *RC = NULL;
1202  if (I->getType()->isIntegerTy(8)) {
1203    CReg = X86::CL;
1204    RC = &X86::GR8RegClass;
1205    switch (I->getOpcode()) {
1206    case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1207    case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1208    case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
1209    default: return false;
1210    }
1211  } else if (I->getType()->isIntegerTy(16)) {
1212    CReg = X86::CX;
1213    RC = &X86::GR16RegClass;
1214    switch (I->getOpcode()) {
1215    case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1216    case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1217    case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
1218    default: return false;
1219    }
1220  } else if (I->getType()->isIntegerTy(32)) {
1221    CReg = X86::ECX;
1222    RC = &X86::GR32RegClass;
1223    switch (I->getOpcode()) {
1224    case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1225    case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1226    case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
1227    default: return false;
1228    }
1229  } else if (I->getType()->isIntegerTy(64)) {
1230    CReg = X86::RCX;
1231    RC = &X86::GR64RegClass;
1232    switch (I->getOpcode()) {
1233    case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1234    case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1235    case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
1236    default: return false;
1237    }
1238  } else {
1239    return false;
1240  }
1241
1242  MVT VT;
1243  if (!isTypeLegal(I->getType(), VT))
1244    return false;
1245
1246  unsigned Op0Reg = getRegForValue(I->getOperand(0));
1247  if (Op0Reg == 0) return false;
1248
1249  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1250  if (Op1Reg == 0) return false;
1251  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1252          CReg).addReg(Op1Reg);
1253
1254  // The shift instruction uses X86::CL. If we defined a super-register
1255  // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1256  if (CReg != X86::CL)
1257    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1258            TII.get(TargetOpcode::KILL), X86::CL)
1259      .addReg(CReg, RegState::Kill);
1260
1261  unsigned ResultReg = createResultReg(RC);
1262  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1263    .addReg(Op0Reg);
1264  UpdateValueMap(I, ResultReg);
1265  return true;
1266}
1267
1268bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1269  const static unsigned NumTypes = 4; // i8, i16, i32, i64
1270  const static unsigned NumOps   = 4; // SDiv, SRem, UDiv, URem
1271  const static bool S = true;  // IsSigned
1272  const static bool U = false; // !IsSigned
1273  const static unsigned Copy = TargetOpcode::COPY;
1274  // For the X86 DIV/IDIV instruction, in most cases the dividend
1275  // (numerator) must be in a specific register pair highreg:lowreg,
1276  // producing the quotient in lowreg and the remainder in highreg.
1277  // For most data types, to set up the instruction, the dividend is
1278  // copied into lowreg, and lowreg is sign-extended or zero-extended
1279  // into highreg.  The exception is i8, where the dividend is defined
1280  // as a single register rather than a register pair, and we
1281  // therefore directly sign-extend or zero-extend the dividend into
1282  // lowreg, instead of copying, and ignore the highreg.
1283  const static struct DivRemEntry {
1284    // The following portion depends only on the data type.
1285    const TargetRegisterClass *RC;
1286    unsigned LowInReg;  // low part of the register pair
1287    unsigned HighInReg; // high part of the register pair
1288    // The following portion depends on both the data type and the operation.
1289    struct DivRemResult {
1290    unsigned OpDivRem;        // The specific DIV/IDIV opcode to use.
1291    unsigned OpSignExtend;    // Opcode for sign-extending lowreg into
1292                              // highreg, or copying a zero into highreg.
1293    unsigned OpCopy;          // Opcode for copying dividend into lowreg, or
1294                              // zero/sign-extending into lowreg for i8.
1295    unsigned DivRemResultReg; // Register containing the desired result.
1296    bool IsOpSigned;          // Whether to use signed or unsigned form.
1297    } ResultTable[NumOps];
1298  } OpTable[NumTypes] = {
1299    { &X86::GR8RegClass,  X86::AX,  0, {
1300        { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AL,  S }, // SDiv
1301        { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AH,  S }, // SRem
1302        { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AL,  U }, // UDiv
1303        { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AH,  U }, // URem
1304      }
1305    }, // i8
1306    { &X86::GR16RegClass, X86::AX,  X86::DX, {
1307        { X86::IDIV16r, X86::CWD,     Copy,            X86::AX,  S }, // SDiv
1308        { X86::IDIV16r, X86::CWD,     Copy,            X86::DX,  S }, // SRem
1309        { X86::DIV16r,  X86::MOV32r0, Copy,            X86::AX,  U }, // UDiv
1310        { X86::DIV16r,  X86::MOV32r0, Copy,            X86::DX,  U }, // URem
1311      }
1312    }, // i16
1313    { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1314        { X86::IDIV32r, X86::CDQ,     Copy,            X86::EAX, S }, // SDiv
1315        { X86::IDIV32r, X86::CDQ,     Copy,            X86::EDX, S }, // SRem
1316        { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EAX, U }, // UDiv
1317        { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EDX, U }, // URem
1318      }
1319    }, // i32
1320    { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1321        { X86::IDIV64r, X86::CQO,     Copy,            X86::RAX, S }, // SDiv
1322        { X86::IDIV64r, X86::CQO,     Copy,            X86::RDX, S }, // SRem
1323        { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RAX, U }, // UDiv
1324        { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RDX, U }, // URem
1325      }
1326    }, // i64
1327  };
1328
1329  MVT VT;
1330  if (!isTypeLegal(I->getType(), VT))
1331    return false;
1332
1333  unsigned TypeIndex, OpIndex;
1334  switch (VT.SimpleTy) {
1335  default: return false;
1336  case MVT::i8:  TypeIndex = 0; break;
1337  case MVT::i16: TypeIndex = 1; break;
1338  case MVT::i32: TypeIndex = 2; break;
1339  case MVT::i64: TypeIndex = 3;
1340    if (!Subtarget->is64Bit())
1341      return false;
1342    break;
1343  }
1344
1345  switch (I->getOpcode()) {
1346  default: llvm_unreachable("Unexpected div/rem opcode");
1347  case Instruction::SDiv: OpIndex = 0; break;
1348  case Instruction::SRem: OpIndex = 1; break;
1349  case Instruction::UDiv: OpIndex = 2; break;
1350  case Instruction::URem: OpIndex = 3; break;
1351  }
1352
1353  const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1354  const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1355  unsigned Op0Reg = getRegForValue(I->getOperand(0));
1356  if (Op0Reg == 0)
1357    return false;
1358  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1359  if (Op1Reg == 0)
1360    return false;
1361
1362  // Move op0 into low-order input register.
1363  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1364          TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1365  // Zero-extend or sign-extend into high-order input register.
1366  if (OpEntry.OpSignExtend) {
1367    if (OpEntry.IsOpSigned)
1368      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1369              TII.get(OpEntry.OpSignExtend));
1370    else {
1371      unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1372      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1373              TII.get(X86::MOV32r0), Zero32);
1374
1375      // Copy the zero into the appropriate sub/super/identical physical
1376      // register. Unfortunately the operations needed are not uniform enough to
1377      // fit neatly into the table above.
1378      if (VT.SimpleTy == MVT::i16) {
1379        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1380                TII.get(Copy), TypeEntry.HighInReg)
1381          .addReg(Zero32, 0, X86::sub_16bit);
1382      } else if (VT.SimpleTy == MVT::i32) {
1383        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1384                TII.get(Copy), TypeEntry.HighInReg)
1385            .addReg(Zero32);
1386      } else if (VT.SimpleTy == MVT::i64) {
1387        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1388                TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1389            .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1390      }
1391    }
1392  }
1393  // Generate the DIV/IDIV instruction.
1394  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1395          TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1396  // For i8 remainder, we can't reference AH directly, as we'll end
1397  // up with bogus copies like %R9B = COPY %AH. Reference AX
1398  // instead to prevent AH references in a REX instruction.
1399  //
1400  // The current assumption of the fast register allocator is that isel
1401  // won't generate explicit references to the GPR8_NOREX registers. If
1402  // the allocator and/or the backend get enhanced to be more robust in
1403  // that regard, this can be, and should be, removed.
1404  unsigned ResultReg = 0;
1405  if ((I->getOpcode() == Instruction::SRem ||
1406       I->getOpcode() == Instruction::URem) &&
1407      OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1408    unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1409    unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1410    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1411            TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1412
1413    // Shift AX right by 8 bits instead of using AH.
1414    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SHR16ri),
1415            ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1416
1417    // Now reference the 8-bit subreg of the result.
1418    ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1419                                           /*Kill=*/true, X86::sub_8bit);
1420  }
1421  // Copy the result out of the physreg if we haven't already.
1422  if (!ResultReg) {
1423    ResultReg = createResultReg(TypeEntry.RC);
1424    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Copy), ResultReg)
1425        .addReg(OpEntry.DivRemResultReg);
1426  }
1427  UpdateValueMap(I, ResultReg);
1428
1429  return true;
1430}
1431
1432bool X86FastISel::X86SelectSelect(const Instruction *I) {
1433  MVT VT;
1434  if (!isTypeLegal(I->getType(), VT))
1435    return false;
1436
1437  // We only use cmov here, if we don't have a cmov instruction bail.
1438  if (!Subtarget->hasCMov()) return false;
1439
1440  unsigned Opc = 0;
1441  const TargetRegisterClass *RC = NULL;
1442  if (VT == MVT::i16) {
1443    Opc = X86::CMOVE16rr;
1444    RC = &X86::GR16RegClass;
1445  } else if (VT == MVT::i32) {
1446    Opc = X86::CMOVE32rr;
1447    RC = &X86::GR32RegClass;
1448  } else if (VT == MVT::i64) {
1449    Opc = X86::CMOVE64rr;
1450    RC = &X86::GR64RegClass;
1451  } else {
1452    return false;
1453  }
1454
1455  unsigned Op0Reg = getRegForValue(I->getOperand(0));
1456  if (Op0Reg == 0) return false;
1457  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1458  if (Op1Reg == 0) return false;
1459  unsigned Op2Reg = getRegForValue(I->getOperand(2));
1460  if (Op2Reg == 0) return false;
1461
1462  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1463    .addReg(Op0Reg).addReg(Op0Reg);
1464  unsigned ResultReg = createResultReg(RC);
1465  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1466    .addReg(Op1Reg).addReg(Op2Reg);
1467  UpdateValueMap(I, ResultReg);
1468  return true;
1469}
1470
1471bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1472  // fpext from float to double.
1473  if (X86ScalarSSEf64 &&
1474      I->getType()->isDoubleTy()) {
1475    const Value *V = I->getOperand(0);
1476    if (V->getType()->isFloatTy()) {
1477      unsigned OpReg = getRegForValue(V);
1478      if (OpReg == 0) return false;
1479      unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1480      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1481              TII.get(X86::CVTSS2SDrr), ResultReg)
1482        .addReg(OpReg);
1483      UpdateValueMap(I, ResultReg);
1484      return true;
1485    }
1486  }
1487
1488  return false;
1489}
1490
1491bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1492  if (X86ScalarSSEf64) {
1493    if (I->getType()->isFloatTy()) {
1494      const Value *V = I->getOperand(0);
1495      if (V->getType()->isDoubleTy()) {
1496        unsigned OpReg = getRegForValue(V);
1497        if (OpReg == 0) return false;
1498        unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1499        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1500                TII.get(X86::CVTSD2SSrr), ResultReg)
1501          .addReg(OpReg);
1502        UpdateValueMap(I, ResultReg);
1503        return true;
1504      }
1505    }
1506  }
1507
1508  return false;
1509}
1510
1511bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1512  EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1513  EVT DstVT = TLI.getValueType(I->getType());
1514
1515  // This code only handles truncation to byte.
1516  if (DstVT != MVT::i8 && DstVT != MVT::i1)
1517    return false;
1518  if (!TLI.isTypeLegal(SrcVT))
1519    return false;
1520
1521  unsigned InputReg = getRegForValue(I->getOperand(0));
1522  if (!InputReg)
1523    // Unhandled operand.  Halt "fast" selection and bail.
1524    return false;
1525
1526  if (SrcVT == MVT::i8) {
1527    // Truncate from i8 to i1; no code needed.
1528    UpdateValueMap(I, InputReg);
1529    return true;
1530  }
1531
1532  if (!Subtarget->is64Bit()) {
1533    // If we're on x86-32; we can't extract an i8 from a general register.
1534    // First issue a copy to GR16_ABCD or GR32_ABCD.
1535    const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1536      (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1537      (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1538    unsigned CopyReg = createResultReg(CopyRC);
1539    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1540            CopyReg).addReg(InputReg);
1541    InputReg = CopyReg;
1542  }
1543
1544  // Issue an extract_subreg.
1545  unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1546                                                  InputReg, /*Kill=*/true,
1547                                                  X86::sub_8bit);
1548  if (!ResultReg)
1549    return false;
1550
1551  UpdateValueMap(I, ResultReg);
1552  return true;
1553}
1554
1555bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1556  return Len <= (Subtarget->is64Bit() ? 32 : 16);
1557}
1558
1559bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1560                                     X86AddressMode SrcAM, uint64_t Len) {
1561
1562  // Make sure we don't bloat code by inlining very large memcpy's.
1563  if (!IsMemcpySmall(Len))
1564    return false;
1565
1566  bool i64Legal = Subtarget->is64Bit();
1567
1568  // We don't care about alignment here since we just emit integer accesses.
1569  while (Len) {
1570    MVT VT;
1571    if (Len >= 8 && i64Legal)
1572      VT = MVT::i64;
1573    else if (Len >= 4)
1574      VT = MVT::i32;
1575    else if (Len >= 2)
1576      VT = MVT::i16;
1577    else {
1578      VT = MVT::i8;
1579    }
1580
1581    unsigned Reg;
1582    bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1583    RV &= X86FastEmitStore(VT, Reg, DestAM);
1584    assert(RV && "Failed to emit load or store??");
1585
1586    unsigned Size = VT.getSizeInBits()/8;
1587    Len -= Size;
1588    DestAM.Disp += Size;
1589    SrcAM.Disp += Size;
1590  }
1591
1592  return true;
1593}
1594
1595bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1596  // FIXME: Handle more intrinsics.
1597  switch (I.getIntrinsicID()) {
1598  default: return false;
1599  case Intrinsic::memcpy: {
1600    const MemCpyInst &MCI = cast<MemCpyInst>(I);
1601    // Don't handle volatile or variable length memcpys.
1602    if (MCI.isVolatile())
1603      return false;
1604
1605    if (isa<ConstantInt>(MCI.getLength())) {
1606      // Small memcpy's are common enough that we want to do them
1607      // without a call if possible.
1608      uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1609      if (IsMemcpySmall(Len)) {
1610        X86AddressMode DestAM, SrcAM;
1611        if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1612            !X86SelectAddress(MCI.getRawSource(), SrcAM))
1613          return false;
1614        TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1615        return true;
1616      }
1617    }
1618
1619    unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1620    if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1621      return false;
1622
1623    if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1624      return false;
1625
1626    return DoSelectCall(&I, "memcpy");
1627  }
1628  case Intrinsic::memset: {
1629    const MemSetInst &MSI = cast<MemSetInst>(I);
1630
1631    if (MSI.isVolatile())
1632      return false;
1633
1634    unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1635    if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1636      return false;
1637
1638    if (MSI.getDestAddressSpace() > 255)
1639      return false;
1640
1641    return DoSelectCall(&I, "memset");
1642  }
1643  case Intrinsic::stackprotector: {
1644    // Emit code to store the stack guard onto the stack.
1645    EVT PtrTy = TLI.getPointerTy();
1646
1647    const Value *Op1 = I.getArgOperand(0); // The guard's value.
1648    const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1649
1650    // Grab the frame index.
1651    X86AddressMode AM;
1652    if (!X86SelectAddress(Slot, AM)) return false;
1653    if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1654    return true;
1655  }
1656  case Intrinsic::dbg_declare: {
1657    const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1658    X86AddressMode AM;
1659    assert(DI->getAddress() && "Null address should be checked earlier!");
1660    if (!X86SelectAddress(DI->getAddress(), AM))
1661      return false;
1662    const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1663    // FIXME may need to add RegState::Debug to any registers produced,
1664    // although ESP/EBP should be the only ones at the moment.
1665    addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1666      addImm(0).addMetadata(DI->getVariable());
1667    return true;
1668  }
1669  case Intrinsic::trap: {
1670    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1671    return true;
1672  }
1673  case Intrinsic::sadd_with_overflow:
1674  case Intrinsic::uadd_with_overflow: {
1675    // FIXME: Should fold immediates.
1676
1677    // Replace "add with overflow" intrinsics with an "add" instruction followed
1678    // by a seto/setc instruction.
1679    const Function *Callee = I.getCalledFunction();
1680    Type *RetTy =
1681      cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1682
1683    MVT VT;
1684    if (!isTypeLegal(RetTy, VT))
1685      return false;
1686
1687    const Value *Op1 = I.getArgOperand(0);
1688    const Value *Op2 = I.getArgOperand(1);
1689    unsigned Reg1 = getRegForValue(Op1);
1690    unsigned Reg2 = getRegForValue(Op2);
1691
1692    if (Reg1 == 0 || Reg2 == 0)
1693      // FIXME: Handle values *not* in registers.
1694      return false;
1695
1696    unsigned OpC = 0;
1697    if (VT == MVT::i32)
1698      OpC = X86::ADD32rr;
1699    else if (VT == MVT::i64)
1700      OpC = X86::ADD64rr;
1701    else
1702      return false;
1703
1704    // The call to CreateRegs builds two sequential registers, to store the
1705    // both the returned values.
1706    unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1707    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1708      .addReg(Reg1).addReg(Reg2);
1709
1710    unsigned Opc = X86::SETBr;
1711    if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1712      Opc = X86::SETOr;
1713    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1714
1715    UpdateValueMap(&I, ResultReg, 2);
1716    return true;
1717  }
1718  }
1719}
1720
1721bool X86FastISel::FastLowerArguments() {
1722  if (!FuncInfo.CanLowerReturn)
1723    return false;
1724
1725  const Function *F = FuncInfo.Fn;
1726  if (F->isVarArg())
1727    return false;
1728
1729  CallingConv::ID CC = F->getCallingConv();
1730  if (CC != CallingConv::C)
1731    return false;
1732
1733  if (Subtarget->isCallingConvWin64(CC))
1734    return false;
1735
1736  if (!Subtarget->is64Bit())
1737    return false;
1738
1739  // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1740  unsigned Idx = 1;
1741  for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1742       I != E; ++I, ++Idx) {
1743    if (Idx > 6)
1744      return false;
1745
1746    if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1747        F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1748        F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1749        F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1750      return false;
1751
1752    Type *ArgTy = I->getType();
1753    if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1754      return false;
1755
1756    EVT ArgVT = TLI.getValueType(ArgTy);
1757    if (!ArgVT.isSimple()) return false;
1758    switch (ArgVT.getSimpleVT().SimpleTy) {
1759    case MVT::i32:
1760    case MVT::i64:
1761      break;
1762    default:
1763      return false;
1764    }
1765  }
1766
1767  static const uint16_t GPR32ArgRegs[] = {
1768    X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1769  };
1770  static const uint16_t GPR64ArgRegs[] = {
1771    X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1772  };
1773
1774  Idx = 0;
1775  const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1776  const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1777  for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1778       I != E; ++I, ++Idx) {
1779    bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1780    const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1781    unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1782    unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1783    // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1784    // Without this, EmitLiveInCopies may eliminate the livein if its only
1785    // use is a bitcast (which isn't turned into an instruction).
1786    unsigned ResultReg = createResultReg(RC);
1787    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1788            ResultReg).addReg(DstReg, getKillRegState(true));
1789    UpdateValueMap(I, ResultReg);
1790  }
1791  return true;
1792}
1793
1794bool X86FastISel::X86SelectCall(const Instruction *I) {
1795  const CallInst *CI = cast<CallInst>(I);
1796  const Value *Callee = CI->getCalledValue();
1797
1798  // Can't handle inline asm yet.
1799  if (isa<InlineAsm>(Callee))
1800    return false;
1801
1802  // Handle intrinsic calls.
1803  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1804    return X86VisitIntrinsicCall(*II);
1805
1806  // Allow SelectionDAG isel to handle tail calls.
1807  if (cast<CallInst>(I)->isTailCall())
1808    return false;
1809
1810  return DoSelectCall(I, 0);
1811}
1812
1813static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1814                                           const ImmutableCallSite &CS) {
1815  if (Subtarget.is64Bit())
1816    return 0;
1817  if (Subtarget.isTargetWindows())
1818    return 0;
1819  CallingConv::ID CC = CS.getCallingConv();
1820  if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1821    return 0;
1822  if (!CS.paramHasAttr(1, Attribute::StructRet))
1823    return 0;
1824  if (CS.paramHasAttr(1, Attribute::InReg))
1825    return 0;
1826  return 4;
1827}
1828
1829// Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1830bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1831  const CallInst *CI = cast<CallInst>(I);
1832  const Value *Callee = CI->getCalledValue();
1833
1834  // Handle only C and fastcc calling conventions for now.
1835  ImmutableCallSite CS(CI);
1836  CallingConv::ID CC = CS.getCallingConv();
1837  bool isWin64 = Subtarget->isCallingConvWin64(CC);
1838  if (CC != CallingConv::C && CC != CallingConv::Fast &&
1839      CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
1840      CC != CallingConv::X86_64_SysV)
1841    return false;
1842
1843  // fastcc with -tailcallopt is intended to provide a guaranteed
1844  // tail call optimization. Fastisel doesn't know how to do that.
1845  if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1846    return false;
1847
1848  PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1849  FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1850  bool isVarArg = FTy->isVarArg();
1851
1852  // Don't know how to handle Win64 varargs yet.  Nothing special needed for
1853  // x86-32.  Special handling for x86-64 is implemented.
1854  if (isVarArg && isWin64)
1855    return false;
1856
1857  // Fast-isel doesn't know about callee-pop yet.
1858  if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1859                       TM.Options.GuaranteedTailCallOpt))
1860    return false;
1861
1862  // Check whether the function can return without sret-demotion.
1863  SmallVector<ISD::OutputArg, 4> Outs;
1864  GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1865  bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1866                                           *FuncInfo.MF, FTy->isVarArg(),
1867                                           Outs, FTy->getContext());
1868  if (!CanLowerReturn)
1869    return false;
1870
1871  // Materialize callee address in a register. FIXME: GV address can be
1872  // handled with a CALLpcrel32 instead.
1873  X86AddressMode CalleeAM;
1874  if (!X86SelectCallAddress(Callee, CalleeAM))
1875    return false;
1876  unsigned CalleeOp = 0;
1877  const GlobalValue *GV = 0;
1878  if (CalleeAM.GV != 0) {
1879    GV = CalleeAM.GV;
1880  } else if (CalleeAM.Base.Reg != 0) {
1881    CalleeOp = CalleeAM.Base.Reg;
1882  } else
1883    return false;
1884
1885  // Deal with call operands first.
1886  SmallVector<const Value *, 8> ArgVals;
1887  SmallVector<unsigned, 8> Args;
1888  SmallVector<MVT, 8> ArgVTs;
1889  SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1890  unsigned arg_size = CS.arg_size();
1891  Args.reserve(arg_size);
1892  ArgVals.reserve(arg_size);
1893  ArgVTs.reserve(arg_size);
1894  ArgFlags.reserve(arg_size);
1895  for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1896       i != e; ++i) {
1897    // If we're lowering a mem intrinsic instead of a regular call, skip the
1898    // last two arguments, which should not passed to the underlying functions.
1899    if (MemIntName && e-i <= 2)
1900      break;
1901    Value *ArgVal = *i;
1902    ISD::ArgFlagsTy Flags;
1903    unsigned AttrInd = i - CS.arg_begin() + 1;
1904    if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1905      Flags.setSExt();
1906    if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1907      Flags.setZExt();
1908
1909    if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1910      PointerType *Ty = cast<PointerType>(ArgVal->getType());
1911      Type *ElementTy = Ty->getElementType();
1912      unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1913      unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1914      if (!FrameAlign)
1915        FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1916      Flags.setByVal();
1917      Flags.setByValSize(FrameSize);
1918      Flags.setByValAlign(FrameAlign);
1919      if (!IsMemcpySmall(FrameSize))
1920        return false;
1921    }
1922
1923    if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1924      Flags.setInReg();
1925    if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1926      Flags.setNest();
1927
1928    // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1929    // instruction.  This is safe because it is common to all fastisel supported
1930    // calling conventions on x86.
1931    if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1932      if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1933          CI->getBitWidth() == 16) {
1934        if (Flags.isSExt())
1935          ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1936        else
1937          ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1938      }
1939    }
1940
1941    unsigned ArgReg;
1942
1943    // Passing bools around ends up doing a trunc to i1 and passing it.
1944    // Codegen this as an argument + "and 1".
1945    if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1946        cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1947        ArgVal->hasOneUse()) {
1948      ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1949      ArgReg = getRegForValue(ArgVal);
1950      if (ArgReg == 0) return false;
1951
1952      MVT ArgVT;
1953      if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1954
1955      ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1956                           ArgVal->hasOneUse(), 1);
1957    } else {
1958      ArgReg = getRegForValue(ArgVal);
1959    }
1960
1961    if (ArgReg == 0) return false;
1962
1963    Type *ArgTy = ArgVal->getType();
1964    MVT ArgVT;
1965    if (!isTypeLegal(ArgTy, ArgVT))
1966      return false;
1967    if (ArgVT == MVT::x86mmx)
1968      return false;
1969    unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1970    Flags.setOrigAlign(OriginalAlignment);
1971
1972    Args.push_back(ArgReg);
1973    ArgVals.push_back(ArgVal);
1974    ArgVTs.push_back(ArgVT);
1975    ArgFlags.push_back(Flags);
1976  }
1977
1978  // Analyze operands of the call, assigning locations to each operand.
1979  SmallVector<CCValAssign, 16> ArgLocs;
1980  CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1981                 I->getParent()->getContext());
1982
1983  // Allocate shadow area for Win64
1984  if (isWin64)
1985    CCInfo.AllocateStack(32, 8);
1986
1987  CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1988
1989  // Get a count of how many bytes are to be pushed on the stack.
1990  unsigned NumBytes = CCInfo.getNextStackOffset();
1991
1992  // Issue CALLSEQ_START
1993  unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1994  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1995    .addImm(NumBytes);
1996
1997  // Process argument: walk the register/memloc assignments, inserting
1998  // copies / loads.
1999  SmallVector<unsigned, 4> RegArgs;
2000  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2001    CCValAssign &VA = ArgLocs[i];
2002    unsigned Arg = Args[VA.getValNo()];
2003    EVT ArgVT = ArgVTs[VA.getValNo()];
2004
2005    // Promote the value if needed.
2006    switch (VA.getLocInfo()) {
2007    case CCValAssign::Full: break;
2008    case CCValAssign::SExt: {
2009      assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2010             "Unexpected extend");
2011      bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2012                                       Arg, ArgVT, Arg);
2013      assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2014      ArgVT = VA.getLocVT();
2015      break;
2016    }
2017    case CCValAssign::ZExt: {
2018      assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2019             "Unexpected extend");
2020      bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2021                                       Arg, ArgVT, Arg);
2022      assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2023      ArgVT = VA.getLocVT();
2024      break;
2025    }
2026    case CCValAssign::AExt: {
2027      assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2028             "Unexpected extend");
2029      bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2030                                       Arg, ArgVT, Arg);
2031      if (!Emitted)
2032        Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2033                                    Arg, ArgVT, Arg);
2034      if (!Emitted)
2035        Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2036                                    Arg, ArgVT, Arg);
2037
2038      assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2039      ArgVT = VA.getLocVT();
2040      break;
2041    }
2042    case CCValAssign::BCvt: {
2043      unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2044                               ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2045      assert(BC != 0 && "Failed to emit a bitcast!");
2046      Arg = BC;
2047      ArgVT = VA.getLocVT();
2048      break;
2049    }
2050    case CCValAssign::VExt:
2051      // VExt has not been implemented, so this should be impossible to reach
2052      // for now.  However, fallback to Selection DAG isel once implemented.
2053      return false;
2054    case CCValAssign::Indirect:
2055      // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2056      // support this.
2057      return false;
2058    }
2059
2060    if (VA.isRegLoc()) {
2061      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2062              VA.getLocReg()).addReg(Arg);
2063      RegArgs.push_back(VA.getLocReg());
2064    } else {
2065      unsigned LocMemOffset = VA.getLocMemOffset();
2066      X86AddressMode AM;
2067      const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2068          getTargetMachine()->getRegisterInfo());
2069      AM.Base.Reg = RegInfo->getStackRegister();
2070      AM.Disp = LocMemOffset;
2071      const Value *ArgVal = ArgVals[VA.getValNo()];
2072      ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2073
2074      if (Flags.isByVal()) {
2075        X86AddressMode SrcAM;
2076        SrcAM.Base.Reg = Arg;
2077        bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2078        assert(Res && "memcpy length already checked!"); (void)Res;
2079      } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2080        // If this is a really simple value, emit this with the Value* version
2081        // of X86FastEmitStore.  If it isn't simple, we don't want to do this,
2082        // as it can cause us to reevaluate the argument.
2083        if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2084          return false;
2085      } else {
2086        if (!X86FastEmitStore(ArgVT, Arg, AM))
2087          return false;
2088      }
2089    }
2090  }
2091
2092  // ELF / PIC requires GOT in the EBX register before function calls via PLT
2093  // GOT pointer.
2094  if (Subtarget->isPICStyleGOT()) {
2095    unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2096    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2097            X86::EBX).addReg(Base);
2098  }
2099
2100  if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2101    // Count the number of XMM registers allocated.
2102    static const uint16_t XMMArgRegs[] = {
2103      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2104      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2105    };
2106    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2107    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2108            X86::AL).addImm(NumXMMRegs);
2109  }
2110
2111  // Issue the call.
2112  MachineInstrBuilder MIB;
2113  if (CalleeOp) {
2114    // Register-indirect call.
2115    unsigned CallOpc;
2116    if (Subtarget->is64Bit())
2117      CallOpc = X86::CALL64r;
2118    else
2119      CallOpc = X86::CALL32r;
2120    MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2121      .addReg(CalleeOp);
2122
2123  } else {
2124    // Direct call.
2125    assert(GV && "Not a direct call");
2126    unsigned CallOpc;
2127    if (Subtarget->is64Bit())
2128      CallOpc = X86::CALL64pcrel32;
2129    else
2130      CallOpc = X86::CALLpcrel32;
2131
2132    // See if we need any target-specific flags on the GV operand.
2133    unsigned char OpFlags = 0;
2134
2135    // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2136    // external symbols most go through the PLT in PIC mode.  If the symbol
2137    // has hidden or protected visibility, or if it is static or local, then
2138    // we don't need to use the PLT - we can directly call it.
2139    if (Subtarget->isTargetELF() &&
2140        TM.getRelocationModel() == Reloc::PIC_ &&
2141        GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2142      OpFlags = X86II::MO_PLT;
2143    } else if (Subtarget->isPICStyleStubAny() &&
2144               (GV->isDeclaration() || GV->isWeakForLinker()) &&
2145               (!Subtarget->getTargetTriple().isMacOSX() ||
2146                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2147      // PC-relative references to external symbols should go through $stub,
2148      // unless we're building with the leopard linker or later, which
2149      // automatically synthesizes these stubs.
2150      OpFlags = X86II::MO_DARWIN_STUB;
2151    }
2152
2153
2154    MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2155    if (MemIntName)
2156      MIB.addExternalSymbol(MemIntName, OpFlags);
2157    else
2158      MIB.addGlobalAddress(GV, 0, OpFlags);
2159  }
2160
2161  // Add a register mask with the call-preserved registers.
2162  // Proper defs for return values will be added by setPhysRegsDeadExcept().
2163  MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2164
2165  // Add an implicit use GOT pointer in EBX.
2166  if (Subtarget->isPICStyleGOT())
2167    MIB.addReg(X86::EBX, RegState::Implicit);
2168
2169  if (Subtarget->is64Bit() && isVarArg && !isWin64)
2170    MIB.addReg(X86::AL, RegState::Implicit);
2171
2172  // Add implicit physical register uses to the call.
2173  for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2174    MIB.addReg(RegArgs[i], RegState::Implicit);
2175
2176  // Issue CALLSEQ_END
2177  unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2178  const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2179  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2180    .addImm(NumBytes).addImm(NumBytesCallee);
2181
2182  // Build info for return calling conv lowering code.
2183  // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2184  SmallVector<ISD::InputArg, 32> Ins;
2185  SmallVector<EVT, 4> RetTys;
2186  ComputeValueVTs(TLI, I->getType(), RetTys);
2187  for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2188    EVT VT = RetTys[i];
2189    MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2190    unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2191    for (unsigned j = 0; j != NumRegs; ++j) {
2192      ISD::InputArg MyFlags;
2193      MyFlags.VT = RegisterVT;
2194      MyFlags.Used = !CS.getInstruction()->use_empty();
2195      if (CS.paramHasAttr(0, Attribute::SExt))
2196        MyFlags.Flags.setSExt();
2197      if (CS.paramHasAttr(0, Attribute::ZExt))
2198        MyFlags.Flags.setZExt();
2199      if (CS.paramHasAttr(0, Attribute::InReg))
2200        MyFlags.Flags.setInReg();
2201      Ins.push_back(MyFlags);
2202    }
2203  }
2204
2205  // Now handle call return values.
2206  SmallVector<unsigned, 4> UsedRegs;
2207  SmallVector<CCValAssign, 16> RVLocs;
2208  CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2209                    I->getParent()->getContext());
2210  unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2211  CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2212  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2213    EVT CopyVT = RVLocs[i].getValVT();
2214    unsigned CopyReg = ResultReg + i;
2215
2216    // If this is a call to a function that returns an fp value on the x87 fp
2217    // stack, but where we prefer to use the value in xmm registers, copy it
2218    // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2219    if ((RVLocs[i].getLocReg() == X86::ST0 ||
2220         RVLocs[i].getLocReg() == X86::ST1)) {
2221      if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2222        CopyVT = MVT::f80;
2223        CopyReg = createResultReg(&X86::RFP80RegClass);
2224      }
2225      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2226              CopyReg);
2227    } else {
2228      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2229              CopyReg).addReg(RVLocs[i].getLocReg());
2230      UsedRegs.push_back(RVLocs[i].getLocReg());
2231    }
2232
2233    if (CopyVT != RVLocs[i].getValVT()) {
2234      // Round the F80 the right size, which also moves to the appropriate xmm
2235      // register. This is accomplished by storing the F80 value in memory and
2236      // then loading it back. Ewww...
2237      EVT ResVT = RVLocs[i].getValVT();
2238      unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2239      unsigned MemSize = ResVT.getSizeInBits()/8;
2240      int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2241      addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2242                                TII.get(Opc)), FI)
2243        .addReg(CopyReg);
2244      Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2245      addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2246                                TII.get(Opc), ResultReg + i), FI);
2247    }
2248  }
2249
2250  if (RVLocs.size())
2251    UpdateValueMap(I, ResultReg, RVLocs.size());
2252
2253  // Set all unused physreg defs as dead.
2254  static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2255
2256  return true;
2257}
2258
2259
2260bool
2261X86FastISel::TargetSelectInstruction(const Instruction *I)  {
2262  switch (I->getOpcode()) {
2263  default: break;
2264  case Instruction::Load:
2265    return X86SelectLoad(I);
2266  case Instruction::Store:
2267    return X86SelectStore(I);
2268  case Instruction::Ret:
2269    return X86SelectRet(I);
2270  case Instruction::ICmp:
2271  case Instruction::FCmp:
2272    return X86SelectCmp(I);
2273  case Instruction::ZExt:
2274    return X86SelectZExt(I);
2275  case Instruction::Br:
2276    return X86SelectBranch(I);
2277  case Instruction::Call:
2278    return X86SelectCall(I);
2279  case Instruction::LShr:
2280  case Instruction::AShr:
2281  case Instruction::Shl:
2282    return X86SelectShift(I);
2283  case Instruction::SDiv:
2284  case Instruction::UDiv:
2285  case Instruction::SRem:
2286  case Instruction::URem:
2287    return X86SelectDivRem(I);
2288  case Instruction::Select:
2289    return X86SelectSelect(I);
2290  case Instruction::Trunc:
2291    return X86SelectTrunc(I);
2292  case Instruction::FPExt:
2293    return X86SelectFPExt(I);
2294  case Instruction::FPTrunc:
2295    return X86SelectFPTrunc(I);
2296  case Instruction::IntToPtr: // Deliberate fall-through.
2297  case Instruction::PtrToInt: {
2298    EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2299    EVT DstVT = TLI.getValueType(I->getType());
2300    if (DstVT.bitsGT(SrcVT))
2301      return X86SelectZExt(I);
2302    if (DstVT.bitsLT(SrcVT))
2303      return X86SelectTrunc(I);
2304    unsigned Reg = getRegForValue(I->getOperand(0));
2305    if (Reg == 0) return false;
2306    UpdateValueMap(I, Reg);
2307    return true;
2308  }
2309  }
2310
2311  return false;
2312}
2313
2314unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2315  MVT VT;
2316  if (!isTypeLegal(C->getType(), VT))
2317    return 0;
2318
2319  // Can't handle alternate code models yet.
2320  if (TM.getCodeModel() != CodeModel::Small)
2321    return 0;
2322
2323  // Get opcode and regclass of the output for the given load instruction.
2324  unsigned Opc = 0;
2325  const TargetRegisterClass *RC = NULL;
2326  switch (VT.SimpleTy) {
2327  default: return 0;
2328  case MVT::i8:
2329    Opc = X86::MOV8rm;
2330    RC  = &X86::GR8RegClass;
2331    break;
2332  case MVT::i16:
2333    Opc = X86::MOV16rm;
2334    RC  = &X86::GR16RegClass;
2335    break;
2336  case MVT::i32:
2337    Opc = X86::MOV32rm;
2338    RC  = &X86::GR32RegClass;
2339    break;
2340  case MVT::i64:
2341    // Must be in x86-64 mode.
2342    Opc = X86::MOV64rm;
2343    RC  = &X86::GR64RegClass;
2344    break;
2345  case MVT::f32:
2346    if (X86ScalarSSEf32) {
2347      Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2348      RC  = &X86::FR32RegClass;
2349    } else {
2350      Opc = X86::LD_Fp32m;
2351      RC  = &X86::RFP32RegClass;
2352    }
2353    break;
2354  case MVT::f64:
2355    if (X86ScalarSSEf64) {
2356      Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2357      RC  = &X86::FR64RegClass;
2358    } else {
2359      Opc = X86::LD_Fp64m;
2360      RC  = &X86::RFP64RegClass;
2361    }
2362    break;
2363  case MVT::f80:
2364    // No f80 support yet.
2365    return 0;
2366  }
2367
2368  // Materialize addresses with LEA instructions.
2369  if (isa<GlobalValue>(C)) {
2370    X86AddressMode AM;
2371    if (X86SelectAddress(C, AM)) {
2372      // If the expression is just a basereg, then we're done, otherwise we need
2373      // to emit an LEA.
2374      if (AM.BaseType == X86AddressMode::RegBase &&
2375          AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2376        return AM.Base.Reg;
2377
2378      Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2379      unsigned ResultReg = createResultReg(RC);
2380      addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2381                             TII.get(Opc), ResultReg), AM);
2382      return ResultReg;
2383    }
2384    return 0;
2385  }
2386
2387  // MachineConstantPool wants an explicit alignment.
2388  unsigned Align = TD.getPrefTypeAlignment(C->getType());
2389  if (Align == 0) {
2390    // Alignment of vector types.  FIXME!
2391    Align = TD.getTypeAllocSize(C->getType());
2392  }
2393
2394  // x86-32 PIC requires a PIC base register for constant pools.
2395  unsigned PICBase = 0;
2396  unsigned char OpFlag = 0;
2397  if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2398    OpFlag = X86II::MO_PIC_BASE_OFFSET;
2399    PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2400  } else if (Subtarget->isPICStyleGOT()) {
2401    OpFlag = X86II::MO_GOTOFF;
2402    PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2403  } else if (Subtarget->isPICStyleRIPRel() &&
2404             TM.getCodeModel() == CodeModel::Small) {
2405    PICBase = X86::RIP;
2406  }
2407
2408  // Create the load from the constant pool.
2409  unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2410  unsigned ResultReg = createResultReg(RC);
2411  addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2412                                   TII.get(Opc), ResultReg),
2413                           MCPOffset, PICBase, OpFlag);
2414
2415  return ResultReg;
2416}
2417
2418unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2419  // Fail on dynamic allocas. At this point, getRegForValue has already
2420  // checked its CSE maps, so if we're here trying to handle a dynamic
2421  // alloca, we're not going to succeed. X86SelectAddress has a
2422  // check for dynamic allocas, because it's called directly from
2423  // various places, but TargetMaterializeAlloca also needs a check
2424  // in order to avoid recursion between getRegForValue,
2425  // X86SelectAddrss, and TargetMaterializeAlloca.
2426  if (!FuncInfo.StaticAllocaMap.count(C))
2427    return 0;
2428
2429  X86AddressMode AM;
2430  if (!X86SelectAddress(C, AM))
2431    return 0;
2432  unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2433  const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2434  unsigned ResultReg = createResultReg(RC);
2435  addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2436                         TII.get(Opc), ResultReg), AM);
2437  return ResultReg;
2438}
2439
2440unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2441  MVT VT;
2442  if (!isTypeLegal(CF->getType(), VT))
2443    return 0;
2444
2445  // Get opcode and regclass for the given zero.
2446  unsigned Opc = 0;
2447  const TargetRegisterClass *RC = NULL;
2448  switch (VT.SimpleTy) {
2449  default: return 0;
2450  case MVT::f32:
2451    if (X86ScalarSSEf32) {
2452      Opc = X86::FsFLD0SS;
2453      RC  = &X86::FR32RegClass;
2454    } else {
2455      Opc = X86::LD_Fp032;
2456      RC  = &X86::RFP32RegClass;
2457    }
2458    break;
2459  case MVT::f64:
2460    if (X86ScalarSSEf64) {
2461      Opc = X86::FsFLD0SD;
2462      RC  = &X86::FR64RegClass;
2463    } else {
2464      Opc = X86::LD_Fp064;
2465      RC  = &X86::RFP64RegClass;
2466    }
2467    break;
2468  case MVT::f80:
2469    // No f80 support yet.
2470    return 0;
2471  }
2472
2473  unsigned ResultReg = createResultReg(RC);
2474  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2475  return ResultReg;
2476}
2477
2478
2479bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2480                                      const LoadInst *LI) {
2481  X86AddressMode AM;
2482  if (!X86SelectAddress(LI->getOperand(0), AM))
2483    return false;
2484
2485  const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2486
2487  unsigned Size = TD.getTypeAllocSize(LI->getType());
2488  unsigned Alignment = LI->getAlignment();
2489
2490  SmallVector<MachineOperand, 8> AddrOps;
2491  AM.getFullAddress(AddrOps);
2492
2493  MachineInstr *Result =
2494    XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2495  if (Result == 0) return false;
2496
2497  FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2498  MI->eraseFromParent();
2499  return true;
2500}
2501
2502
2503namespace llvm {
2504  FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2505                                const TargetLibraryInfo *libInfo) {
2506    return new X86FastISel(funcInfo, libInfo);
2507  }
2508}
2509