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