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