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