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