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