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