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