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