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