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