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