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