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