1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86RegisterInfo.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Target/TargetOptions.h"
48 class X86FastISel final : public FastISel {
49 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50 /// make the right decision when generating code for different targets.
51 const X86Subtarget *Subtarget;
53 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54 /// floating point ops.
55 /// When SSE is available, use it for f32 operations.
56 /// When SSE2 is available, use it for f64 operations.
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();
69 bool fastSelectInstruction(const Instruction *I) override;
71 /// \brief The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
82 #include "X86GenFastISel.inc"
85 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
88 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
89 unsigned &ResultReg, unsigned Alignment = 1);
91 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
92 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
95 MachineMemOperand *MMO = nullptr, bool Aligned = false);
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
103 bool X86SelectLoad(const Instruction *I);
105 bool X86SelectStore(const Instruction *I);
107 bool X86SelectRet(const Instruction *I);
109 bool X86SelectCmp(const Instruction *I);
111 bool X86SelectZExt(const Instruction *I);
113 bool X86SelectBranch(const Instruction *I);
115 bool X86SelectShift(const Instruction *I);
117 bool X86SelectDivRem(const Instruction *I);
119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
125 bool X86SelectSelect(const Instruction *I);
127 bool X86SelectTrunc(const Instruction *I);
129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130 const TargetRegisterClass *RC);
132 bool X86SelectFPExt(const Instruction *I);
133 bool X86SelectFPTrunc(const Instruction *I);
134 bool X86SelectSIToFP(const Instruction *I);
136 const X86InstrInfo *getInstrInfo() const {
137 return Subtarget->getInstrInfo();
139 const X86TargetMachine *getTargetMachine() const {
140 return static_cast<const X86TargetMachine *>(&TM);
143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
145 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
146 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
147 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
148 unsigned fastMaterializeConstant(const Constant *C) override;
150 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155 /// computed in an SSE register, not on the X87 floating point stack.
156 bool isScalarFPTypeInSSEReg(EVT VT) const {
157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
163 bool IsMemcpySmall(uint64_t Len);
165 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166 X86AddressMode SrcAM, uint64_t Len);
168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
174 unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
175 const TargetRegisterClass *RC, unsigned Op0,
176 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
177 unsigned Op2, bool Op2IsKill, unsigned Op3,
181 } // end anonymous namespace.
183 static std::pair<X86::CondCode, bool>
184 getX86ConditionCode(CmpInst::Predicate Predicate) {
185 X86::CondCode CC = X86::COND_INVALID;
186 bool NeedSwap = false;
189 // Floating-point Predicates
190 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
191 case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH;
192 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
193 case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH;
194 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
195 case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH;
196 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
197 case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH;
198 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
199 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
200 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
201 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
202 case CmpInst::FCMP_OEQ: LLVM_FALLTHROUGH;
203 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
205 // Integer Predicates
206 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
207 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
208 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
209 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
210 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
211 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
212 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
213 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
214 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
215 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
218 return std::make_pair(CC, NeedSwap);
221 static std::pair<unsigned, bool>
222 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
224 bool NeedSwap = false;
226 // SSE Condition code mapping:
236 default: llvm_unreachable("Unexpected predicate");
237 case CmpInst::FCMP_OEQ: CC = 0; break;
238 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
239 case CmpInst::FCMP_OLT: CC = 1; break;
240 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
241 case CmpInst::FCMP_OLE: CC = 2; break;
242 case CmpInst::FCMP_UNO: CC = 3; break;
243 case CmpInst::FCMP_UNE: CC = 4; break;
244 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
245 case CmpInst::FCMP_UGE: CC = 5; break;
246 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
247 case CmpInst::FCMP_UGT: CC = 6; break;
248 case CmpInst::FCMP_ORD: CC = 7; break;
249 case CmpInst::FCMP_UEQ:
250 case CmpInst::FCMP_ONE: CC = 8; break;
253 return std::make_pair(CC, NeedSwap);
256 /// \brief Adds a complex addressing mode to the given machine instr builder.
257 /// Note, this will constrain the index register. If its not possible to
258 /// constrain the given index register, then a new one will be created. The
259 /// IndexReg field of the addressing mode will be updated to match in this case.
260 const MachineInstrBuilder &
261 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
262 X86AddressMode &AM) {
263 // First constrain the index register. It needs to be a GR64_NOSP.
264 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
265 MIB->getNumOperands() +
267 return ::addFullAddress(MIB, AM);
270 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
271 /// into the user. The condition code will only be updated on success.
272 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
274 if (!isa<ExtractValueInst>(Cond))
277 const auto *EV = cast<ExtractValueInst>(Cond);
278 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
281 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
283 const Function *Callee = II->getCalledFunction();
285 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
286 if (!isTypeLegal(RetTy, RetVT))
289 if (RetVT != MVT::i32 && RetVT != MVT::i64)
293 switch (II->getIntrinsicID()) {
294 default: return false;
295 case Intrinsic::sadd_with_overflow:
296 case Intrinsic::ssub_with_overflow:
297 case Intrinsic::smul_with_overflow:
298 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
299 case Intrinsic::uadd_with_overflow:
300 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
303 // Check if both instructions are in the same basic block.
304 if (II->getParent() != I->getParent())
307 // Make sure nothing is in the way
308 BasicBlock::const_iterator Start(I);
309 BasicBlock::const_iterator End(II);
310 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
311 // We only expect extractvalue instructions between the intrinsic and the
312 // instruction to be selected.
313 if (!isa<ExtractValueInst>(Itr))
316 // Check that the extractvalue operand comes from the intrinsic.
317 const auto *EVI = cast<ExtractValueInst>(Itr);
318 if (EVI->getAggregateOperand() != II)
326 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
327 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
328 if (evt == MVT::Other || !evt.isSimple())
329 // Unhandled type. Halt "fast" selection and bail.
332 VT = evt.getSimpleVT();
333 // For now, require SSE/SSE2 for performing floating-point operations,
334 // since x87 requires additional work.
335 if (VT == MVT::f64 && !X86ScalarSSEf64)
337 if (VT == MVT::f32 && !X86ScalarSSEf32)
339 // Similarly, no f80 support yet.
342 // We only handle legal types. For example, on x86-32 the instruction
343 // selector contains all of the 64-bit instructions from x86-64,
344 // under the assumption that i64 won't be used if the target doesn't
346 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
349 #include "X86GenCallingConv.inc"
351 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
352 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
353 /// Return true and the result register by reference if it is possible.
354 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
355 MachineMemOperand *MMO, unsigned &ResultReg,
356 unsigned Alignment) {
357 bool HasSSE41 = Subtarget->hasSSE41();
358 bool HasAVX = Subtarget->hasAVX();
359 bool HasAVX2 = Subtarget->hasAVX2();
360 bool HasAVX512 = Subtarget->hasAVX512();
361 bool HasVLX = Subtarget->hasVLX();
362 bool IsNonTemporal = MMO && MMO->isNonTemporal();
364 // Get opcode and regclass of the output for the given load instruction.
366 const TargetRegisterClass *RC = nullptr;
367 switch (VT.getSimpleVT().SimpleTy) {
368 default: return false;
370 // TODO: Support this properly.
371 if (Subtarget->hasAVX512())
376 RC = &X86::GR8RegClass;
380 RC = &X86::GR16RegClass;
384 RC = &X86::GR32RegClass;
387 // Must be in x86-64 mode.
389 RC = &X86::GR64RegClass;
392 if (X86ScalarSSEf32) {
393 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
394 RC = &X86::FR32RegClass;
397 RC = &X86::RFP32RegClass;
401 if (X86ScalarSSEf64) {
402 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
403 RC = &X86::FR64RegClass;
406 RC = &X86::RFP64RegClass;
410 // No f80 support yet.
413 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
414 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
415 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
416 else if (Alignment >= 16)
417 Opc = HasVLX ? X86::VMOVAPSZ128rm :
418 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
420 Opc = HasVLX ? X86::VMOVUPSZ128rm :
421 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
422 RC = &X86::VR128RegClass;
425 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
426 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
427 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
428 else if (Alignment >= 16)
429 Opc = HasVLX ? X86::VMOVAPDZ128rm :
430 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
432 Opc = HasVLX ? X86::VMOVUPDZ128rm :
433 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
434 RC = &X86::VR128RegClass;
440 if (IsNonTemporal && Alignment >= 16)
441 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
442 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
443 else if (Alignment >= 16)
444 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
445 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
447 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
448 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
449 RC = &X86::VR128RegClass;
453 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
454 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
455 else if (Alignment >= 32)
456 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
458 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
459 RC = &X86::VR256RegClass;
463 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
464 Opc = X86::VMOVNTDQAYrm;
465 else if (Alignment >= 32)
466 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
468 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
469 RC = &X86::VR256RegClass;
476 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
477 Opc = X86::VMOVNTDQAYrm;
478 else if (Alignment >= 32)
479 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
481 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
482 RC = &X86::VR256RegClass;
486 if (IsNonTemporal && Alignment >= 64)
487 Opc = X86::VMOVNTDQAZrm;
489 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
490 RC = &X86::VR512RegClass;
494 if (IsNonTemporal && Alignment >= 64)
495 Opc = X86::VMOVNTDQAZrm;
497 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
498 RC = &X86::VR512RegClass;
505 // Note: There are a lot more choices based on type with AVX-512, but
506 // there's really no advantage when the load isn't masked.
507 if (IsNonTemporal && Alignment >= 64)
508 Opc = X86::VMOVNTDQAZrm;
510 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
511 RC = &X86::VR512RegClass;
515 ResultReg = createResultReg(RC);
516 MachineInstrBuilder MIB =
517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
518 addFullAddress(MIB, AM);
520 MIB->addMemOperand(*FuncInfo.MF, MMO);
524 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
525 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
526 /// and a displacement offset, or a GlobalAddress,
527 /// i.e. V. Return true if it is possible.
528 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
530 MachineMemOperand *MMO, bool Aligned) {
531 bool HasSSE1 = Subtarget->hasSSE1();
532 bool HasSSE2 = Subtarget->hasSSE2();
533 bool HasSSE4A = Subtarget->hasSSE4A();
534 bool HasAVX = Subtarget->hasAVX();
535 bool HasAVX512 = Subtarget->hasAVX512();
536 bool HasVLX = Subtarget->hasVLX();
537 bool IsNonTemporal = MMO && MMO->isNonTemporal();
539 // Get opcode and regclass of the output for the given store instruction.
541 switch (VT.getSimpleVT().SimpleTy) {
542 case MVT::f80: // No f80 support yet.
543 default: return false;
545 // In case ValReg is a K register, COPY to a GPR
546 if (MRI.getRegClass(ValReg) == &X86::VK1RegClass) {
547 unsigned KValReg = ValReg;
548 ValReg = createResultReg(&X86::GR32RegClass);
549 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
550 TII.get(TargetOpcode::COPY), ValReg)
552 ValReg = fastEmitInst_extractsubreg(MVT::i8, ValReg, /*Kill=*/true,
555 // Mask out all but lowest bit.
556 unsigned AndResult = createResultReg(&X86::GR8RegClass);
557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
558 TII.get(X86::AND8ri), AndResult)
559 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
561 LLVM_FALLTHROUGH; // handle i1 as i8.
563 case MVT::i8: Opc = X86::MOV8mr; break;
564 case MVT::i16: Opc = X86::MOV16mr; break;
566 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
569 // Must be in x86-64 mode.
570 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
573 if (X86ScalarSSEf32) {
574 if (IsNonTemporal && HasSSE4A)
577 Opc = HasAVX512 ? X86::VMOVSSZmr :
578 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
583 if (X86ScalarSSEf32) {
584 if (IsNonTemporal && HasSSE4A)
587 Opc = HasAVX512 ? X86::VMOVSDZmr :
588 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
593 Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
598 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
599 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
601 Opc = HasVLX ? X86::VMOVAPSZ128mr :
602 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
604 Opc = HasVLX ? X86::VMOVUPSZ128mr :
605 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
610 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
611 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
613 Opc = HasVLX ? X86::VMOVAPDZ128mr :
614 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
616 Opc = HasVLX ? X86::VMOVUPDZ128mr :
617 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
625 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
626 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
628 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
629 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
631 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
632 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
638 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
640 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
642 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
648 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
650 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
652 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
661 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
663 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
665 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
670 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
672 Opc = X86::VMOVUPSZmr;
677 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
679 Opc = X86::VMOVUPDZmr;
686 // Note: There are a lot more choices based on type with AVX-512, but
687 // there's really no advantage when the store isn't masked.
689 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
691 Opc = X86::VMOVDQU64Zmr;
695 const MCInstrDesc &Desc = TII.get(Opc);
696 // Some of the instructions in the previous switch use FR128 instead
697 // of FR32 for ValReg. Make sure the register we feed the instruction
698 // matches its register class constraints.
699 // Note: This is fine to do a copy from FR32 to FR128, this is the
700 // same registers behind the scene and actually why it did not trigger
702 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
703 MachineInstrBuilder MIB =
704 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
705 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
707 MIB->addMemOperand(*FuncInfo.MF, MMO);
712 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
714 MachineMemOperand *MMO, bool Aligned) {
715 // Handle 'null' like i32/i64 0.
716 if (isa<ConstantPointerNull>(Val))
717 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
719 // If this is a store of a simple constant, fold the constant into the store.
720 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
723 switch (VT.getSimpleVT().SimpleTy) {
727 LLVM_FALLTHROUGH; // Handle as i8.
728 case MVT::i8: Opc = X86::MOV8mi; break;
729 case MVT::i16: Opc = X86::MOV16mi; break;
730 case MVT::i32: Opc = X86::MOV32mi; break;
732 // Must be a 32-bit sign extended value.
733 if (isInt<32>(CI->getSExtValue()))
734 Opc = X86::MOV64mi32;
739 MachineInstrBuilder MIB =
740 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
741 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
742 : CI->getZExtValue());
744 MIB->addMemOperand(*FuncInfo.MF, MMO);
749 unsigned ValReg = getRegForValue(Val);
753 bool ValKill = hasTrivialKill(Val);
754 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
757 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
758 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
759 /// ISD::SIGN_EXTEND).
760 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
761 unsigned Src, EVT SrcVT,
762 unsigned &ResultReg) {
763 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
764 Src, /*TODO: Kill=*/false);
772 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
773 // Handle constant address.
774 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
775 // Can't handle alternate code models yet.
776 if (TM.getCodeModel() != CodeModel::Small)
779 // Can't handle TLS yet.
780 if (GV->isThreadLocal())
783 // RIP-relative addresses can't have additional register operands, so if
784 // we've already folded stuff into the addressing mode, just force the
785 // global value into its own register, which we can use as the basereg.
786 if (!Subtarget->isPICStyleRIPRel() ||
787 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
788 // Okay, we've committed to selecting this global. Set up the address.
791 // Allow the subtarget to classify the global.
792 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
794 // If this reference is relative to the pic base, set it now.
795 if (isGlobalRelativeToPICBase(GVFlags)) {
796 // FIXME: How do we know Base.Reg is free??
797 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
800 // Unless the ABI requires an extra load, return a direct reference to
802 if (!isGlobalStubReference(GVFlags)) {
803 if (Subtarget->isPICStyleRIPRel()) {
804 // Use rip-relative addressing if we can. Above we verified that the
805 // base and index registers are unused.
806 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
807 AM.Base.Reg = X86::RIP;
809 AM.GVOpFlags = GVFlags;
813 // Ok, we need to do a load from a stub. If we've already loaded from
814 // this stub, reuse the loaded pointer, otherwise emit the load now.
815 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
817 if (I != LocalValueMap.end() && I->second != 0) {
820 // Issue load from stub.
822 const TargetRegisterClass *RC = nullptr;
823 X86AddressMode StubAM;
824 StubAM.Base.Reg = AM.Base.Reg;
826 StubAM.GVOpFlags = GVFlags;
828 // Prepare for inserting code in the local-value area.
829 SavePoint SaveInsertPt = enterLocalValueArea();
831 if (TLI.getPointerTy(DL) == MVT::i64) {
833 RC = &X86::GR64RegClass;
835 if (Subtarget->isPICStyleRIPRel())
836 StubAM.Base.Reg = X86::RIP;
839 RC = &X86::GR32RegClass;
842 LoadReg = createResultReg(RC);
843 MachineInstrBuilder LoadMI =
844 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
845 addFullAddress(LoadMI, StubAM);
847 // Ok, back to normal mode.
848 leaveLocalValueArea(SaveInsertPt);
850 // Prevent loading GV stub multiple times in same MBB.
851 LocalValueMap[V] = LoadReg;
854 // Now construct the final address. Note that the Disp, Scale,
855 // and Index values may already be set here.
856 AM.Base.Reg = LoadReg;
862 // If all else fails, try to materialize the value in a register.
863 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
864 if (AM.Base.Reg == 0) {
865 AM.Base.Reg = getRegForValue(V);
866 return AM.Base.Reg != 0;
868 if (AM.IndexReg == 0) {
869 assert(AM.Scale == 1 && "Scale with no index!");
870 AM.IndexReg = getRegForValue(V);
871 return AM.IndexReg != 0;
878 /// X86SelectAddress - Attempt to fill in an address from the given value.
880 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
881 SmallVector<const Value *, 32> GEPs;
883 const User *U = nullptr;
884 unsigned Opcode = Instruction::UserOp1;
885 if (const Instruction *I = dyn_cast<Instruction>(V)) {
886 // Don't walk into other basic blocks; it's possible we haven't
887 // visited them yet, so the instructions may not yet be assigned
888 // virtual registers.
889 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
890 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
891 Opcode = I->getOpcode();
894 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
895 Opcode = C->getOpcode();
899 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
900 if (Ty->getAddressSpace() > 255)
901 // Fast instruction selection doesn't support the special
907 case Instruction::BitCast:
908 // Look past bitcasts.
909 return X86SelectAddress(U->getOperand(0), AM);
911 case Instruction::IntToPtr:
912 // Look past no-op inttoptrs.
913 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
914 TLI.getPointerTy(DL))
915 return X86SelectAddress(U->getOperand(0), AM);
918 case Instruction::PtrToInt:
919 // Look past no-op ptrtoints.
920 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
921 return X86SelectAddress(U->getOperand(0), AM);
924 case Instruction::Alloca: {
925 // Do static allocas.
926 const AllocaInst *A = cast<AllocaInst>(V);
927 DenseMap<const AllocaInst *, int>::iterator SI =
928 FuncInfo.StaticAllocaMap.find(A);
929 if (SI != FuncInfo.StaticAllocaMap.end()) {
930 AM.BaseType = X86AddressMode::FrameIndexBase;
931 AM.Base.FrameIndex = SI->second;
937 case Instruction::Add: {
938 // Adds of constants are common and easy enough.
939 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
940 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
941 // They have to fit in the 32-bit signed displacement field though.
942 if (isInt<32>(Disp)) {
943 AM.Disp = (uint32_t)Disp;
944 return X86SelectAddress(U->getOperand(0), AM);
950 case Instruction::GetElementPtr: {
951 X86AddressMode SavedAM = AM;
953 // Pattern-match simple GEPs.
954 uint64_t Disp = (int32_t)AM.Disp;
955 unsigned IndexReg = AM.IndexReg;
956 unsigned Scale = AM.Scale;
957 gep_type_iterator GTI = gep_type_begin(U);
958 // Iterate through the indices, folding what we can. Constants can be
959 // folded, and one dynamic index can be handled, if the scale is supported.
960 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
961 i != e; ++i, ++GTI) {
962 const Value *Op = *i;
963 if (StructType *STy = GTI.getStructTypeOrNull()) {
964 const StructLayout *SL = DL.getStructLayout(STy);
965 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
969 // A array/variable index is always of the form i*S where S is the
970 // constant scale size. See if we can push the scale into immediates.
971 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
973 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
974 // Constant-offset addressing.
975 Disp += CI->getSExtValue() * S;
978 if (canFoldAddIntoGEP(U, Op)) {
979 // A compatible add with a constant operand. Fold the constant.
981 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
982 Disp += CI->getSExtValue() * S;
983 // Iterate on the other operand.
984 Op = cast<AddOperator>(Op)->getOperand(0);
988 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
989 (S == 1 || S == 2 || S == 4 || S == 8)) {
990 // Scaled-index addressing.
992 IndexReg = getRegForGEPIndex(Op).first;
998 goto unsupported_gep;
1002 // Check for displacement overflow.
1003 if (!isInt<32>(Disp))
1006 AM.IndexReg = IndexReg;
1008 AM.Disp = (uint32_t)Disp;
1011 if (const GetElementPtrInst *GEP =
1012 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
1013 // Ok, the GEP indices were covered by constant-offset and scaled-index
1014 // addressing. Update the address state and move on to examining the base.
1017 } else if (X86SelectAddress(U->getOperand(0), AM)) {
1021 // If we couldn't merge the gep value into this addr mode, revert back to
1022 // our address and just match the value instead of completely failing.
1025 for (const Value *I : reverse(GEPs))
1026 if (handleConstantAddresses(I, AM))
1031 // Ok, the GEP indices weren't all covered.
1036 return handleConstantAddresses(V, AM);
1039 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
1041 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1042 const User *U = nullptr;
1043 unsigned Opcode = Instruction::UserOp1;
1044 const Instruction *I = dyn_cast<Instruction>(V);
1045 // Record if the value is defined in the same basic block.
1047 // This information is crucial to know whether or not folding an
1048 // operand is valid.
1049 // Indeed, FastISel generates or reuses a virtual register for all
1050 // operands of all instructions it selects. Obviously, the definition and
1051 // its uses must use the same virtual register otherwise the produced
1052 // code is incorrect.
1053 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1054 // registers for values that are alive across basic blocks. This ensures
1055 // that the values are consistently set between across basic block, even
1056 // if different instruction selection mechanisms are used (e.g., a mix of
1057 // SDISel and FastISel).
1058 // For values local to a basic block, the instruction selection process
1059 // generates these virtual registers with whatever method is appropriate
1060 // for its needs. In particular, FastISel and SDISel do not share the way
1061 // local virtual registers are set.
1062 // Therefore, this is impossible (or at least unsafe) to share values
1063 // between basic blocks unless they use the same instruction selection
1064 // method, which is not guarantee for X86.
1065 // Moreover, things like hasOneUse could not be used accurately, if we
1066 // allow to reference values across basic blocks whereas they are not
1067 // alive across basic blocks initially.
1070 Opcode = I->getOpcode();
1072 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1073 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1074 Opcode = C->getOpcode();
1080 case Instruction::BitCast:
1081 // Look past bitcasts if its operand is in the same BB.
1083 return X86SelectCallAddress(U->getOperand(0), AM);
1086 case Instruction::IntToPtr:
1087 // Look past no-op inttoptrs if its operand is in the same BB.
1089 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1090 TLI.getPointerTy(DL))
1091 return X86SelectCallAddress(U->getOperand(0), AM);
1094 case Instruction::PtrToInt:
1095 // Look past no-op ptrtoints if its operand is in the same BB.
1096 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
1097 return X86SelectCallAddress(U->getOperand(0), AM);
1101 // Handle constant address.
1102 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1103 // Can't handle alternate code models yet.
1104 if (TM.getCodeModel() != CodeModel::Small)
1107 // RIP-relative addresses can't have additional register operands.
1108 if (Subtarget->isPICStyleRIPRel() &&
1109 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1112 // Can't handle DLL Import.
1113 if (GV->hasDLLImportStorageClass())
1116 // Can't handle TLS.
1117 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1118 if (GVar->isThreadLocal())
1121 // Okay, we've committed to selecting this global. Set up the basic address.
1124 // No ABI requires an extra load for anything other than DLLImport, which
1125 // we rejected above. Return a direct reference to the global.
1126 if (Subtarget->isPICStyleRIPRel()) {
1127 // Use rip-relative addressing if we can. Above we verified that the
1128 // base and index registers are unused.
1129 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1130 AM.Base.Reg = X86::RIP;
1132 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
1138 // If all else fails, try to materialize the value in a register.
1139 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1140 if (AM.Base.Reg == 0) {
1141 AM.Base.Reg = getRegForValue(V);
1142 return AM.Base.Reg != 0;
1144 if (AM.IndexReg == 0) {
1145 assert(AM.Scale == 1 && "Scale with no index!");
1146 AM.IndexReg = getRegForValue(V);
1147 return AM.IndexReg != 0;
1155 /// X86SelectStore - Select and emit code to implement store instructions.
1156 bool X86FastISel::X86SelectStore(const Instruction *I) {
1157 // Atomic stores need special handling.
1158 const StoreInst *S = cast<StoreInst>(I);
1163 const Value *PtrV = I->getOperand(1);
1164 if (TLI.supportSwiftError()) {
1165 // Swifterror values can come from either a function parameter with
1166 // swifterror attribute or an alloca with swifterror attribute.
1167 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1168 if (Arg->hasSwiftErrorAttr())
1172 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1173 if (Alloca->isSwiftError())
1178 const Value *Val = S->getValueOperand();
1179 const Value *Ptr = S->getPointerOperand();
1182 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1185 unsigned Alignment = S->getAlignment();
1186 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1187 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1188 Alignment = ABIAlignment;
1189 bool Aligned = Alignment >= ABIAlignment;
1192 if (!X86SelectAddress(Ptr, AM))
1195 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1198 /// X86SelectRet - Select and emit code to implement ret instructions.
1199 bool X86FastISel::X86SelectRet(const Instruction *I) {
1200 const ReturnInst *Ret = cast<ReturnInst>(I);
1201 const Function &F = *I->getParent()->getParent();
1202 const X86MachineFunctionInfo *X86MFInfo =
1203 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1205 if (!FuncInfo.CanLowerReturn)
1208 if (TLI.supportSwiftError() &&
1209 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1212 if (TLI.supportSplitCSR(FuncInfo.MF))
1215 CallingConv::ID CC = F.getCallingConv();
1216 if (CC != CallingConv::C &&
1217 CC != CallingConv::Fast &&
1218 CC != CallingConv::X86_FastCall &&
1219 CC != CallingConv::X86_StdCall &&
1220 CC != CallingConv::X86_ThisCall &&
1221 CC != CallingConv::X86_64_SysV &&
1222 CC != CallingConv::X86_64_Win64)
1225 // Don't handle popping bytes if they don't fit the ret's immediate.
1226 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
1229 // fastcc with -tailcallopt is intended to provide a guaranteed
1230 // tail call optimization. Fastisel doesn't know how to do that.
1231 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1234 // Let SDISel handle vararg functions.
1238 // Build a list of return value registers.
1239 SmallVector<unsigned, 4> RetRegs;
1241 if (Ret->getNumOperands() > 0) {
1242 SmallVector<ISD::OutputArg, 4> Outs;
1243 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1245 // Analyze operands of the call, assigning locations to each operand.
1246 SmallVector<CCValAssign, 16> ValLocs;
1247 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1248 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1250 const Value *RV = Ret->getOperand(0);
1251 unsigned Reg = getRegForValue(RV);
1255 // Only handle a single return value for now.
1256 if (ValLocs.size() != 1)
1259 CCValAssign &VA = ValLocs[0];
1261 // Don't bother handling odd stuff for now.
1262 if (VA.getLocInfo() != CCValAssign::Full)
1264 // Only handle register returns for now.
1268 // The calling-convention tables for x87 returns don't tell
1270 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1273 unsigned SrcReg = Reg + VA.getValNo();
1274 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1275 EVT DstVT = VA.getValVT();
1276 // Special handling for extended integers.
1277 if (SrcVT != DstVT) {
1278 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1281 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1284 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1286 if (SrcVT == MVT::i1) {
1287 if (Outs[0].Flags.isSExt())
1289 // In case SrcReg is a K register, COPY to a GPR
1290 if (MRI.getRegClass(SrcReg) == &X86::VK1RegClass) {
1291 unsigned KSrcReg = SrcReg;
1292 SrcReg = createResultReg(&X86::GR32RegClass);
1293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1294 TII.get(TargetOpcode::COPY), SrcReg)
1296 SrcReg = fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
1299 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1302 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1304 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1305 SrcReg, /*TODO: Kill=*/false);
1309 unsigned DstReg = VA.getLocReg();
1310 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1311 // Avoid a cross-class copy. This is very unlikely.
1312 if (!SrcRC->contains(DstReg))
1314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1315 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1317 // Add register to return instruction.
1318 RetRegs.push_back(VA.getLocReg());
1321 // Swift calling convention does not require we copy the sret argument
1322 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1324 // All x86 ABIs require that for returning structs by value we copy
1325 // the sret argument into %rax/%eax (depending on ABI) for the return.
1326 // We saved the argument into a virtual register in the entry block,
1327 // so now we copy the value out and into %rax/%eax.
1328 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
1329 unsigned Reg = X86MFInfo->getSRetReturnReg();
1331 "SRetReturnReg should have been set in LowerFormalArguments()!");
1332 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1334 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1335 RetRegs.push_back(RetReg);
1338 // Now emit the RET.
1339 MachineInstrBuilder MIB;
1340 if (X86MFInfo->getBytesToPopOnReturn()) {
1341 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1342 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1343 .addImm(X86MFInfo->getBytesToPopOnReturn());
1345 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1346 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1348 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1349 MIB.addReg(RetRegs[i], RegState::Implicit);
1353 /// X86SelectLoad - Select and emit code to implement load instructions.
1355 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1356 const LoadInst *LI = cast<LoadInst>(I);
1358 // Atomic loads need special handling.
1362 const Value *SV = I->getOperand(0);
1363 if (TLI.supportSwiftError()) {
1364 // Swifterror values can come from either a function parameter with
1365 // swifterror attribute or an alloca with swifterror attribute.
1366 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1367 if (Arg->hasSwiftErrorAttr())
1371 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1372 if (Alloca->isSwiftError())
1378 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1381 const Value *Ptr = LI->getPointerOperand();
1384 if (!X86SelectAddress(Ptr, AM))
1387 unsigned Alignment = LI->getAlignment();
1388 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1389 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1390 Alignment = ABIAlignment;
1392 unsigned ResultReg = 0;
1393 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1397 updateValueMap(I, ResultReg);
1401 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1402 bool HasAVX = Subtarget->hasAVX();
1403 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1404 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1406 switch (VT.getSimpleVT().SimpleTy) {
1408 case MVT::i8: return X86::CMP8rr;
1409 case MVT::i16: return X86::CMP16rr;
1410 case MVT::i32: return X86::CMP32rr;
1411 case MVT::i64: return X86::CMP64rr;
1413 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1415 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1419 /// If we have a comparison with RHS as the RHS of the comparison, return an
1420 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1421 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1422 int64_t Val = RHSC->getSExtValue();
1423 switch (VT.getSimpleVT().SimpleTy) {
1424 // Otherwise, we can't fold the immediate into this comparison.
1431 return X86::CMP16ri8;
1432 return X86::CMP16ri;
1435 return X86::CMP32ri8;
1436 return X86::CMP32ri;
1439 return X86::CMP64ri8;
1440 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1443 return X86::CMP64ri32;
1448 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1449 const DebugLoc &CurDbgLoc) {
1450 unsigned Op0Reg = getRegForValue(Op0);
1451 if (Op0Reg == 0) return false;
1453 // Handle 'null' like i32/i64 0.
1454 if (isa<ConstantPointerNull>(Op1))
1455 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1457 // We have two options: compare with register or immediate. If the RHS of
1458 // the compare is an immediate that we can fold into this compare, use
1459 // CMPri, otherwise use CMPrr.
1460 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1461 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1464 .addImm(Op1C->getSExtValue());
1469 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1470 if (CompareOpc == 0) return false;
1472 unsigned Op1Reg = getRegForValue(Op1);
1473 if (Op1Reg == 0) return false;
1474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1481 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1482 const CmpInst *CI = cast<CmpInst>(I);
1485 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1488 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1491 // Try to optimize or fold the cmp.
1492 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1493 unsigned ResultReg = 0;
1494 switch (Predicate) {
1496 case CmpInst::FCMP_FALSE: {
1497 ResultReg = createResultReg(&X86::GR32RegClass);
1498 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1500 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1506 case CmpInst::FCMP_TRUE: {
1507 ResultReg = createResultReg(&X86::GR8RegClass);
1508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1509 ResultReg).addImm(1);
1515 updateValueMap(I, ResultReg);
1519 const Value *LHS = CI->getOperand(0);
1520 const Value *RHS = CI->getOperand(1);
1522 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1523 // We don't have to materialize a zero constant for this case and can just use
1524 // %x again on the RHS.
1525 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1526 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1527 if (RHSC && RHSC->isNullValue())
1531 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1532 static const uint16_t SETFOpcTable[2][3] = {
1533 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1534 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1536 const uint16_t *SETFOpc = nullptr;
1537 switch (Predicate) {
1539 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1540 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1543 ResultReg = createResultReg(&X86::GR8RegClass);
1545 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1548 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1549 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1550 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1554 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1555 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1556 updateValueMap(I, ResultReg);
1562 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1563 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1564 unsigned Opc = X86::getSETFromCond(CC);
1567 std::swap(LHS, RHS);
1569 // Emit a compare of LHS/RHS.
1570 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1573 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1574 updateValueMap(I, ResultReg);
1578 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1579 EVT DstVT = TLI.getValueType(DL, I->getType());
1580 if (!TLI.isTypeLegal(DstVT))
1583 unsigned ResultReg = getRegForValue(I->getOperand(0));
1587 // Handle zero-extension from i1 to i8, which is common.
1588 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1589 if (SrcVT == MVT::i1) {
1590 // In case ResultReg is a K register, COPY to a GPR
1591 if (MRI.getRegClass(ResultReg) == &X86::VK1RegClass) {
1592 unsigned KResultReg = ResultReg;
1593 ResultReg = createResultReg(&X86::GR32RegClass);
1594 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1595 TII.get(TargetOpcode::COPY), ResultReg)
1596 .addReg(KResultReg);
1597 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1601 // Set the high bits to zero.
1602 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1609 if (DstVT == MVT::i64) {
1610 // Handle extension to 64-bits via sub-register shenanigans.
1613 switch (SrcVT.SimpleTy) {
1614 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1615 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1616 case MVT::i32: MovInst = X86::MOV32rr; break;
1617 default: llvm_unreachable("Unexpected zext to i64 source type");
1620 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1621 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1624 ResultReg = createResultReg(&X86::GR64RegClass);
1625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1627 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1628 } else if (DstVT != MVT::i8) {
1629 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1630 ResultReg, /*Kill=*/true);
1635 updateValueMap(I, ResultReg);
1639 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1640 // Unconditional branches are selected by tablegen-generated code.
1641 // Handle a conditional branch.
1642 const BranchInst *BI = cast<BranchInst>(I);
1643 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1644 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1646 // Fold the common case of a conditional branch with a comparison
1647 // in the same block (values defined on other blocks may not have
1648 // initialized registers).
1650 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1651 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1652 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1654 // Try to optimize or fold the cmp.
1655 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1656 switch (Predicate) {
1658 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1659 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1662 const Value *CmpLHS = CI->getOperand(0);
1663 const Value *CmpRHS = CI->getOperand(1);
1665 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1667 // We don't have to materialize a zero constant for this case and can just
1668 // use %x again on the RHS.
1669 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1670 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1671 if (CmpRHSC && CmpRHSC->isNullValue())
1675 // Try to take advantage of fallthrough opportunities.
1676 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1677 std::swap(TrueMBB, FalseMBB);
1678 Predicate = CmpInst::getInversePredicate(Predicate);
1681 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1682 // code check. Instead two branch instructions are required to check all
1683 // the flags. First we change the predicate to a supported condition code,
1684 // which will be the first branch. Later one we will emit the second
1686 bool NeedExtraBranch = false;
1687 switch (Predicate) {
1689 case CmpInst::FCMP_OEQ:
1690 std::swap(TrueMBB, FalseMBB);
1692 case CmpInst::FCMP_UNE:
1693 NeedExtraBranch = true;
1694 Predicate = CmpInst::FCMP_ONE;
1700 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1701 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1703 BranchOpc = X86::GetCondBranchFromCond(CC);
1705 std::swap(CmpLHS, CmpRHS);
1707 // Emit a compare of the LHS and RHS, setting the flags.
1708 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1714 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1716 if (NeedExtraBranch) {
1717 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1721 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1724 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1725 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1726 // typically happen for _Bool and C++ bools.
1728 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1729 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1730 unsigned TestOpc = 0;
1731 switch (SourceVT.SimpleTy) {
1733 case MVT::i8: TestOpc = X86::TEST8ri; break;
1734 case MVT::i16: TestOpc = X86::TEST16ri; break;
1735 case MVT::i32: TestOpc = X86::TEST32ri; break;
1736 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1739 unsigned OpReg = getRegForValue(TI->getOperand(0));
1740 if (OpReg == 0) return false;
1742 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1743 .addReg(OpReg).addImm(1);
1745 unsigned JmpOpc = X86::JNE_1;
1746 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1747 std::swap(TrueMBB, FalseMBB);
1751 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1754 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1758 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1759 // Fake request the condition, otherwise the intrinsic might be completely
1761 unsigned TmpReg = getRegForValue(BI->getCondition());
1765 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1767 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1769 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1773 // Otherwise do a clumsy setcc and re-test it.
1774 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1775 // in an explicit cast, so make sure to handle that correctly.
1776 unsigned OpReg = getRegForValue(BI->getCondition());
1777 if (OpReg == 0) return false;
1779 // In case OpReg is a K register, COPY to a GPR
1780 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1781 unsigned KOpReg = OpReg;
1782 OpReg = createResultReg(&X86::GR32RegClass);
1783 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1784 TII.get(TargetOpcode::COPY), OpReg)
1786 OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, /*Kill=*/true,
1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1794 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1798 bool X86FastISel::X86SelectShift(const Instruction *I) {
1799 unsigned CReg = 0, OpReg = 0;
1800 const TargetRegisterClass *RC = nullptr;
1801 if (I->getType()->isIntegerTy(8)) {
1803 RC = &X86::GR8RegClass;
1804 switch (I->getOpcode()) {
1805 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1806 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1807 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1808 default: return false;
1810 } else if (I->getType()->isIntegerTy(16)) {
1812 RC = &X86::GR16RegClass;
1813 switch (I->getOpcode()) {
1814 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1815 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1816 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1817 default: return false;
1819 } else if (I->getType()->isIntegerTy(32)) {
1821 RC = &X86::GR32RegClass;
1822 switch (I->getOpcode()) {
1823 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1824 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1825 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1826 default: return false;
1828 } else if (I->getType()->isIntegerTy(64)) {
1830 RC = &X86::GR64RegClass;
1831 switch (I->getOpcode()) {
1832 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1833 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1834 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1835 default: return false;
1842 if (!isTypeLegal(I->getType(), VT))
1845 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1846 if (Op0Reg == 0) return false;
1848 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1849 if (Op1Reg == 0) return false;
1850 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1851 CReg).addReg(Op1Reg);
1853 // The shift instruction uses X86::CL. If we defined a super-register
1854 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1855 if (CReg != X86::CL)
1856 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1857 TII.get(TargetOpcode::KILL), X86::CL)
1858 .addReg(CReg, RegState::Kill);
1860 unsigned ResultReg = createResultReg(RC);
1861 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1863 updateValueMap(I, ResultReg);
1867 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1868 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1869 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1870 const static bool S = true; // IsSigned
1871 const static bool U = false; // !IsSigned
1872 const static unsigned Copy = TargetOpcode::COPY;
1873 // For the X86 DIV/IDIV instruction, in most cases the dividend
1874 // (numerator) must be in a specific register pair highreg:lowreg,
1875 // producing the quotient in lowreg and the remainder in highreg.
1876 // For most data types, to set up the instruction, the dividend is
1877 // copied into lowreg, and lowreg is sign-extended or zero-extended
1878 // into highreg. The exception is i8, where the dividend is defined
1879 // as a single register rather than a register pair, and we
1880 // therefore directly sign-extend or zero-extend the dividend into
1881 // lowreg, instead of copying, and ignore the highreg.
1882 const static struct DivRemEntry {
1883 // The following portion depends only on the data type.
1884 const TargetRegisterClass *RC;
1885 unsigned LowInReg; // low part of the register pair
1886 unsigned HighInReg; // high part of the register pair
1887 // The following portion depends on both the data type and the operation.
1888 struct DivRemResult {
1889 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1890 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1891 // highreg, or copying a zero into highreg.
1892 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1893 // zero/sign-extending into lowreg for i8.
1894 unsigned DivRemResultReg; // Register containing the desired result.
1895 bool IsOpSigned; // Whether to use signed or unsigned form.
1896 } ResultTable[NumOps];
1897 } OpTable[NumTypes] = {
1898 { &X86::GR8RegClass, X86::AX, 0, {
1899 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1900 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1901 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1902 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1905 { &X86::GR16RegClass, X86::AX, X86::DX, {
1906 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1907 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1908 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1909 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1912 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1913 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1914 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1915 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1916 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1919 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1920 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1921 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1922 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1923 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1929 if (!isTypeLegal(I->getType(), VT))
1932 unsigned TypeIndex, OpIndex;
1933 switch (VT.SimpleTy) {
1934 default: return false;
1935 case MVT::i8: TypeIndex = 0; break;
1936 case MVT::i16: TypeIndex = 1; break;
1937 case MVT::i32: TypeIndex = 2; break;
1938 case MVT::i64: TypeIndex = 3;
1939 if (!Subtarget->is64Bit())
1944 switch (I->getOpcode()) {
1945 default: llvm_unreachable("Unexpected div/rem opcode");
1946 case Instruction::SDiv: OpIndex = 0; break;
1947 case Instruction::SRem: OpIndex = 1; break;
1948 case Instruction::UDiv: OpIndex = 2; break;
1949 case Instruction::URem: OpIndex = 3; break;
1952 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1953 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1954 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1957 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1961 // Move op0 into low-order input register.
1962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1963 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1964 // Zero-extend or sign-extend into high-order input register.
1965 if (OpEntry.OpSignExtend) {
1966 if (OpEntry.IsOpSigned)
1967 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1968 TII.get(OpEntry.OpSignExtend));
1970 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1972 TII.get(X86::MOV32r0), Zero32);
1974 // Copy the zero into the appropriate sub/super/identical physical
1975 // register. Unfortunately the operations needed are not uniform enough
1976 // to fit neatly into the table above.
1977 if (VT == MVT::i16) {
1978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1979 TII.get(Copy), TypeEntry.HighInReg)
1980 .addReg(Zero32, 0, X86::sub_16bit);
1981 } else if (VT == MVT::i32) {
1982 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1983 TII.get(Copy), TypeEntry.HighInReg)
1985 } else if (VT == MVT::i64) {
1986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1987 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1988 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1992 // Generate the DIV/IDIV instruction.
1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1994 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1995 // For i8 remainder, we can't reference AH directly, as we'll end
1996 // up with bogus copies like %R9B = COPY %AH. Reference AX
1997 // instead to prevent AH references in a REX instruction.
1999 // The current assumption of the fast register allocator is that isel
2000 // won't generate explicit references to the GPR8_NOREX registers. If
2001 // the allocator and/or the backend get enhanced to be more robust in
2002 // that regard, this can be, and should be, removed.
2003 unsigned ResultReg = 0;
2004 if ((I->getOpcode() == Instruction::SRem ||
2005 I->getOpcode() == Instruction::URem) &&
2006 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
2007 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
2008 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
2009 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2010 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
2012 // Shift AX right by 8 bits instead of using AH.
2013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
2014 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
2016 // Now reference the 8-bit subreg of the result.
2017 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
2018 /*Kill=*/true, X86::sub_8bit);
2020 // Copy the result out of the physreg if we haven't already.
2022 ResultReg = createResultReg(TypeEntry.RC);
2023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
2024 .addReg(OpEntry.DivRemResultReg);
2026 updateValueMap(I, ResultReg);
2031 /// \brief Emit a conditional move instruction (if the are supported) to lower
2033 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2034 // Check if the subtarget supports these instructions.
2035 if (!Subtarget->hasCMov())
2038 // FIXME: Add support for i8.
2039 if (RetVT < MVT::i16 || RetVT > MVT::i64)
2042 const Value *Cond = I->getOperand(0);
2043 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2044 bool NeedTest = true;
2045 X86::CondCode CC = X86::COND_NE;
2047 // Optimize conditions coming from a compare if both instructions are in the
2048 // same basic block (values defined in other basic blocks may not have
2049 // initialized registers).
2050 const auto *CI = dyn_cast<CmpInst>(Cond);
2051 if (CI && (CI->getParent() == I->getParent())) {
2052 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2054 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
2055 static const uint16_t SETFOpcTable[2][3] = {
2056 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2057 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2059 const uint16_t *SETFOpc = nullptr;
2060 switch (Predicate) {
2062 case CmpInst::FCMP_OEQ:
2063 SETFOpc = &SETFOpcTable[0][0];
2064 Predicate = CmpInst::ICMP_NE;
2066 case CmpInst::FCMP_UNE:
2067 SETFOpc = &SETFOpcTable[1][0];
2068 Predicate = CmpInst::ICMP_NE;
2073 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
2074 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2076 const Value *CmpLHS = CI->getOperand(0);
2077 const Value *CmpRHS = CI->getOperand(1);
2079 std::swap(CmpLHS, CmpRHS);
2081 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2082 // Emit a compare of the LHS and RHS, setting the flags.
2083 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2087 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2088 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2093 auto const &II = TII.get(SETFOpc[2]);
2094 if (II.getNumDefs()) {
2095 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2097 .addReg(FlagReg2).addReg(FlagReg1);
2099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2100 .addReg(FlagReg2).addReg(FlagReg1);
2104 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2105 // Fake request the condition, otherwise the intrinsic might be completely
2107 unsigned TmpReg = getRegForValue(Cond);
2115 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2116 // garbage. Indeed, only the less significant bit is supposed to be
2117 // accurate. If we read more than the lsb, we may see non-zero values
2118 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2119 // the select. This is achieved by performing TEST against 1.
2120 unsigned CondReg = getRegForValue(Cond);
2123 bool CondIsKill = hasTrivialKill(Cond);
2125 // In case OpReg is a K register, COPY to a GPR
2126 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2127 unsigned KCondReg = CondReg;
2128 CondReg = createResultReg(&X86::GR32RegClass);
2129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2130 TII.get(TargetOpcode::COPY), CondReg)
2131 .addReg(KCondReg, getKillRegState(CondIsKill));
2132 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2135 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2136 .addReg(CondReg, getKillRegState(CondIsKill))
2140 const Value *LHS = I->getOperand(1);
2141 const Value *RHS = I->getOperand(2);
2143 unsigned RHSReg = getRegForValue(RHS);
2144 bool RHSIsKill = hasTrivialKill(RHS);
2146 unsigned LHSReg = getRegForValue(LHS);
2147 bool LHSIsKill = hasTrivialKill(LHS);
2149 if (!LHSReg || !RHSReg)
2152 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2153 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2155 updateValueMap(I, ResultReg);
2159 /// \brief Emit SSE or AVX instructions to lower the select.
2161 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2162 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
2163 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
2164 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2165 // Optimize conditions coming from a compare if both instructions are in the
2166 // same basic block (values defined in other basic blocks may not have
2167 // initialized registers).
2168 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2169 if (!CI || (CI->getParent() != I->getParent()))
2172 if (I->getType() != CI->getOperand(0)->getType() ||
2173 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2174 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2177 const Value *CmpLHS = CI->getOperand(0);
2178 const Value *CmpRHS = CI->getOperand(1);
2179 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2181 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2182 // We don't have to materialize a zero constant for this case and can just use
2183 // %x again on the RHS.
2184 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2185 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2186 if (CmpRHSC && CmpRHSC->isNullValue())
2192 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2197 std::swap(CmpLHS, CmpRHS);
2199 // Choose the SSE instruction sequence based on data type (float or double).
2200 static const uint16_t OpcTable[2][4] = {
2201 { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2202 { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
2205 const uint16_t *Opc = nullptr;
2206 switch (RetVT.SimpleTy) {
2207 default: return false;
2208 case MVT::f32: Opc = &OpcTable[0][0]; break;
2209 case MVT::f64: Opc = &OpcTable[1][0]; break;
2212 const Value *LHS = I->getOperand(1);
2213 const Value *RHS = I->getOperand(2);
2215 unsigned LHSReg = getRegForValue(LHS);
2216 bool LHSIsKill = hasTrivialKill(LHS);
2218 unsigned RHSReg = getRegForValue(RHS);
2219 bool RHSIsKill = hasTrivialKill(RHS);
2221 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2222 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2224 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2225 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2227 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2230 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2233 if (Subtarget->hasAVX512()) {
2234 // If we have AVX512 we can use a mask compare and masked movss/sd.
2235 const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2236 const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2238 unsigned CmpOpcode =
2239 (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
2240 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpLHSIsKill,
2241 CmpRHSReg, CmpRHSIsKill, CC);
2243 // Need an IMPLICIT_DEF for the input that is used to generate the upper
2244 // bits of the result register since its not based on any of the inputs.
2245 unsigned ImplicitDefReg = createResultReg(VR128X);
2246 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2247 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2249 // Place RHSReg is the passthru of the masked movss/sd operation and put
2250 // LHS in the input. The mask input comes from the compare.
2251 unsigned MovOpcode =
2252 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
2253 unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, RHSIsKill,
2254 CmpReg, true, ImplicitDefReg, true,
2257 ResultReg = createResultReg(RC);
2258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2259 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2261 } else if (Subtarget->hasAVX()) {
2262 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2264 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2265 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2266 // uses XMM0 as the selection register. That may need just as many
2267 // instructions as the AND/ANDN/OR sequence due to register moves, so
2269 unsigned CmpOpcode =
2270 (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2271 unsigned BlendOpcode =
2272 (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2274 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
2275 CmpRHSReg, CmpRHSIsKill, CC);
2276 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2277 LHSReg, LHSIsKill, CmpReg, true);
2278 ResultReg = createResultReg(RC);
2279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2280 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
2282 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2283 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2284 CmpRHSReg, CmpRHSIsKill, CC);
2285 unsigned AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, /*IsKill=*/false,
2287 unsigned AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, /*IsKill=*/true,
2289 unsigned OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, /*IsKill=*/true,
2290 AndReg, /*IsKill=*/true);
2291 ResultReg = createResultReg(RC);
2292 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2293 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
2295 updateValueMap(I, ResultReg);
2299 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2300 // These are pseudo CMOV instructions and will be later expanded into control-
2303 switch (RetVT.SimpleTy) {
2304 default: return false;
2305 case MVT::i8: Opc = X86::CMOV_GR8; break;
2306 case MVT::i16: Opc = X86::CMOV_GR16; break;
2307 case MVT::i32: Opc = X86::CMOV_GR32; break;
2308 case MVT::f32: Opc = X86::CMOV_FR32; break;
2309 case MVT::f64: Opc = X86::CMOV_FR64; break;
2312 const Value *Cond = I->getOperand(0);
2313 X86::CondCode CC = X86::COND_NE;
2315 // Optimize conditions coming from a compare if both instructions are in the
2316 // same basic block (values defined in other basic blocks may not have
2317 // initialized registers).
2318 const auto *CI = dyn_cast<CmpInst>(Cond);
2319 if (CI && (CI->getParent() == I->getParent())) {
2321 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2322 if (CC > X86::LAST_VALID_COND)
2325 const Value *CmpLHS = CI->getOperand(0);
2326 const Value *CmpRHS = CI->getOperand(1);
2329 std::swap(CmpLHS, CmpRHS);
2331 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2332 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2335 unsigned CondReg = getRegForValue(Cond);
2338 bool CondIsKill = hasTrivialKill(Cond);
2340 // In case OpReg is a K register, COPY to a GPR
2341 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2342 unsigned KCondReg = CondReg;
2343 CondReg = createResultReg(&X86::GR32RegClass);
2344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2345 TII.get(TargetOpcode::COPY), CondReg)
2346 .addReg(KCondReg, getKillRegState(CondIsKill));
2347 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2350 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2351 .addReg(CondReg, getKillRegState(CondIsKill))
2355 const Value *LHS = I->getOperand(1);
2356 const Value *RHS = I->getOperand(2);
2358 unsigned LHSReg = getRegForValue(LHS);
2359 bool LHSIsKill = hasTrivialKill(LHS);
2361 unsigned RHSReg = getRegForValue(RHS);
2362 bool RHSIsKill = hasTrivialKill(RHS);
2364 if (!LHSReg || !RHSReg)
2367 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2369 unsigned ResultReg =
2370 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2371 updateValueMap(I, ResultReg);
2375 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2377 if (!isTypeLegal(I->getType(), RetVT))
2380 // Check if we can fold the select.
2381 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2382 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2383 const Value *Opnd = nullptr;
2384 switch (Predicate) {
2386 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2387 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2389 // No need for a select anymore - this is an unconditional move.
2391 unsigned OpReg = getRegForValue(Opnd);
2394 bool OpIsKill = hasTrivialKill(Opnd);
2395 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2396 unsigned ResultReg = createResultReg(RC);
2397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2398 TII.get(TargetOpcode::COPY), ResultReg)
2399 .addReg(OpReg, getKillRegState(OpIsKill));
2400 updateValueMap(I, ResultReg);
2405 // First try to use real conditional move instructions.
2406 if (X86FastEmitCMoveSelect(RetVT, I))
2409 // Try to use a sequence of SSE instructions to simulate a conditional move.
2410 if (X86FastEmitSSESelect(RetVT, I))
2413 // Fall-back to pseudo conditional move instructions, which will be later
2414 // converted to control-flow.
2415 if (X86FastEmitPseudoSelect(RetVT, I))
2421 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2422 // The target-independent selection algorithm in FastISel already knows how
2423 // to select a SINT_TO_FP if the target is SSE but not AVX.
2424 // Early exit if the subtarget doesn't have AVX.
2425 if (!Subtarget->hasAVX())
2428 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2431 // Select integer to float/double conversion.
2432 unsigned OpReg = getRegForValue(I->getOperand(0));
2436 const TargetRegisterClass *RC = nullptr;
2439 if (I->getType()->isDoubleTy()) {
2440 // sitofp int -> double
2441 Opcode = X86::VCVTSI2SDrr;
2442 RC = &X86::FR64RegClass;
2443 } else if (I->getType()->isFloatTy()) {
2444 // sitofp int -> float
2445 Opcode = X86::VCVTSI2SSrr;
2446 RC = &X86::FR32RegClass;
2450 unsigned ImplicitDefReg = createResultReg(RC);
2451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2452 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2453 unsigned ResultReg =
2454 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2455 updateValueMap(I, ResultReg);
2459 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2460 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2462 const TargetRegisterClass *RC) {
2463 assert((I->getOpcode() == Instruction::FPExt ||
2464 I->getOpcode() == Instruction::FPTrunc) &&
2465 "Instruction must be an FPExt or FPTrunc!");
2467 unsigned OpReg = getRegForValue(I->getOperand(0));
2471 unsigned ImplicitDefReg;
2472 if (Subtarget->hasAVX()) {
2473 ImplicitDefReg = createResultReg(RC);
2474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2475 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2479 unsigned ResultReg = createResultReg(RC);
2480 MachineInstrBuilder MIB;
2481 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2484 if (Subtarget->hasAVX())
2485 MIB.addReg(ImplicitDefReg);
2488 updateValueMap(I, ResultReg);
2492 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2493 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2494 I->getOperand(0)->getType()->isFloatTy()) {
2495 // fpext from float to double.
2496 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2497 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2503 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2504 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2505 I->getOperand(0)->getType()->isDoubleTy()) {
2506 // fptrunc from double to float.
2507 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2508 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2514 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2515 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2516 EVT DstVT = TLI.getValueType(DL, I->getType());
2518 // This code only handles truncation to byte.
2519 // TODO: Support truncate to i1 with AVX512.
2520 if (DstVT != MVT::i8 && (DstVT != MVT::i1 || Subtarget->hasAVX512()))
2522 if (!TLI.isTypeLegal(SrcVT))
2525 unsigned InputReg = getRegForValue(I->getOperand(0));
2527 // Unhandled operand. Halt "fast" selection and bail.
2530 if (SrcVT == MVT::i8) {
2531 // Truncate from i8 to i1; no code needed.
2532 updateValueMap(I, InputReg);
2536 bool KillInputReg = false;
2537 if (!Subtarget->is64Bit()) {
2538 // If we're on x86-32; we can't extract an i8 from a general register.
2539 // First issue a copy to GR16_ABCD or GR32_ABCD.
2540 const TargetRegisterClass *CopyRC =
2541 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2542 unsigned CopyReg = createResultReg(CopyRC);
2543 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2544 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2546 KillInputReg = true;
2549 // Issue an extract_subreg.
2550 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2551 InputReg, KillInputReg,
2556 updateValueMap(I, ResultReg);
2560 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2561 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2564 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2565 X86AddressMode SrcAM, uint64_t Len) {
2567 // Make sure we don't bloat code by inlining very large memcpy's.
2568 if (!IsMemcpySmall(Len))
2571 bool i64Legal = Subtarget->is64Bit();
2573 // We don't care about alignment here since we just emit integer accesses.
2576 if (Len >= 8 && i64Legal)
2586 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2587 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2588 assert(RV && "Failed to emit load or store??");
2590 unsigned Size = VT.getSizeInBits()/8;
2592 DestAM.Disp += Size;
2599 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2600 // FIXME: Handle more intrinsics.
2601 switch (II->getIntrinsicID()) {
2602 default: return false;
2603 case Intrinsic::convert_from_fp16:
2604 case Intrinsic::convert_to_fp16: {
2605 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2608 const Value *Op = II->getArgOperand(0);
2609 unsigned InputReg = getRegForValue(Op);
2613 // F16C only allows converting from float to half and from half to float.
2614 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2615 if (IsFloatToHalf) {
2616 if (!Op->getType()->isFloatTy())
2619 if (!II->getType()->isFloatTy())
2623 unsigned ResultReg = 0;
2624 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2625 if (IsFloatToHalf) {
2626 // 'InputReg' is implicitly promoted from register class FR32 to
2627 // register class VR128 by method 'constrainOperandRegClass' which is
2628 // directly called by 'fastEmitInst_ri'.
2629 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2630 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2631 // It's consistent with the other FP instructions, which are usually
2632 // controlled by MXCSR.
2633 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
2635 // Move the lower 32-bits of ResultReg to another register of class GR32.
2636 ResultReg = createResultReg(&X86::GR32RegClass);
2637 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2638 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2639 .addReg(InputReg, RegState::Kill);
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, true, RegIdx);
2645 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2646 // Explicitly sign-extend the input to 32-bit.
2647 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2650 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2651 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2652 InputReg, /*Kill=*/true);
2654 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2656 // The result value is in the lower 32-bits of ResultReg.
2657 // Emit an explicit copy from register class VR128 to register class FR32.
2658 ResultReg = createResultReg(&X86::FR32RegClass);
2659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2660 TII.get(TargetOpcode::COPY), ResultReg)
2661 .addReg(InputReg, RegState::Kill);
2664 updateValueMap(II, ResultReg);
2667 case Intrinsic::frameaddress: {
2668 MachineFunction *MF = FuncInfo.MF;
2669 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2672 Type *RetTy = II->getCalledFunction()->getReturnType();
2675 if (!isTypeLegal(RetTy, VT))
2679 const TargetRegisterClass *RC = nullptr;
2681 switch (VT.SimpleTy) {
2682 default: llvm_unreachable("Invalid result type for frameaddress.");
2683 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2684 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2687 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2688 // we get the wrong frame register.
2689 MachineFrameInfo &MFI = MF->getFrameInfo();
2690 MFI.setFrameAddressIsTaken(true);
2692 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2693 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2694 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2695 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2696 "Invalid Frame Register!");
2698 // Always make a copy of the frame register to to a vreg first, so that we
2699 // never directly reference the frame register (the TwoAddressInstruction-
2700 // Pass doesn't like that).
2701 unsigned SrcReg = createResultReg(RC);
2702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2703 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2705 // Now recursively load from the frame address.
2706 // movq (%rbp), %rax
2707 // movq (%rax), %rax
2708 // movq (%rax), %rax
2711 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2713 DestReg = createResultReg(RC);
2714 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2715 TII.get(Opc), DestReg), SrcReg);
2719 updateValueMap(II, SrcReg);
2722 case Intrinsic::memcpy: {
2723 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2724 // Don't handle volatile or variable length memcpys.
2725 if (MCI->isVolatile())
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))
2737 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2742 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2743 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2746 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2749 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2751 case Intrinsic::memset: {
2752 const MemSetInst *MSI = cast<MemSetInst>(II);
2754 if (MSI->isVolatile())
2757 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2758 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2761 if (MSI->getDestAddressSpace() > 255)
2764 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2766 case Intrinsic::stackprotector: {
2767 // Emit code to store the stack guard onto the stack.
2768 EVT PtrTy = TLI.getPointerTy(DL);
2770 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2771 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2773 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2775 // Grab the frame index.
2777 if (!X86SelectAddress(Slot, AM)) return false;
2778 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2781 case Intrinsic::dbg_declare: {
2782 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2784 assert(DI->getAddress() && "Null address should be checked earlier!");
2785 if (!X86SelectAddress(DI->getAddress(), AM))
2787 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2788 // FIXME may need to add RegState::Debug to any registers produced,
2789 // although ESP/EBP should be the only ones at the moment.
2790 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2791 "Expected inlined-at fields to agree");
2792 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2794 .addMetadata(DI->getVariable())
2795 .addMetadata(DI->getExpression());
2798 case Intrinsic::trap: {
2799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2802 case Intrinsic::sqrt: {
2803 if (!Subtarget->hasSSE1())
2806 Type *RetTy = II->getCalledFunction()->getReturnType();
2809 if (!isTypeLegal(RetTy, VT))
2812 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2813 // is not generated by FastISel yet.
2814 // FIXME: Update this code once tablegen can handle it.
2815 static const uint16_t SqrtOpc[2][2] = {
2816 {X86::SQRTSSr, X86::VSQRTSSr},
2817 {X86::SQRTSDr, X86::VSQRTSDr}
2819 bool HasAVX = Subtarget->hasAVX();
2821 const TargetRegisterClass *RC;
2822 switch (VT.SimpleTy) {
2823 default: return false;
2824 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2825 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2828 const Value *SrcVal = II->getArgOperand(0);
2829 unsigned SrcReg = getRegForValue(SrcVal);
2834 unsigned ImplicitDefReg = 0;
2836 ImplicitDefReg = createResultReg(RC);
2837 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2838 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2841 unsigned ResultReg = createResultReg(RC);
2842 MachineInstrBuilder MIB;
2843 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2847 MIB.addReg(ImplicitDefReg);
2851 updateValueMap(II, ResultReg);
2854 case Intrinsic::sadd_with_overflow:
2855 case Intrinsic::uadd_with_overflow:
2856 case Intrinsic::ssub_with_overflow:
2857 case Intrinsic::usub_with_overflow:
2858 case Intrinsic::smul_with_overflow:
2859 case Intrinsic::umul_with_overflow: {
2860 // This implements the basic lowering of the xalu with overflow intrinsics
2861 // into add/sub/mul followed by either seto or setb.
2862 const Function *Callee = II->getCalledFunction();
2863 auto *Ty = cast<StructType>(Callee->getReturnType());
2864 Type *RetTy = Ty->getTypeAtIndex(0U);
2865 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2866 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2867 "Overflow value expected to be an i1");
2870 if (!isTypeLegal(RetTy, VT))
2873 if (VT < MVT::i8 || VT > MVT::i64)
2876 const Value *LHS = II->getArgOperand(0);
2877 const Value *RHS = II->getArgOperand(1);
2879 // Canonicalize immediate to the RHS.
2880 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2881 isCommutativeIntrinsic(II))
2882 std::swap(LHS, RHS);
2884 bool UseIncDec = false;
2885 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2888 unsigned BaseOpc, CondOpc;
2889 switch (II->getIntrinsicID()) {
2890 default: llvm_unreachable("Unexpected intrinsic!");
2891 case Intrinsic::sadd_with_overflow:
2892 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2893 CondOpc = X86::SETOr;
2895 case Intrinsic::uadd_with_overflow:
2896 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2897 case Intrinsic::ssub_with_overflow:
2898 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2899 CondOpc = X86::SETOr;
2901 case Intrinsic::usub_with_overflow:
2902 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2903 case Intrinsic::smul_with_overflow:
2904 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2905 case Intrinsic::umul_with_overflow:
2906 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2909 unsigned LHSReg = getRegForValue(LHS);
2912 bool LHSIsKill = hasTrivialKill(LHS);
2914 unsigned ResultReg = 0;
2915 // Check if we have an immediate version.
2916 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2917 static const uint16_t Opc[2][4] = {
2918 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2919 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2922 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2923 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2924 bool IsDec = BaseOpc == X86ISD::DEC;
2925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2926 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2927 .addReg(LHSReg, getKillRegState(LHSIsKill));
2929 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2930 CI->getZExtValue());
2936 RHSReg = getRegForValue(RHS);
2939 RHSIsKill = hasTrivialKill(RHS);
2940 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2944 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2946 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2947 static const uint16_t MULOpc[] =
2948 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2949 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2950 // First copy the first operand into RAX, which is an implicit input to
2951 // the X86::MUL*r instruction.
2952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2953 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2954 .addReg(LHSReg, getKillRegState(LHSIsKill));
2955 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2956 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2957 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2958 static const uint16_t MULOpc[] =
2959 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2960 if (VT == MVT::i8) {
2961 // Copy the first operand into AL, which is an implicit input to the
2962 // X86::IMUL8r instruction.
2963 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2964 TII.get(TargetOpcode::COPY), X86::AL)
2965 .addReg(LHSReg, getKillRegState(LHSIsKill));
2966 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2969 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2970 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2977 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2978 unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
2979 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2983 updateValueMap(II, ResultReg, 2);
2986 case Intrinsic::x86_sse_cvttss2si:
2987 case Intrinsic::x86_sse_cvttss2si64:
2988 case Intrinsic::x86_sse2_cvttsd2si:
2989 case Intrinsic::x86_sse2_cvttsd2si64: {
2991 switch (II->getIntrinsicID()) {
2992 default: llvm_unreachable("Unexpected intrinsic.");
2993 case Intrinsic::x86_sse_cvttss2si:
2994 case Intrinsic::x86_sse_cvttss2si64:
2995 if (!Subtarget->hasSSE1())
2997 IsInputDouble = false;
2999 case Intrinsic::x86_sse2_cvttsd2si:
3000 case Intrinsic::x86_sse2_cvttsd2si64:
3001 if (!Subtarget->hasSSE2())
3003 IsInputDouble = true;
3007 Type *RetTy = II->getCalledFunction()->getReturnType();
3009 if (!isTypeLegal(RetTy, VT))
3012 static const uint16_t CvtOpc[2][2][2] = {
3013 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
3014 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
3015 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
3016 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
3018 bool HasAVX = Subtarget->hasAVX();
3020 switch (VT.SimpleTy) {
3021 default: llvm_unreachable("Unexpected result type.");
3022 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
3023 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
3026 // Check if we can fold insertelement instructions into the convert.
3027 const Value *Op = II->getArgOperand(0);
3028 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
3029 const Value *Index = IE->getOperand(2);
3030 if (!isa<ConstantInt>(Index))
3032 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
3035 Op = IE->getOperand(1);
3038 Op = IE->getOperand(0);
3041 unsigned Reg = getRegForValue(Op);
3045 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3046 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3049 updateValueMap(II, ResultReg);
3055 bool X86FastISel::fastLowerArguments() {
3056 if (!FuncInfo.CanLowerReturn)
3059 const Function *F = FuncInfo.Fn;
3063 CallingConv::ID CC = F->getCallingConv();
3064 if (CC != CallingConv::C)
3067 if (Subtarget->isCallingConvWin64(CC))
3070 if (!Subtarget->is64Bit())
3073 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3074 unsigned GPRCnt = 0;
3075 unsigned FPRCnt = 0;
3077 for (auto const &Arg : F->args()) {
3078 // The first argument is at index 1.
3080 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
3081 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
3082 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
3083 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
3084 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
3085 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
3088 Type *ArgTy = Arg.getType();
3089 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3092 EVT ArgVT = TLI.getValueType(DL, ArgTy);
3093 if (!ArgVT.isSimple()) return false;
3094 switch (ArgVT.getSimpleVT().SimpleTy) {
3095 default: return false;
3102 if (!Subtarget->hasSSE1())
3115 static const MCPhysReg GPR32ArgRegs[] = {
3116 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3118 static const MCPhysReg GPR64ArgRegs[] = {
3119 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3121 static const MCPhysReg XMMArgRegs[] = {
3122 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3123 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3126 unsigned GPRIdx = 0;
3127 unsigned FPRIdx = 0;
3128 for (auto const &Arg : F->args()) {
3129 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
3130 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3132 switch (VT.SimpleTy) {
3133 default: llvm_unreachable("Unexpected value type.");
3134 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3135 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
3136 case MVT::f32: LLVM_FALLTHROUGH;
3137 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3139 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3140 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3141 // Without this, EmitLiveInCopies may eliminate the livein if its only
3142 // use is a bitcast (which isn't turned into an instruction).
3143 unsigned ResultReg = createResultReg(RC);
3144 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3145 TII.get(TargetOpcode::COPY), ResultReg)
3146 .addReg(DstReg, getKillRegState(true));
3147 updateValueMap(&Arg, ResultReg);
3152 static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3154 ImmutableCallSite *CS) {
3155 if (Subtarget->is64Bit())
3157 if (Subtarget->getTargetTriple().isOSMSVCRT())
3159 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3160 CC == CallingConv::HiPE)
3164 if (CS->arg_empty() || !CS->paramHasAttr(0, Attribute::StructRet) ||
3165 CS->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
3171 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3172 auto &OutVals = CLI.OutVals;
3173 auto &OutFlags = CLI.OutFlags;
3174 auto &OutRegs = CLI.OutRegs;
3175 auto &Ins = CLI.Ins;
3176 auto &InRegs = CLI.InRegs;
3177 CallingConv::ID CC = CLI.CallConv;
3178 bool &IsTailCall = CLI.IsTailCall;
3179 bool IsVarArg = CLI.IsVarArg;
3180 const Value *Callee = CLI.Callee;
3181 MCSymbol *Symbol = CLI.Symbol;
3183 bool Is64Bit = Subtarget->is64Bit();
3184 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3186 // Handle only C, fastcc, and webkit_js calling conventions for now.
3188 default: return false;
3189 case CallingConv::C:
3190 case CallingConv::Fast:
3191 case CallingConv::WebKit_JS:
3192 case CallingConv::Swift:
3193 case CallingConv::X86_FastCall:
3194 case CallingConv::X86_StdCall:
3195 case CallingConv::X86_ThisCall:
3196 case CallingConv::X86_64_Win64:
3197 case CallingConv::X86_64_SysV:
3201 // Allow SelectionDAG isel to handle tail calls.
3205 // fastcc with -tailcallopt is intended to provide a guaranteed
3206 // tail call optimization. Fastisel doesn't know how to do that.
3207 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3210 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3211 // x86-32. Special handling for x86-64 is implemented.
3212 if (IsVarArg && IsWin64)
3215 // Don't know about inalloca yet.
3216 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3219 for (auto Flag : CLI.OutFlags)
3220 if (Flag.isSwiftError())
3223 SmallVector<MVT, 16> OutVTs;
3224 SmallVector<unsigned, 16> ArgRegs;
3226 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3227 // instruction. This is safe because it is common to all FastISel supported
3228 // calling conventions on x86.
3229 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3230 Value *&Val = OutVals[i];
3231 ISD::ArgFlagsTy Flags = OutFlags[i];
3232 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3233 if (CI->getBitWidth() < 32) {
3235 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3237 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3241 // Passing bools around ends up doing a trunc to i1 and passing it.
3242 // Codegen this as an argument + "and 1".
3244 auto *TI = dyn_cast<TruncInst>(Val);
3246 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3247 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3249 Value *PrevVal = TI->getOperand(0);
3250 ResultReg = getRegForValue(PrevVal);
3255 if (!isTypeLegal(PrevVal->getType(), VT))
3259 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3261 if (!isTypeLegal(Val->getType(), VT))
3263 ResultReg = getRegForValue(Val);
3269 ArgRegs.push_back(ResultReg);
3270 OutVTs.push_back(VT);
3273 // Analyze operands of the call, assigning locations to each operand.
3274 SmallVector<CCValAssign, 16> ArgLocs;
3275 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3277 // Allocate shadow area for Win64
3279 CCInfo.AllocateStack(32, 8);
3281 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3283 // Get a count of how many bytes are to be pushed on the stack.
3284 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3286 // Issue CALLSEQ_START
3287 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
3289 .addImm(NumBytes).addImm(0);
3291 // Walk the register/memloc assignments, inserting copies/loads.
3292 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3293 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3294 CCValAssign const &VA = ArgLocs[i];
3295 const Value *ArgVal = OutVals[VA.getValNo()];
3296 MVT ArgVT = OutVTs[VA.getValNo()];
3298 if (ArgVT == MVT::x86mmx)
3301 unsigned ArgReg = ArgRegs[VA.getValNo()];
3303 // Promote the value if needed.
3304 switch (VA.getLocInfo()) {
3305 case CCValAssign::Full: break;
3306 case CCValAssign::SExt: {
3307 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3308 "Unexpected extend");
3310 if (ArgVT == MVT::i1)
3313 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3315 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3316 ArgVT = VA.getLocVT();
3319 case CCValAssign::ZExt: {
3320 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3321 "Unexpected extend");
3323 // Handle zero-extension from i1 to i8, which is common.
3324 if (ArgVT == MVT::i1) {
3325 // In case SrcReg is a K register, COPY to a GPR
3326 if (MRI.getRegClass(ArgReg) == &X86::VK1RegClass) {
3327 unsigned KArgReg = ArgReg;
3328 ArgReg = createResultReg(&X86::GR32RegClass);
3329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3330 TII.get(TargetOpcode::COPY), ArgReg)
3332 ArgReg = fastEmitInst_extractsubreg(MVT::i8, ArgReg, /*Kill=*/true,
3335 // Set the high bits to zero.
3336 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3343 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3345 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3346 ArgVT = VA.getLocVT();
3349 case CCValAssign::AExt: {
3350 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3351 "Unexpected extend");
3352 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3355 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3358 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3361 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3362 ArgVT = VA.getLocVT();
3365 case CCValAssign::BCvt: {
3366 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3367 /*TODO: Kill=*/false);
3368 assert(ArgReg && "Failed to emit a bitcast!");
3369 ArgVT = VA.getLocVT();
3372 case CCValAssign::VExt:
3373 // VExt has not been implemented, so this should be impossible to reach
3374 // for now. However, fallback to Selection DAG isel once implemented.
3376 case CCValAssign::AExtUpper:
3377 case CCValAssign::SExtUpper:
3378 case CCValAssign::ZExtUpper:
3379 case CCValAssign::FPExt:
3380 llvm_unreachable("Unexpected loc info!");
3381 case CCValAssign::Indirect:
3382 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3387 if (VA.isRegLoc()) {
3388 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3389 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3390 OutRegs.push_back(VA.getLocReg());
3392 assert(VA.isMemLoc());
3394 // Don't emit stores for undef values.
3395 if (isa<UndefValue>(ArgVal))
3398 unsigned LocMemOffset = VA.getLocMemOffset();
3400 AM.Base.Reg = RegInfo->getStackRegister();
3401 AM.Disp = LocMemOffset;
3402 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3403 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3404 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3405 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3406 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3407 if (Flags.isByVal()) {
3408 X86AddressMode SrcAM;
3409 SrcAM.Base.Reg = ArgReg;
3410 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3412 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3413 // If this is a really simple value, emit this with the Value* version
3414 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3415 // as it can cause us to reevaluate the argument.
3416 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3419 bool ValIsKill = hasTrivialKill(ArgVal);
3420 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3426 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3428 if (Subtarget->isPICStyleGOT()) {
3429 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3431 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3434 if (Is64Bit && IsVarArg && !IsWin64) {
3435 // From AMD64 ABI document:
3436 // For calls that may call functions that use varargs or stdargs
3437 // (prototype-less calls or calls to functions containing ellipsis (...) in
3438 // the declaration) %al is used as hidden argument to specify the number
3439 // of SSE registers used. The contents of %al do not need to match exactly
3440 // the number of registers, but must be an ubound on the number of SSE
3441 // registers used and is in the range 0 - 8 inclusive.
3443 // Count the number of XMM registers allocated.
3444 static const MCPhysReg XMMArgRegs[] = {
3445 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3446 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3448 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3449 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3450 && "SSE registers cannot be used when SSE is disabled");
3451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3452 X86::AL).addImm(NumXMMRegs);
3455 // Materialize callee address in a register. FIXME: GV address can be
3456 // handled with a CALLpcrel32 instead.
3457 X86AddressMode CalleeAM;
3458 if (!X86SelectCallAddress(Callee, CalleeAM))
3461 unsigned CalleeOp = 0;
3462 const GlobalValue *GV = nullptr;
3463 if (CalleeAM.GV != nullptr) {
3465 } else if (CalleeAM.Base.Reg != 0) {
3466 CalleeOp = CalleeAM.Base.Reg;
3471 MachineInstrBuilder MIB;
3473 // Register-indirect call.
3474 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3475 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3479 assert(GV && "Not a direct call");
3480 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3482 // See if we need any target-specific flags on the GV operand.
3483 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
3484 // Ignore NonLazyBind attribute in FastISel
3485 if (OpFlags == X86II::MO_GOTPCREL)
3488 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3490 MIB.addSym(Symbol, OpFlags);
3492 MIB.addGlobalAddress(GV, 0, OpFlags);
3495 // Add a register mask operand representing the call-preserved registers.
3496 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3497 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3499 // Add an implicit use GOT pointer in EBX.
3500 if (Subtarget->isPICStyleGOT())
3501 MIB.addReg(X86::EBX, RegState::Implicit);
3503 if (Is64Bit && IsVarArg && !IsWin64)
3504 MIB.addReg(X86::AL, RegState::Implicit);
3506 // Add implicit physical register uses to the call.
3507 for (auto Reg : OutRegs)
3508 MIB.addReg(Reg, RegState::Implicit);
3510 // Issue CALLSEQ_END
3511 unsigned NumBytesForCalleeToPop =
3512 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3513 TM.Options.GuaranteedTailCallOpt)
3514 ? NumBytes // Callee pops everything.
3515 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
3516 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3518 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3520 // Now handle call return values.
3521 SmallVector<CCValAssign, 16> RVLocs;
3522 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3523 CLI.RetTy->getContext());
3524 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3526 // Copy all of the result registers out of their specified physreg.
3527 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3528 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3529 CCValAssign &VA = RVLocs[i];
3530 EVT CopyVT = VA.getValVT();
3531 unsigned CopyReg = ResultReg + i;
3532 unsigned SrcReg = VA.getLocReg();
3534 // If this is x86-64, and we disabled SSE, we can't return FP values
3535 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3536 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3537 report_fatal_error("SSE register return with SSE disabled");
3540 // If the return value is an i1 and AVX-512 is enabled, we need
3541 // to do a fixup to make the copy legal.
3542 if (CopyVT == MVT::i1 && SrcReg == X86::AL && Subtarget->hasAVX512()) {
3543 // Need to copy to a GR32 first.
3544 // TODO: MOVZX isn't great here. We don't care about the upper bits.
3545 SrcReg = createResultReg(&X86::GR32RegClass);
3546 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3547 TII.get(X86::MOVZX32rr8), SrcReg).addReg(X86::AL);
3550 // If we prefer to use the value in xmm registers, copy it out as f80 and
3551 // use a truncate to move it from fp stack reg to xmm reg.
3552 if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
3553 isScalarFPTypeInSSEReg(VA.getValVT())) {
3555 CopyReg = createResultReg(&X86::RFP80RegClass);
3558 // Copy out the result.
3559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3560 TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
3561 InRegs.push_back(VA.getLocReg());
3563 // Round the f80 to the right size, which also moves it to the appropriate
3564 // xmm register. This is accomplished by storing the f80 value in memory
3565 // and then loading it back.
3566 if (CopyVT != VA.getValVT()) {
3567 EVT ResVT = VA.getValVT();
3568 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3569 unsigned MemSize = ResVT.getSizeInBits()/8;
3570 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3571 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3574 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3575 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3576 TII.get(Opc), ResultReg + i), FI);
3580 CLI.ResultReg = ResultReg;
3581 CLI.NumResultRegs = RVLocs.size();
3588 X86FastISel::fastSelectInstruction(const Instruction *I) {
3589 switch (I->getOpcode()) {
3591 case Instruction::Load:
3592 return X86SelectLoad(I);
3593 case Instruction::Store:
3594 return X86SelectStore(I);
3595 case Instruction::Ret:
3596 return X86SelectRet(I);
3597 case Instruction::ICmp:
3598 case Instruction::FCmp:
3599 return X86SelectCmp(I);
3600 case Instruction::ZExt:
3601 return X86SelectZExt(I);
3602 case Instruction::Br:
3603 return X86SelectBranch(I);
3604 case Instruction::LShr:
3605 case Instruction::AShr:
3606 case Instruction::Shl:
3607 return X86SelectShift(I);
3608 case Instruction::SDiv:
3609 case Instruction::UDiv:
3610 case Instruction::SRem:
3611 case Instruction::URem:
3612 return X86SelectDivRem(I);
3613 case Instruction::Select:
3614 return X86SelectSelect(I);
3615 case Instruction::Trunc:
3616 return X86SelectTrunc(I);
3617 case Instruction::FPExt:
3618 return X86SelectFPExt(I);
3619 case Instruction::FPTrunc:
3620 return X86SelectFPTrunc(I);
3621 case Instruction::SIToFP:
3622 return X86SelectSIToFP(I);
3623 case Instruction::IntToPtr: // Deliberate fall-through.
3624 case Instruction::PtrToInt: {
3625 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3626 EVT DstVT = TLI.getValueType(DL, I->getType());
3627 if (DstVT.bitsGT(SrcVT))
3628 return X86SelectZExt(I);
3629 if (DstVT.bitsLT(SrcVT))
3630 return X86SelectTrunc(I);
3631 unsigned Reg = getRegForValue(I->getOperand(0));
3632 if (Reg == 0) return false;
3633 updateValueMap(I, Reg);
3636 case Instruction::BitCast: {
3637 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3638 if (!Subtarget->hasSSE2())
3641 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3642 EVT DstVT = TLI.getValueType(DL, I->getType());
3644 if (!SrcVT.isSimple() || !DstVT.isSimple())
3647 MVT SVT = SrcVT.getSimpleVT();
3648 MVT DVT = DstVT.getSimpleVT();
3650 if (!SVT.is128BitVector() &&
3651 !(Subtarget->hasAVX() && SVT.is256BitVector()) &&
3652 !(Subtarget->hasAVX512() && SVT.is512BitVector() &&
3653 (Subtarget->hasBWI() || (SVT.getScalarSizeInBits() >= 32 &&
3654 DVT.getScalarSizeInBits() >= 32))))
3657 unsigned Reg = getRegForValue(I->getOperand(0));
3661 // No instruction is needed for conversion. Reuse the register used by
3662 // the fist operand.
3663 updateValueMap(I, Reg);
3671 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3675 uint64_t Imm = CI->getZExtValue();
3677 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3678 switch (VT.SimpleTy) {
3679 default: llvm_unreachable("Unexpected value type");
3681 if (Subtarget->hasAVX512()) {
3682 // Need to copy to a VK1 register.
3683 unsigned ResultReg = createResultReg(&X86::VK1RegClass);
3684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3685 TII.get(TargetOpcode::COPY), ResultReg).addReg(SrcReg);
3689 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3692 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3697 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3698 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3699 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3700 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3707 switch (VT.SimpleTy) {
3708 default: llvm_unreachable("Unexpected value type");
3710 // TODO: Support this properly.
3711 if (Subtarget->hasAVX512())
3715 case MVT::i8: Opc = X86::MOV8ri; break;
3716 case MVT::i16: Opc = X86::MOV16ri; break;
3717 case MVT::i32: Opc = X86::MOV32ri; break;
3719 if (isUInt<32>(Imm))
3721 else if (isInt<32>(Imm))
3722 Opc = X86::MOV64ri32;
3728 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3729 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3730 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3731 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3732 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3733 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3736 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3739 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3740 if (CFP->isNullValue())
3741 return fastMaterializeFloatZero(CFP);
3743 // Can't handle alternate code models yet.
3744 CodeModel::Model CM = TM.getCodeModel();
3745 if (CM != CodeModel::Small && CM != CodeModel::Large)
3748 // Get opcode and regclass of the output for the given load instruction.
3750 const TargetRegisterClass *RC = nullptr;
3751 switch (VT.SimpleTy) {
3754 if (X86ScalarSSEf32) {
3755 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3756 RC = &X86::FR32RegClass;
3758 Opc = X86::LD_Fp32m;
3759 RC = &X86::RFP32RegClass;
3763 if (X86ScalarSSEf64) {
3764 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3765 RC = &X86::FR64RegClass;
3767 Opc = X86::LD_Fp64m;
3768 RC = &X86::RFP64RegClass;
3772 // No f80 support yet.
3776 // MachineConstantPool wants an explicit alignment.
3777 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3779 // Alignment of vector types. FIXME!
3780 Align = DL.getTypeAllocSize(CFP->getType());
3783 // x86-32 PIC requires a PIC base register for constant pools.
3784 unsigned PICBase = 0;
3785 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3786 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
3787 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3788 else if (OpFlag == X86II::MO_GOTOFF)
3789 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3790 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
3793 // Create the load from the constant pool.
3794 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3795 unsigned ResultReg = createResultReg(RC);
3797 if (CM == CodeModel::Large) {
3798 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3801 .addConstantPoolIndex(CPI, 0, OpFlag);
3802 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3803 TII.get(Opc), ResultReg);
3804 addDirectMem(MIB, AddrReg);
3805 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3806 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3807 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
3808 MIB->addMemOperand(*FuncInfo.MF, MMO);
3812 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3813 TII.get(Opc), ResultReg),
3814 CPI, PICBase, OpFlag);
3818 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3819 // Can't handle alternate code models yet.
3820 if (TM.getCodeModel() != CodeModel::Small)
3823 // Materialize addresses with LEA/MOV instructions.
3825 if (X86SelectAddress(GV, AM)) {
3826 // If the expression is just a basereg, then we're done, otherwise we need
3828 if (AM.BaseType == X86AddressMode::RegBase &&
3829 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3832 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3833 if (TM.getRelocationModel() == Reloc::Static &&
3834 TLI.getPointerTy(DL) == MVT::i64) {
3835 // The displacement code could be more than 32 bits away so we need to use
3836 // an instruction with a 64 bit immediate
3837 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3839 .addGlobalAddress(GV);
3842 TLI.getPointerTy(DL) == MVT::i32
3843 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3845 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3846 TII.get(Opc), ResultReg), AM);
3853 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3854 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3856 // Only handle simple types.
3857 if (!CEVT.isSimple())
3859 MVT VT = CEVT.getSimpleVT();
3861 if (const auto *CI = dyn_cast<ConstantInt>(C))
3862 return X86MaterializeInt(CI, VT);
3863 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3864 return X86MaterializeFP(CFP, VT);
3865 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3866 return X86MaterializeGV(GV, VT);
3871 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3872 // Fail on dynamic allocas. At this point, getRegForValue has already
3873 // checked its CSE maps, so if we're here trying to handle a dynamic
3874 // alloca, we're not going to succeed. X86SelectAddress has a
3875 // check for dynamic allocas, because it's called directly from
3876 // various places, but targetMaterializeAlloca also needs a check
3877 // in order to avoid recursion between getRegForValue,
3878 // X86SelectAddrss, and targetMaterializeAlloca.
3879 if (!FuncInfo.StaticAllocaMap.count(C))
3881 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3884 if (!X86SelectAddress(C, AM))
3887 TLI.getPointerTy(DL) == MVT::i32
3888 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3890 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3891 unsigned ResultReg = createResultReg(RC);
3892 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3893 TII.get(Opc), ResultReg), AM);
3897 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3899 if (!isTypeLegal(CF->getType(), VT))
3902 // Get opcode and regclass for the given zero.
3904 const TargetRegisterClass *RC = nullptr;
3905 switch (VT.SimpleTy) {
3908 if (X86ScalarSSEf32) {
3909 Opc = X86::FsFLD0SS;
3910 RC = &X86::FR32RegClass;
3912 Opc = X86::LD_Fp032;
3913 RC = &X86::RFP32RegClass;
3917 if (X86ScalarSSEf64) {
3918 Opc = X86::FsFLD0SD;
3919 RC = &X86::FR64RegClass;
3921 Opc = X86::LD_Fp064;
3922 RC = &X86::RFP64RegClass;
3926 // No f80 support yet.
3930 unsigned ResultReg = createResultReg(RC);
3931 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3936 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3937 const LoadInst *LI) {
3938 const Value *Ptr = LI->getPointerOperand();
3940 if (!X86SelectAddress(Ptr, AM))
3943 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3945 unsigned Size = DL.getTypeAllocSize(LI->getType());
3946 unsigned Alignment = LI->getAlignment();
3948 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3949 Alignment = DL.getABITypeAlignment(LI->getType());
3951 SmallVector<MachineOperand, 8> AddrOps;
3952 AM.getFullAddress(AddrOps);
3954 MachineInstr *Result = XII.foldMemoryOperandImpl(
3955 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3956 /*AllowCommute=*/true);
3960 // The index register could be in the wrong register class. Unfortunately,
3961 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3962 // to just look at OpNo + the offset to the index reg. We actually need to
3963 // scan the instruction to find the index reg and see if its the correct reg
3965 unsigned OperandNo = 0;
3966 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3967 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3968 MachineOperand &MO = *I;
3969 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3971 // Found the index reg, now try to rewrite it.
3972 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3973 MO.getReg(), OperandNo);
3974 if (IndexReg == MO.getReg())
3976 MO.setReg(IndexReg);
3979 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3980 MI->eraseFromParent();
3984 unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
3985 const TargetRegisterClass *RC,
3986 unsigned Op0, bool Op0IsKill,
3987 unsigned Op1, bool Op1IsKill,
3988 unsigned Op2, bool Op2IsKill,
3989 unsigned Op3, bool Op3IsKill) {
3990 const MCInstrDesc &II = TII.get(MachineInstOpcode);
3992 unsigned ResultReg = createResultReg(RC);
3993 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
3994 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
3995 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
3996 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 3);
3998 if (II.getNumDefs() >= 1)
3999 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
4000 .addReg(Op0, getKillRegState(Op0IsKill))
4001 .addReg(Op1, getKillRegState(Op1IsKill))
4002 .addReg(Op2, getKillRegState(Op2IsKill))
4003 .addReg(Op3, getKillRegState(Op3IsKill));
4005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
4006 .addReg(Op0, getKillRegState(Op0IsKill))
4007 .addReg(Op1, getKillRegState(Op1IsKill))
4008 .addReg(Op2, getKillRegState(Op2IsKill))
4009 .addReg(Op3, getKillRegState(Op3IsKill));
4010 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4011 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
4018 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
4019 const TargetLibraryInfo *libInfo) {
4020 return new X86FastISel(funcInfo, libInfo);