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