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