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