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