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/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.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, DebugLoc DL);
87 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
88 unsigned &ResultReg, unsigned Alignment = 1);
90 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
91 MachineMemOperand *MMO = nullptr, bool Aligned = false);
92 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
94 MachineMemOperand *MMO = nullptr, bool Aligned = false);
96 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
99 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
100 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
102 bool X86SelectLoad(const Instruction *I);
104 bool X86SelectStore(const Instruction *I);
106 bool X86SelectRet(const Instruction *I);
108 bool X86SelectCmp(const Instruction *I);
110 bool X86SelectZExt(const Instruction *I);
112 bool X86SelectBranch(const Instruction *I);
114 bool X86SelectShift(const Instruction *I);
116 bool X86SelectDivRem(const Instruction *I);
118 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
120 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
122 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
124 bool X86SelectSelect(const Instruction *I);
126 bool X86SelectTrunc(const Instruction *I);
128 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
129 const TargetRegisterClass *RC);
131 bool X86SelectFPExt(const Instruction *I);
132 bool X86SelectFPTrunc(const Instruction *I);
133 bool X86SelectSIToFP(const Instruction *I);
135 const X86InstrInfo *getInstrInfo() const {
136 return Subtarget->getInstrInfo();
138 const X86TargetMachine *getTargetMachine() const {
139 return static_cast<const X86TargetMachine *>(&TM);
142 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
144 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
145 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
146 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
147 unsigned fastMaterializeConstant(const Constant *C) override;
149 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
151 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
153 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
154 /// computed in an SSE register, not on the X87 floating point stack.
155 bool isScalarFPTypeInSSEReg(EVT VT) const {
156 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
157 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
160 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
162 bool IsMemcpySmall(uint64_t Len);
164 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
165 X86AddressMode SrcAM, uint64_t Len);
167 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
170 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
174 } // end anonymous namespace.
176 static std::pair<X86::CondCode, bool>
177 getX86ConditionCode(CmpInst::Predicate Predicate) {
178 X86::CondCode CC = X86::COND_INVALID;
179 bool NeedSwap = false;
182 // Floating-point Predicates
183 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
184 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
185 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
186 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
187 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
188 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
189 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
190 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
191 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
192 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
193 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
194 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
195 case CmpInst::FCMP_OEQ: // fall-through
196 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
198 // Integer Predicates
199 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
200 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
201 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
202 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
203 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
204 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
205 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
206 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
207 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
208 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
211 return std::make_pair(CC, NeedSwap);
214 static std::pair<unsigned, bool>
215 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
217 bool NeedSwap = false;
219 // SSE Condition code mapping:
229 default: llvm_unreachable("Unexpected predicate");
230 case CmpInst::FCMP_OEQ: CC = 0; break;
231 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
232 case CmpInst::FCMP_OLT: CC = 1; break;
233 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
234 case CmpInst::FCMP_OLE: CC = 2; break;
235 case CmpInst::FCMP_UNO: CC = 3; break;
236 case CmpInst::FCMP_UNE: CC = 4; break;
237 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
238 case CmpInst::FCMP_UGE: CC = 5; break;
239 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
240 case CmpInst::FCMP_UGT: CC = 6; break;
241 case CmpInst::FCMP_ORD: CC = 7; break;
242 case CmpInst::FCMP_UEQ:
243 case CmpInst::FCMP_ONE: CC = 8; break;
246 return std::make_pair(CC, NeedSwap);
249 /// \brief Adds a complex addressing mode to the given machine instr builder.
250 /// Note, this will constrain the index register. If its not possible to
251 /// constrain the given index register, then a new one will be created. The
252 /// IndexReg field of the addressing mode will be updated to match in this case.
253 const MachineInstrBuilder &
254 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
255 X86AddressMode &AM) {
256 // First constrain the index register. It needs to be a GR64_NOSP.
257 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
258 MIB->getNumOperands() +
260 return ::addFullAddress(MIB, AM);
263 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
264 /// into the user. The condition code will only be updated on success.
265 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
267 if (!isa<ExtractValueInst>(Cond))
270 const auto *EV = cast<ExtractValueInst>(Cond);
271 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
274 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
276 const Function *Callee = II->getCalledFunction();
278 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
279 if (!isTypeLegal(RetTy, RetVT))
282 if (RetVT != MVT::i32 && RetVT != MVT::i64)
286 switch (II->getIntrinsicID()) {
287 default: return false;
288 case Intrinsic::sadd_with_overflow:
289 case Intrinsic::ssub_with_overflow:
290 case Intrinsic::smul_with_overflow:
291 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
292 case Intrinsic::uadd_with_overflow:
293 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
296 // Check if both instructions are in the same basic block.
297 if (II->getParent() != I->getParent())
300 // Make sure nothing is in the way
301 BasicBlock::const_iterator Start = I;
302 BasicBlock::const_iterator End = II;
303 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
304 // We only expect extractvalue instructions between the intrinsic and the
305 // instruction to be selected.
306 if (!isa<ExtractValueInst>(Itr))
309 // Check that the extractvalue operand comes from the intrinsic.
310 const auto *EVI = cast<ExtractValueInst>(Itr);
311 if (EVI->getAggregateOperand() != II)
319 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
320 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
321 if (evt == MVT::Other || !evt.isSimple())
322 // Unhandled type. Halt "fast" selection and bail.
325 VT = evt.getSimpleVT();
326 // For now, require SSE/SSE2 for performing floating-point operations,
327 // since x87 requires additional work.
328 if (VT == MVT::f64 && !X86ScalarSSEf64)
330 if (VT == MVT::f32 && !X86ScalarSSEf32)
332 // Similarly, no f80 support yet.
335 // We only handle legal types. For example, on x86-32 the instruction
336 // selector contains all of the 64-bit instructions from x86-64,
337 // under the assumption that i64 won't be used if the target doesn't
339 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
342 #include "X86GenCallingConv.inc"
344 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
345 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
346 /// Return true and the result register by reference if it is possible.
347 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
348 MachineMemOperand *MMO, unsigned &ResultReg,
349 unsigned Alignment) {
350 // Get opcode and regclass of the output for the given load instruction.
352 const TargetRegisterClass *RC = nullptr;
353 switch (VT.getSimpleVT().SimpleTy) {
354 default: return false;
358 RC = &X86::GR8RegClass;
362 RC = &X86::GR16RegClass;
366 RC = &X86::GR32RegClass;
369 // Must be in x86-64 mode.
371 RC = &X86::GR64RegClass;
374 if (X86ScalarSSEf32) {
375 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
376 RC = &X86::FR32RegClass;
379 RC = &X86::RFP32RegClass;
383 if (X86ScalarSSEf64) {
384 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
385 RC = &X86::FR64RegClass;
388 RC = &X86::RFP64RegClass;
392 // No f80 support yet.
396 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
398 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
399 RC = &X86::VR128RegClass;
403 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
405 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
406 RC = &X86::VR128RegClass;
413 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
415 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
416 RC = &X86::VR128RegClass;
420 ResultReg = createResultReg(RC);
421 MachineInstrBuilder MIB =
422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
423 addFullAddress(MIB, AM);
425 MIB->addMemOperand(*FuncInfo.MF, MMO);
429 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
430 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
431 /// and a displacement offset, or a GlobalAddress,
432 /// i.e. V. Return true if it is possible.
433 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
435 MachineMemOperand *MMO, bool Aligned) {
436 // Get opcode and regclass of the output for the given store instruction.
438 switch (VT.getSimpleVT().SimpleTy) {
439 case MVT::f80: // No f80 support yet.
440 default: return false;
442 // Mask out all but lowest bit.
443 unsigned AndResult = createResultReg(&X86::GR8RegClass);
444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
445 TII.get(X86::AND8ri), AndResult)
446 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
449 // FALLTHROUGH, handling i1 as i8.
450 case MVT::i8: Opc = X86::MOV8mr; break;
451 case MVT::i16: Opc = X86::MOV16mr; break;
452 case MVT::i32: Opc = X86::MOV32mr; break;
453 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
455 Opc = X86ScalarSSEf32 ?
456 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
459 Opc = X86ScalarSSEf64 ?
460 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
464 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
466 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
470 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
472 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
479 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
481 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
485 MachineInstrBuilder MIB =
486 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
487 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
489 MIB->addMemOperand(*FuncInfo.MF, MMO);
494 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
496 MachineMemOperand *MMO, bool Aligned) {
497 // Handle 'null' like i32/i64 0.
498 if (isa<ConstantPointerNull>(Val))
499 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
501 // If this is a store of a simple constant, fold the constant into the store.
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
505 switch (VT.getSimpleVT().SimpleTy) {
507 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
508 case MVT::i8: Opc = X86::MOV8mi; break;
509 case MVT::i16: Opc = X86::MOV16mi; break;
510 case MVT::i32: Opc = X86::MOV32mi; break;
512 // Must be a 32-bit sign extended value.
513 if (isInt<32>(CI->getSExtValue()))
514 Opc = X86::MOV64mi32;
519 MachineInstrBuilder MIB =
520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
521 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
522 : CI->getZExtValue());
524 MIB->addMemOperand(*FuncInfo.MF, MMO);
529 unsigned ValReg = getRegForValue(Val);
533 bool ValKill = hasTrivialKill(Val);
534 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
537 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
538 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
539 /// ISD::SIGN_EXTEND).
540 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
541 unsigned Src, EVT SrcVT,
542 unsigned &ResultReg) {
543 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
544 Src, /*TODO: Kill=*/false);
552 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
553 // Handle constant address.
554 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
555 // Can't handle alternate code models yet.
556 if (TM.getCodeModel() != CodeModel::Small)
559 // Can't handle TLS yet.
560 if (GV->isThreadLocal())
563 // RIP-relative addresses can't have additional register operands, so if
564 // we've already folded stuff into the addressing mode, just force the
565 // global value into its own register, which we can use as the basereg.
566 if (!Subtarget->isPICStyleRIPRel() ||
567 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
568 // Okay, we've committed to selecting this global. Set up the address.
571 // Allow the subtarget to classify the global.
572 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
574 // If this reference is relative to the pic base, set it now.
575 if (isGlobalRelativeToPICBase(GVFlags)) {
576 // FIXME: How do we know Base.Reg is free??
577 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
580 // Unless the ABI requires an extra load, return a direct reference to
582 if (!isGlobalStubReference(GVFlags)) {
583 if (Subtarget->isPICStyleRIPRel()) {
584 // Use rip-relative addressing if we can. Above we verified that the
585 // base and index registers are unused.
586 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
587 AM.Base.Reg = X86::RIP;
589 AM.GVOpFlags = GVFlags;
593 // Ok, we need to do a load from a stub. If we've already loaded from
594 // this stub, reuse the loaded pointer, otherwise emit the load now.
595 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
597 if (I != LocalValueMap.end() && I->second != 0) {
600 // Issue load from stub.
602 const TargetRegisterClass *RC = nullptr;
603 X86AddressMode StubAM;
604 StubAM.Base.Reg = AM.Base.Reg;
606 StubAM.GVOpFlags = GVFlags;
608 // Prepare for inserting code in the local-value area.
609 SavePoint SaveInsertPt = enterLocalValueArea();
611 if (TLI.getPointerTy(DL) == MVT::i64) {
613 RC = &X86::GR64RegClass;
615 if (Subtarget->isPICStyleRIPRel())
616 StubAM.Base.Reg = X86::RIP;
619 RC = &X86::GR32RegClass;
622 LoadReg = createResultReg(RC);
623 MachineInstrBuilder LoadMI =
624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
625 addFullAddress(LoadMI, StubAM);
627 // Ok, back to normal mode.
628 leaveLocalValueArea(SaveInsertPt);
630 // Prevent loading GV stub multiple times in same MBB.
631 LocalValueMap[V] = LoadReg;
634 // Now construct the final address. Note that the Disp, Scale,
635 // and Index values may already be set here.
636 AM.Base.Reg = LoadReg;
642 // If all else fails, try to materialize the value in a register.
643 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
644 if (AM.Base.Reg == 0) {
645 AM.Base.Reg = getRegForValue(V);
646 return AM.Base.Reg != 0;
648 if (AM.IndexReg == 0) {
649 assert(AM.Scale == 1 && "Scale with no index!");
650 AM.IndexReg = getRegForValue(V);
651 return AM.IndexReg != 0;
658 /// X86SelectAddress - Attempt to fill in an address from the given value.
660 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
661 SmallVector<const Value *, 32> GEPs;
663 const User *U = nullptr;
664 unsigned Opcode = Instruction::UserOp1;
665 if (const Instruction *I = dyn_cast<Instruction>(V)) {
666 // Don't walk into other basic blocks; it's possible we haven't
667 // visited them yet, so the instructions may not yet be assigned
668 // virtual registers.
669 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
670 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
671 Opcode = I->getOpcode();
674 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
675 Opcode = C->getOpcode();
679 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
680 if (Ty->getAddressSpace() > 255)
681 // Fast instruction selection doesn't support the special
687 case Instruction::BitCast:
688 // Look past bitcasts.
689 return X86SelectAddress(U->getOperand(0), AM);
691 case Instruction::IntToPtr:
692 // Look past no-op inttoptrs.
693 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
694 TLI.getPointerTy(DL))
695 return X86SelectAddress(U->getOperand(0), AM);
698 case Instruction::PtrToInt:
699 // Look past no-op ptrtoints.
700 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
701 return X86SelectAddress(U->getOperand(0), AM);
704 case Instruction::Alloca: {
705 // Do static allocas.
706 const AllocaInst *A = cast<AllocaInst>(V);
707 DenseMap<const AllocaInst *, int>::iterator SI =
708 FuncInfo.StaticAllocaMap.find(A);
709 if (SI != FuncInfo.StaticAllocaMap.end()) {
710 AM.BaseType = X86AddressMode::FrameIndexBase;
711 AM.Base.FrameIndex = SI->second;
717 case Instruction::Add: {
718 // Adds of constants are common and easy enough.
719 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
720 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
721 // They have to fit in the 32-bit signed displacement field though.
722 if (isInt<32>(Disp)) {
723 AM.Disp = (uint32_t)Disp;
724 return X86SelectAddress(U->getOperand(0), AM);
730 case Instruction::GetElementPtr: {
731 X86AddressMode SavedAM = AM;
733 // Pattern-match simple GEPs.
734 uint64_t Disp = (int32_t)AM.Disp;
735 unsigned IndexReg = AM.IndexReg;
736 unsigned Scale = AM.Scale;
737 gep_type_iterator GTI = gep_type_begin(U);
738 // Iterate through the indices, folding what we can. Constants can be
739 // folded, and one dynamic index can be handled, if the scale is supported.
740 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
741 i != e; ++i, ++GTI) {
742 const Value *Op = *i;
743 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
744 const StructLayout *SL = DL.getStructLayout(STy);
745 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
749 // A array/variable index is always of the form i*S where S is the
750 // constant scale size. See if we can push the scale into immediates.
751 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
754 // Constant-offset addressing.
755 Disp += CI->getSExtValue() * S;
758 if (canFoldAddIntoGEP(U, Op)) {
759 // A compatible add with a constant operand. Fold the constant.
761 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
762 Disp += CI->getSExtValue() * S;
763 // Iterate on the other operand.
764 Op = cast<AddOperator>(Op)->getOperand(0);
768 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
769 (S == 1 || S == 2 || S == 4 || S == 8)) {
770 // Scaled-index addressing.
772 IndexReg = getRegForGEPIndex(Op).first;
778 goto unsupported_gep;
782 // Check for displacement overflow.
783 if (!isInt<32>(Disp))
786 AM.IndexReg = IndexReg;
788 AM.Disp = (uint32_t)Disp;
791 if (const GetElementPtrInst *GEP =
792 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
793 // Ok, the GEP indices were covered by constant-offset and scaled-index
794 // addressing. Update the address state and move on to examining the base.
797 } else if (X86SelectAddress(U->getOperand(0), AM)) {
801 // If we couldn't merge the gep value into this addr mode, revert back to
802 // our address and just match the value instead of completely failing.
805 for (SmallVectorImpl<const Value *>::reverse_iterator
806 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
807 if (handleConstantAddresses(*I, AM))
812 // Ok, the GEP indices weren't all covered.
817 return handleConstantAddresses(V, AM);
820 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
822 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
823 const User *U = nullptr;
824 unsigned Opcode = Instruction::UserOp1;
825 const Instruction *I = dyn_cast<Instruction>(V);
826 // Record if the value is defined in the same basic block.
828 // This information is crucial to know whether or not folding an
830 // Indeed, FastISel generates or reuses a virtual register for all
831 // operands of all instructions it selects. Obviously, the definition and
832 // its uses must use the same virtual register otherwise the produced
833 // code is incorrect.
834 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
835 // registers for values that are alive across basic blocks. This ensures
836 // that the values are consistently set between across basic block, even
837 // if different instruction selection mechanisms are used (e.g., a mix of
838 // SDISel and FastISel).
839 // For values local to a basic block, the instruction selection process
840 // generates these virtual registers with whatever method is appropriate
841 // for its needs. In particular, FastISel and SDISel do not share the way
842 // local virtual registers are set.
843 // Therefore, this is impossible (or at least unsafe) to share values
844 // between basic blocks unless they use the same instruction selection
845 // method, which is not guarantee for X86.
846 // Moreover, things like hasOneUse could not be used accurately, if we
847 // allow to reference values across basic blocks whereas they are not
848 // alive across basic blocks initially.
851 Opcode = I->getOpcode();
853 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
854 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
855 Opcode = C->getOpcode();
861 case Instruction::BitCast:
862 // Look past bitcasts if its operand is in the same BB.
864 return X86SelectCallAddress(U->getOperand(0), AM);
867 case Instruction::IntToPtr:
868 // Look past no-op inttoptrs if its operand is in the same BB.
870 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
871 TLI.getPointerTy(DL))
872 return X86SelectCallAddress(U->getOperand(0), AM);
875 case Instruction::PtrToInt:
876 // Look past no-op ptrtoints if its operand is in the same BB.
877 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
878 return X86SelectCallAddress(U->getOperand(0), AM);
882 // Handle constant address.
883 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
884 // Can't handle alternate code models yet.
885 if (TM.getCodeModel() != CodeModel::Small)
888 // RIP-relative addresses can't have additional register operands.
889 if (Subtarget->isPICStyleRIPRel() &&
890 (AM.Base.Reg != 0 || AM.IndexReg != 0))
893 // Can't handle DLL Import.
894 if (GV->hasDLLImportStorageClass())
898 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
899 if (GVar->isThreadLocal())
902 // Okay, we've committed to selecting this global. Set up the basic address.
905 // No ABI requires an extra load for anything other than DLLImport, which
906 // we rejected above. Return a direct reference to the global.
907 if (Subtarget->isPICStyleRIPRel()) {
908 // Use rip-relative addressing if we can. Above we verified that the
909 // base and index registers are unused.
910 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
911 AM.Base.Reg = X86::RIP;
912 } else if (Subtarget->isPICStyleStubPIC()) {
913 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
914 } else if (Subtarget->isPICStyleGOT()) {
915 AM.GVOpFlags = X86II::MO_GOTOFF;
921 // If all else fails, try to materialize the value in a register.
922 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
923 if (AM.Base.Reg == 0) {
924 AM.Base.Reg = getRegForValue(V);
925 return AM.Base.Reg != 0;
927 if (AM.IndexReg == 0) {
928 assert(AM.Scale == 1 && "Scale with no index!");
929 AM.IndexReg = getRegForValue(V);
930 return AM.IndexReg != 0;
938 /// X86SelectStore - Select and emit code to implement store instructions.
939 bool X86FastISel::X86SelectStore(const Instruction *I) {
940 // Atomic stores need special handling.
941 const StoreInst *S = cast<StoreInst>(I);
946 const Value *Val = S->getValueOperand();
947 const Value *Ptr = S->getPointerOperand();
950 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
953 unsigned Alignment = S->getAlignment();
954 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
955 if (Alignment == 0) // Ensure that codegen never sees alignment 0
956 Alignment = ABIAlignment;
957 bool Aligned = Alignment >= ABIAlignment;
960 if (!X86SelectAddress(Ptr, AM))
963 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
966 /// X86SelectRet - Select and emit code to implement ret instructions.
967 bool X86FastISel::X86SelectRet(const Instruction *I) {
968 const ReturnInst *Ret = cast<ReturnInst>(I);
969 const Function &F = *I->getParent()->getParent();
970 const X86MachineFunctionInfo *X86MFInfo =
971 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
973 if (!FuncInfo.CanLowerReturn)
976 CallingConv::ID CC = F.getCallingConv();
977 if (CC != CallingConv::C &&
978 CC != CallingConv::Fast &&
979 CC != CallingConv::X86_FastCall &&
980 CC != CallingConv::X86_64_SysV)
983 if (Subtarget->isCallingConvWin64(CC))
986 // Don't handle popping bytes on return for now.
987 if (X86MFInfo->getBytesToPopOnReturn() != 0)
990 // fastcc with -tailcallopt is intended to provide a guaranteed
991 // tail call optimization. Fastisel doesn't know how to do that.
992 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
995 // Let SDISel handle vararg functions.
999 // Build a list of return value registers.
1000 SmallVector<unsigned, 4> RetRegs;
1002 if (Ret->getNumOperands() > 0) {
1003 SmallVector<ISD::OutputArg, 4> Outs;
1004 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1006 // Analyze operands of the call, assigning locations to each operand.
1007 SmallVector<CCValAssign, 16> ValLocs;
1008 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1009 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1011 const Value *RV = Ret->getOperand(0);
1012 unsigned Reg = getRegForValue(RV);
1016 // Only handle a single return value for now.
1017 if (ValLocs.size() != 1)
1020 CCValAssign &VA = ValLocs[0];
1022 // Don't bother handling odd stuff for now.
1023 if (VA.getLocInfo() != CCValAssign::Full)
1025 // Only handle register returns for now.
1029 // The calling-convention tables for x87 returns don't tell
1031 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1034 unsigned SrcReg = Reg + VA.getValNo();
1035 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1036 EVT DstVT = VA.getValVT();
1037 // Special handling for extended integers.
1038 if (SrcVT != DstVT) {
1039 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1042 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1045 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1047 if (SrcVT == MVT::i1) {
1048 if (Outs[0].Flags.isSExt())
1050 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1053 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1055 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1056 SrcReg, /*TODO: Kill=*/false);
1060 unsigned DstReg = VA.getLocReg();
1061 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1062 // Avoid a cross-class copy. This is very unlikely.
1063 if (!SrcRC->contains(DstReg))
1065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1066 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1068 // Add register to return instruction.
1069 RetRegs.push_back(VA.getLocReg());
1072 // The x86-64 ABI for returning structs by value requires that we copy
1073 // the sret argument into %rax for the return. We saved the argument into
1074 // a virtual register in the entry block, so now we copy the value out
1075 // and into %rax. We also do the same with %eax for Win32.
1076 if (F.hasStructRetAttr() &&
1077 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1078 unsigned Reg = X86MFInfo->getSRetReturnReg();
1080 "SRetReturnReg should have been set in LowerFormalArguments()!");
1081 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1083 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1084 RetRegs.push_back(RetReg);
1087 // Now emit the RET.
1088 MachineInstrBuilder MIB =
1089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1090 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1091 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1092 MIB.addReg(RetRegs[i], RegState::Implicit);
1096 /// X86SelectLoad - Select and emit code to implement load instructions.
1098 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1099 const LoadInst *LI = cast<LoadInst>(I);
1101 // Atomic loads need special handling.
1106 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1109 const Value *Ptr = LI->getPointerOperand();
1112 if (!X86SelectAddress(Ptr, AM))
1115 unsigned Alignment = LI->getAlignment();
1116 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1117 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1118 Alignment = ABIAlignment;
1120 unsigned ResultReg = 0;
1121 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1125 updateValueMap(I, ResultReg);
1129 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1130 bool HasAVX = Subtarget->hasAVX();
1131 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1132 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1134 switch (VT.getSimpleVT().SimpleTy) {
1136 case MVT::i8: return X86::CMP8rr;
1137 case MVT::i16: return X86::CMP16rr;
1138 case MVT::i32: return X86::CMP32rr;
1139 case MVT::i64: return X86::CMP64rr;
1141 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1143 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1147 /// If we have a comparison with RHS as the RHS of the comparison, return an
1148 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1149 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1150 int64_t Val = RHSC->getSExtValue();
1151 switch (VT.getSimpleVT().SimpleTy) {
1152 // Otherwise, we can't fold the immediate into this comparison.
1159 return X86::CMP16ri8;
1160 return X86::CMP16ri;
1163 return X86::CMP32ri8;
1164 return X86::CMP32ri;
1167 return X86::CMP64ri8;
1168 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1171 return X86::CMP64ri32;
1176 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1177 EVT VT, DebugLoc CurDbgLoc) {
1178 unsigned Op0Reg = getRegForValue(Op0);
1179 if (Op0Reg == 0) return false;
1181 // Handle 'null' like i32/i64 0.
1182 if (isa<ConstantPointerNull>(Op1))
1183 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1185 // We have two options: compare with register or immediate. If the RHS of
1186 // the compare is an immediate that we can fold into this compare, use
1187 // CMPri, otherwise use CMPrr.
1188 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1189 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1192 .addImm(Op1C->getSExtValue());
1197 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1198 if (CompareOpc == 0) return false;
1200 unsigned Op1Reg = getRegForValue(Op1);
1201 if (Op1Reg == 0) return false;
1202 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1209 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1210 const CmpInst *CI = cast<CmpInst>(I);
1213 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1216 // Try to optimize or fold the cmp.
1217 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1218 unsigned ResultReg = 0;
1219 switch (Predicate) {
1221 case CmpInst::FCMP_FALSE: {
1222 ResultReg = createResultReg(&X86::GR32RegClass);
1223 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1225 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1231 case CmpInst::FCMP_TRUE: {
1232 ResultReg = createResultReg(&X86::GR8RegClass);
1233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1234 ResultReg).addImm(1);
1240 updateValueMap(I, ResultReg);
1244 const Value *LHS = CI->getOperand(0);
1245 const Value *RHS = CI->getOperand(1);
1247 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1248 // We don't have to materialize a zero constant for this case and can just use
1249 // %x again on the RHS.
1250 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1251 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1252 if (RHSC && RHSC->isNullValue())
1256 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1257 static unsigned SETFOpcTable[2][3] = {
1258 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1259 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1261 unsigned *SETFOpc = nullptr;
1262 switch (Predicate) {
1264 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1265 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1268 ResultReg = createResultReg(&X86::GR8RegClass);
1270 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1273 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1274 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1280 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1281 updateValueMap(I, ResultReg);
1287 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1288 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1289 unsigned Opc = X86::getSETFromCond(CC);
1292 std::swap(LHS, RHS);
1294 // Emit a compare of LHS/RHS.
1295 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1299 updateValueMap(I, ResultReg);
1303 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1304 EVT DstVT = TLI.getValueType(DL, I->getType());
1305 if (!TLI.isTypeLegal(DstVT))
1308 unsigned ResultReg = getRegForValue(I->getOperand(0));
1312 // Handle zero-extension from i1 to i8, which is common.
1313 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1314 if (SrcVT.SimpleTy == MVT::i1) {
1315 // Set the high bits to zero.
1316 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1323 if (DstVT == MVT::i64) {
1324 // Handle extension to 64-bits via sub-register shenanigans.
1327 switch (SrcVT.SimpleTy) {
1328 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1329 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1330 case MVT::i32: MovInst = X86::MOV32rr; break;
1331 default: llvm_unreachable("Unexpected zext to i64 source type");
1334 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1338 ResultReg = createResultReg(&X86::GR64RegClass);
1339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1341 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1342 } else if (DstVT != MVT::i8) {
1343 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1344 ResultReg, /*Kill=*/true);
1349 updateValueMap(I, ResultReg);
1353 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1354 // Unconditional branches are selected by tablegen-generated code.
1355 // Handle a conditional branch.
1356 const BranchInst *BI = cast<BranchInst>(I);
1357 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1358 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1360 // Fold the common case of a conditional branch with a comparison
1361 // in the same block (values defined on other blocks may not have
1362 // initialized registers).
1364 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1365 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1366 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1368 // Try to optimize or fold the cmp.
1369 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1370 switch (Predicate) {
1372 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1373 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1376 const Value *CmpLHS = CI->getOperand(0);
1377 const Value *CmpRHS = CI->getOperand(1);
1379 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1381 // We don't have to materialize a zero constant for this case and can just
1382 // use %x again on the RHS.
1383 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1384 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1385 if (CmpRHSC && CmpRHSC->isNullValue())
1389 // Try to take advantage of fallthrough opportunities.
1390 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1391 std::swap(TrueMBB, FalseMBB);
1392 Predicate = CmpInst::getInversePredicate(Predicate);
1395 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1396 // code check. Instead two branch instructions are required to check all
1397 // the flags. First we change the predicate to a supported condition code,
1398 // which will be the first branch. Later one we will emit the second
1400 bool NeedExtraBranch = false;
1401 switch (Predicate) {
1403 case CmpInst::FCMP_OEQ:
1404 std::swap(TrueMBB, FalseMBB); // fall-through
1405 case CmpInst::FCMP_UNE:
1406 NeedExtraBranch = true;
1407 Predicate = CmpInst::FCMP_ONE;
1413 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1414 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1416 BranchOpc = X86::GetCondBranchFromCond(CC);
1418 std::swap(CmpLHS, CmpRHS);
1420 // Emit a compare of the LHS and RHS, setting the flags.
1421 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1427 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1429 if (NeedExtraBranch) {
1430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1434 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1437 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1438 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1439 // typically happen for _Bool and C++ bools.
1441 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1442 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1443 unsigned TestOpc = 0;
1444 switch (SourceVT.SimpleTy) {
1446 case MVT::i8: TestOpc = X86::TEST8ri; break;
1447 case MVT::i16: TestOpc = X86::TEST16ri; break;
1448 case MVT::i32: TestOpc = X86::TEST32ri; break;
1449 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1452 unsigned OpReg = getRegForValue(TI->getOperand(0));
1453 if (OpReg == 0) return false;
1454 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1455 .addReg(OpReg).addImm(1);
1457 unsigned JmpOpc = X86::JNE_1;
1458 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1459 std::swap(TrueMBB, FalseMBB);
1463 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1466 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1470 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1471 // Fake request the condition, otherwise the intrinsic might be completely
1473 unsigned TmpReg = getRegForValue(BI->getCondition());
1477 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1481 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1485 // Otherwise do a clumsy setcc and re-test it.
1486 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1487 // in an explicit cast, so make sure to handle that correctly.
1488 unsigned OpReg = getRegForValue(BI->getCondition());
1489 if (OpReg == 0) return false;
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1492 .addReg(OpReg).addImm(1);
1493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1495 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1499 bool X86FastISel::X86SelectShift(const Instruction *I) {
1500 unsigned CReg = 0, OpReg = 0;
1501 const TargetRegisterClass *RC = nullptr;
1502 if (I->getType()->isIntegerTy(8)) {
1504 RC = &X86::GR8RegClass;
1505 switch (I->getOpcode()) {
1506 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1507 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1508 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1509 default: return false;
1511 } else if (I->getType()->isIntegerTy(16)) {
1513 RC = &X86::GR16RegClass;
1514 switch (I->getOpcode()) {
1515 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1516 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1517 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1518 default: return false;
1520 } else if (I->getType()->isIntegerTy(32)) {
1522 RC = &X86::GR32RegClass;
1523 switch (I->getOpcode()) {
1524 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1525 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1526 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1527 default: return false;
1529 } else if (I->getType()->isIntegerTy(64)) {
1531 RC = &X86::GR64RegClass;
1532 switch (I->getOpcode()) {
1533 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1534 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1535 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1536 default: return false;
1543 if (!isTypeLegal(I->getType(), VT))
1546 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1547 if (Op0Reg == 0) return false;
1549 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1550 if (Op1Reg == 0) return false;
1551 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1552 CReg).addReg(Op1Reg);
1554 // The shift instruction uses X86::CL. If we defined a super-register
1555 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1556 if (CReg != X86::CL)
1557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1558 TII.get(TargetOpcode::KILL), X86::CL)
1559 .addReg(CReg, RegState::Kill);
1561 unsigned ResultReg = createResultReg(RC);
1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1564 updateValueMap(I, ResultReg);
1568 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1569 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1570 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1571 const static bool S = true; // IsSigned
1572 const static bool U = false; // !IsSigned
1573 const static unsigned Copy = TargetOpcode::COPY;
1574 // For the X86 DIV/IDIV instruction, in most cases the dividend
1575 // (numerator) must be in a specific register pair highreg:lowreg,
1576 // producing the quotient in lowreg and the remainder in highreg.
1577 // For most data types, to set up the instruction, the dividend is
1578 // copied into lowreg, and lowreg is sign-extended or zero-extended
1579 // into highreg. The exception is i8, where the dividend is defined
1580 // as a single register rather than a register pair, and we
1581 // therefore directly sign-extend or zero-extend the dividend into
1582 // lowreg, instead of copying, and ignore the highreg.
1583 const static struct DivRemEntry {
1584 // The following portion depends only on the data type.
1585 const TargetRegisterClass *RC;
1586 unsigned LowInReg; // low part of the register pair
1587 unsigned HighInReg; // high part of the register pair
1588 // The following portion depends on both the data type and the operation.
1589 struct DivRemResult {
1590 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1591 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1592 // highreg, or copying a zero into highreg.
1593 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1594 // zero/sign-extending into lowreg for i8.
1595 unsigned DivRemResultReg; // Register containing the desired result.
1596 bool IsOpSigned; // Whether to use signed or unsigned form.
1597 } ResultTable[NumOps];
1598 } OpTable[NumTypes] = {
1599 { &X86::GR8RegClass, X86::AX, 0, {
1600 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1601 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1602 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1603 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1606 { &X86::GR16RegClass, X86::AX, X86::DX, {
1607 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1608 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1609 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1610 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1613 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1614 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1615 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1616 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1617 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1620 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1621 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1622 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1623 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1624 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1630 if (!isTypeLegal(I->getType(), VT))
1633 unsigned TypeIndex, OpIndex;
1634 switch (VT.SimpleTy) {
1635 default: return false;
1636 case MVT::i8: TypeIndex = 0; break;
1637 case MVT::i16: TypeIndex = 1; break;
1638 case MVT::i32: TypeIndex = 2; break;
1639 case MVT::i64: TypeIndex = 3;
1640 if (!Subtarget->is64Bit())
1645 switch (I->getOpcode()) {
1646 default: llvm_unreachable("Unexpected div/rem opcode");
1647 case Instruction::SDiv: OpIndex = 0; break;
1648 case Instruction::SRem: OpIndex = 1; break;
1649 case Instruction::UDiv: OpIndex = 2; break;
1650 case Instruction::URem: OpIndex = 3; break;
1653 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1654 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1655 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1658 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1662 // Move op0 into low-order input register.
1663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1664 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1665 // Zero-extend or sign-extend into high-order input register.
1666 if (OpEntry.OpSignExtend) {
1667 if (OpEntry.IsOpSigned)
1668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1669 TII.get(OpEntry.OpSignExtend));
1671 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1673 TII.get(X86::MOV32r0), Zero32);
1675 // Copy the zero into the appropriate sub/super/identical physical
1676 // register. Unfortunately the operations needed are not uniform enough
1677 // to fit neatly into the table above.
1678 if (VT.SimpleTy == MVT::i16) {
1679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1680 TII.get(Copy), TypeEntry.HighInReg)
1681 .addReg(Zero32, 0, X86::sub_16bit);
1682 } else if (VT.SimpleTy == MVT::i32) {
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1684 TII.get(Copy), TypeEntry.HighInReg)
1686 } else if (VT.SimpleTy == MVT::i64) {
1687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1688 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1689 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1693 // Generate the DIV/IDIV instruction.
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1695 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1696 // For i8 remainder, we can't reference AH directly, as we'll end
1697 // up with bogus copies like %R9B = COPY %AH. Reference AX
1698 // instead to prevent AH references in a REX instruction.
1700 // The current assumption of the fast register allocator is that isel
1701 // won't generate explicit references to the GPR8_NOREX registers. If
1702 // the allocator and/or the backend get enhanced to be more robust in
1703 // that regard, this can be, and should be, removed.
1704 unsigned ResultReg = 0;
1705 if ((I->getOpcode() == Instruction::SRem ||
1706 I->getOpcode() == Instruction::URem) &&
1707 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1708 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1709 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1711 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1713 // Shift AX right by 8 bits instead of using AH.
1714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1715 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1717 // Now reference the 8-bit subreg of the result.
1718 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1719 /*Kill=*/true, X86::sub_8bit);
1721 // Copy the result out of the physreg if we haven't already.
1723 ResultReg = createResultReg(TypeEntry.RC);
1724 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1725 .addReg(OpEntry.DivRemResultReg);
1727 updateValueMap(I, ResultReg);
1732 /// \brief Emit a conditional move instruction (if the are supported) to lower
1734 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1735 // Check if the subtarget supports these instructions.
1736 if (!Subtarget->hasCMov())
1739 // FIXME: Add support for i8.
1740 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1743 const Value *Cond = I->getOperand(0);
1744 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1745 bool NeedTest = true;
1746 X86::CondCode CC = X86::COND_NE;
1748 // Optimize conditions coming from a compare if both instructions are in the
1749 // same basic block (values defined in other basic blocks may not have
1750 // initialized registers).
1751 const auto *CI = dyn_cast<CmpInst>(Cond);
1752 if (CI && (CI->getParent() == I->getParent())) {
1753 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1755 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1756 static unsigned SETFOpcTable[2][3] = {
1757 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1758 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1760 unsigned *SETFOpc = nullptr;
1761 switch (Predicate) {
1763 case CmpInst::FCMP_OEQ:
1764 SETFOpc = &SETFOpcTable[0][0];
1765 Predicate = CmpInst::ICMP_NE;
1767 case CmpInst::FCMP_UNE:
1768 SETFOpc = &SETFOpcTable[1][0];
1769 Predicate = CmpInst::ICMP_NE;
1774 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1775 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1777 const Value *CmpLHS = CI->getOperand(0);
1778 const Value *CmpRHS = CI->getOperand(1);
1780 std::swap(CmpLHS, CmpRHS);
1782 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
1783 // Emit a compare of the LHS and RHS, setting the flags.
1784 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1788 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1789 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1794 auto const &II = TII.get(SETFOpc[2]);
1795 if (II.getNumDefs()) {
1796 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1798 .addReg(FlagReg2).addReg(FlagReg1);
1800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1801 .addReg(FlagReg2).addReg(FlagReg1);
1805 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1806 // Fake request the condition, otherwise the intrinsic might be completely
1808 unsigned TmpReg = getRegForValue(Cond);
1816 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1817 // garbage. Indeed, only the less significant bit is supposed to be
1818 // accurate. If we read more than the lsb, we may see non-zero values
1819 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1820 // the select. This is achieved by performing TEST against 1.
1821 unsigned CondReg = getRegForValue(Cond);
1824 bool CondIsKill = hasTrivialKill(Cond);
1826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1827 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1830 const Value *LHS = I->getOperand(1);
1831 const Value *RHS = I->getOperand(2);
1833 unsigned RHSReg = getRegForValue(RHS);
1834 bool RHSIsKill = hasTrivialKill(RHS);
1836 unsigned LHSReg = getRegForValue(LHS);
1837 bool LHSIsKill = hasTrivialKill(LHS);
1839 if (!LHSReg || !RHSReg)
1842 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1843 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1845 updateValueMap(I, ResultReg);
1849 /// \brief Emit SSE or AVX instructions to lower the select.
1851 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1852 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1853 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1854 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1855 // Optimize conditions coming from a compare if both instructions are in the
1856 // same basic block (values defined in other basic blocks may not have
1857 // initialized registers).
1858 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1859 if (!CI || (CI->getParent() != I->getParent()))
1862 if (I->getType() != CI->getOperand(0)->getType() ||
1863 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1864 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1867 const Value *CmpLHS = CI->getOperand(0);
1868 const Value *CmpRHS = CI->getOperand(1);
1869 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1871 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1872 // We don't have to materialize a zero constant for this case and can just use
1873 // %x again on the RHS.
1874 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1875 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1876 if (CmpRHSC && CmpRHSC->isNullValue())
1882 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1887 std::swap(CmpLHS, CmpRHS);
1889 // Choose the SSE instruction sequence based on data type (float or double).
1890 static unsigned OpcTable[2][4] = {
1891 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1892 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1895 unsigned *Opc = nullptr;
1896 switch (RetVT.SimpleTy) {
1897 default: return false;
1898 case MVT::f32: Opc = &OpcTable[0][0]; break;
1899 case MVT::f64: Opc = &OpcTable[1][0]; break;
1902 const Value *LHS = I->getOperand(1);
1903 const Value *RHS = I->getOperand(2);
1905 unsigned LHSReg = getRegForValue(LHS);
1906 bool LHSIsKill = hasTrivialKill(LHS);
1908 unsigned RHSReg = getRegForValue(RHS);
1909 bool RHSIsKill = hasTrivialKill(RHS);
1911 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1912 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1914 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1915 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1917 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1920 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1923 if (Subtarget->hasAVX()) {
1924 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
1925 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
1927 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1928 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1929 // uses XMM0 as the selection register. That may need just as many
1930 // instructions as the AND/ANDN/OR sequence due to register moves, so
1932 unsigned CmpOpcode =
1933 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1934 unsigned BlendOpcode =
1935 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1937 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
1938 CmpRHSReg, CmpRHSIsKill, CC);
1939 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
1940 LHSReg, LHSIsKill, CmpReg, true);
1941 ResultReg = createResultReg(RC);
1942 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1943 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
1945 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1946 CmpRHSReg, CmpRHSIsKill, CC);
1947 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1949 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1951 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1952 AndReg, /*IsKill=*/true);
1954 updateValueMap(I, ResultReg);
1958 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1959 // These are pseudo CMOV instructions and will be later expanded into control-
1962 switch (RetVT.SimpleTy) {
1963 default: return false;
1964 case MVT::i8: Opc = X86::CMOV_GR8; break;
1965 case MVT::i16: Opc = X86::CMOV_GR16; break;
1966 case MVT::i32: Opc = X86::CMOV_GR32; break;
1967 case MVT::f32: Opc = X86::CMOV_FR32; break;
1968 case MVT::f64: Opc = X86::CMOV_FR64; break;
1971 const Value *Cond = I->getOperand(0);
1972 X86::CondCode CC = X86::COND_NE;
1974 // Optimize conditions coming from a compare if both instructions are in the
1975 // same basic block (values defined in other basic blocks may not have
1976 // initialized registers).
1977 const auto *CI = dyn_cast<CmpInst>(Cond);
1978 if (CI && (CI->getParent() == I->getParent())) {
1980 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1981 if (CC > X86::LAST_VALID_COND)
1984 const Value *CmpLHS = CI->getOperand(0);
1985 const Value *CmpRHS = CI->getOperand(1);
1988 std::swap(CmpLHS, CmpRHS);
1990 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
1991 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1994 unsigned CondReg = getRegForValue(Cond);
1997 bool CondIsKill = hasTrivialKill(Cond);
1998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1999 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2002 const Value *LHS = I->getOperand(1);
2003 const Value *RHS = I->getOperand(2);
2005 unsigned LHSReg = getRegForValue(LHS);
2006 bool LHSIsKill = hasTrivialKill(LHS);
2008 unsigned RHSReg = getRegForValue(RHS);
2009 bool RHSIsKill = hasTrivialKill(RHS);
2011 if (!LHSReg || !RHSReg)
2014 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2016 unsigned ResultReg =
2017 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2018 updateValueMap(I, ResultReg);
2022 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2024 if (!isTypeLegal(I->getType(), RetVT))
2027 // Check if we can fold the select.
2028 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2029 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2030 const Value *Opnd = nullptr;
2031 switch (Predicate) {
2033 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2034 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2036 // No need for a select anymore - this is an unconditional move.
2038 unsigned OpReg = getRegForValue(Opnd);
2041 bool OpIsKill = hasTrivialKill(Opnd);
2042 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2043 unsigned ResultReg = createResultReg(RC);
2044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2045 TII.get(TargetOpcode::COPY), ResultReg)
2046 .addReg(OpReg, getKillRegState(OpIsKill));
2047 updateValueMap(I, ResultReg);
2052 // First try to use real conditional move instructions.
2053 if (X86FastEmitCMoveSelect(RetVT, I))
2056 // Try to use a sequence of SSE instructions to simulate a conditional move.
2057 if (X86FastEmitSSESelect(RetVT, I))
2060 // Fall-back to pseudo conditional move instructions, which will be later
2061 // converted to control-flow.
2062 if (X86FastEmitPseudoSelect(RetVT, I))
2068 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2069 // The target-independent selection algorithm in FastISel already knows how
2070 // to select a SINT_TO_FP if the target is SSE but not AVX.
2071 // Early exit if the subtarget doesn't have AVX.
2072 if (!Subtarget->hasAVX())
2075 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2078 // Select integer to float/double conversion.
2079 unsigned OpReg = getRegForValue(I->getOperand(0));
2083 const TargetRegisterClass *RC = nullptr;
2086 if (I->getType()->isDoubleTy()) {
2087 // sitofp int -> double
2088 Opcode = X86::VCVTSI2SDrr;
2089 RC = &X86::FR64RegClass;
2090 } else if (I->getType()->isFloatTy()) {
2091 // sitofp int -> float
2092 Opcode = X86::VCVTSI2SSrr;
2093 RC = &X86::FR32RegClass;
2097 unsigned ImplicitDefReg = createResultReg(RC);
2098 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2099 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2100 unsigned ResultReg =
2101 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2102 updateValueMap(I, ResultReg);
2106 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2107 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2109 const TargetRegisterClass *RC) {
2110 assert((I->getOpcode() == Instruction::FPExt ||
2111 I->getOpcode() == Instruction::FPTrunc) &&
2112 "Instruction must be an FPExt or FPTrunc!");
2114 unsigned OpReg = getRegForValue(I->getOperand(0));
2118 unsigned ResultReg = createResultReg(RC);
2119 MachineInstrBuilder MIB;
2120 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2122 if (Subtarget->hasAVX())
2125 updateValueMap(I, ResultReg);
2129 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2130 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2131 I->getOperand(0)->getType()->isFloatTy()) {
2132 // fpext from float to double.
2133 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2134 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2140 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2141 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2142 I->getOperand(0)->getType()->isDoubleTy()) {
2143 // fptrunc from double to float.
2144 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2145 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2151 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2152 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2153 EVT DstVT = TLI.getValueType(DL, I->getType());
2155 // This code only handles truncation to byte.
2156 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2158 if (!TLI.isTypeLegal(SrcVT))
2161 unsigned InputReg = getRegForValue(I->getOperand(0));
2163 // Unhandled operand. Halt "fast" selection and bail.
2166 if (SrcVT == MVT::i8) {
2167 // Truncate from i8 to i1; no code needed.
2168 updateValueMap(I, InputReg);
2172 bool KillInputReg = false;
2173 if (!Subtarget->is64Bit()) {
2174 // If we're on x86-32; we can't extract an i8 from a general register.
2175 // First issue a copy to GR16_ABCD or GR32_ABCD.
2176 const TargetRegisterClass *CopyRC =
2177 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2178 unsigned CopyReg = createResultReg(CopyRC);
2179 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2180 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2182 KillInputReg = true;
2185 // Issue an extract_subreg.
2186 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2187 InputReg, KillInputReg,
2192 updateValueMap(I, ResultReg);
2196 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2197 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2200 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2201 X86AddressMode SrcAM, uint64_t Len) {
2203 // Make sure we don't bloat code by inlining very large memcpy's.
2204 if (!IsMemcpySmall(Len))
2207 bool i64Legal = Subtarget->is64Bit();
2209 // We don't care about alignment here since we just emit integer accesses.
2212 if (Len >= 8 && i64Legal)
2222 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2223 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2224 assert(RV && "Failed to emit load or store??");
2226 unsigned Size = VT.getSizeInBits()/8;
2228 DestAM.Disp += Size;
2235 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2236 // FIXME: Handle more intrinsics.
2237 switch (II->getIntrinsicID()) {
2238 default: return false;
2239 case Intrinsic::convert_from_fp16:
2240 case Intrinsic::convert_to_fp16: {
2241 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2244 const Value *Op = II->getArgOperand(0);
2245 unsigned InputReg = getRegForValue(Op);
2249 // F16C only allows converting from float to half and from half to float.
2250 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2251 if (IsFloatToHalf) {
2252 if (!Op->getType()->isFloatTy())
2255 if (!II->getType()->isFloatTy())
2259 unsigned ResultReg = 0;
2260 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2261 if (IsFloatToHalf) {
2262 // 'InputReg' is implicitly promoted from register class FR32 to
2263 // register class VR128 by method 'constrainOperandRegClass' which is
2264 // directly called by 'fastEmitInst_ri'.
2265 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2266 // used to provide rounding control.
2267 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2269 // Move the lower 32-bits of ResultReg to another register of class GR32.
2270 ResultReg = createResultReg(&X86::GR32RegClass);
2271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2272 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2273 .addReg(InputReg, RegState::Kill);
2275 // The result value is in the lower 16-bits of ResultReg.
2276 unsigned RegIdx = X86::sub_16bit;
2277 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2279 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2280 // Explicitly sign-extend the input to 32-bit.
2281 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2284 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2285 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2286 InputReg, /*Kill=*/true);
2288 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2290 // The result value is in the lower 32-bits of ResultReg.
2291 // Emit an explicit copy from register class VR128 to register class FR32.
2292 ResultReg = createResultReg(&X86::FR32RegClass);
2293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2294 TII.get(TargetOpcode::COPY), ResultReg)
2295 .addReg(InputReg, RegState::Kill);
2298 updateValueMap(II, ResultReg);
2301 case Intrinsic::frameaddress: {
2302 MachineFunction *MF = FuncInfo.MF;
2303 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2306 Type *RetTy = II->getCalledFunction()->getReturnType();
2309 if (!isTypeLegal(RetTy, VT))
2313 const TargetRegisterClass *RC = nullptr;
2315 switch (VT.SimpleTy) {
2316 default: llvm_unreachable("Invalid result type for frameaddress.");
2317 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2318 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2321 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2322 // we get the wrong frame register.
2323 MachineFrameInfo *MFI = MF->getFrameInfo();
2324 MFI->setFrameAddressIsTaken(true);
2326 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2327 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2328 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2329 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2330 "Invalid Frame Register!");
2332 // Always make a copy of the frame register to to a vreg first, so that we
2333 // never directly reference the frame register (the TwoAddressInstruction-
2334 // Pass doesn't like that).
2335 unsigned SrcReg = createResultReg(RC);
2336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2337 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2339 // Now recursively load from the frame address.
2340 // movq (%rbp), %rax
2341 // movq (%rax), %rax
2342 // movq (%rax), %rax
2345 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2347 DestReg = createResultReg(RC);
2348 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2349 TII.get(Opc), DestReg), SrcReg);
2353 updateValueMap(II, SrcReg);
2356 case Intrinsic::memcpy: {
2357 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2358 // Don't handle volatile or variable length memcpys.
2359 if (MCI->isVolatile())
2362 if (isa<ConstantInt>(MCI->getLength())) {
2363 // Small memcpy's are common enough that we want to do them
2364 // without a call if possible.
2365 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2366 if (IsMemcpySmall(Len)) {
2367 X86AddressMode DestAM, SrcAM;
2368 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2369 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2371 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2376 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2377 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2380 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2383 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2385 case Intrinsic::memset: {
2386 const MemSetInst *MSI = cast<MemSetInst>(II);
2388 if (MSI->isVolatile())
2391 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2392 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2395 if (MSI->getDestAddressSpace() > 255)
2398 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2400 case Intrinsic::stackprotector: {
2401 // Emit code to store the stack guard onto the stack.
2402 EVT PtrTy = TLI.getPointerTy(DL);
2404 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2405 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2407 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2409 // Grab the frame index.
2411 if (!X86SelectAddress(Slot, AM)) return false;
2412 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2415 case Intrinsic::dbg_declare: {
2416 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2418 assert(DI->getAddress() && "Null address should be checked earlier!");
2419 if (!X86SelectAddress(DI->getAddress(), AM))
2421 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2422 // FIXME may need to add RegState::Debug to any registers produced,
2423 // although ESP/EBP should be the only ones at the moment.
2424 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2425 "Expected inlined-at fields to agree");
2426 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2428 .addMetadata(DI->getVariable())
2429 .addMetadata(DI->getExpression());
2432 case Intrinsic::trap: {
2433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2436 case Intrinsic::sqrt: {
2437 if (!Subtarget->hasSSE1())
2440 Type *RetTy = II->getCalledFunction()->getReturnType();
2443 if (!isTypeLegal(RetTy, VT))
2446 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2447 // is not generated by FastISel yet.
2448 // FIXME: Update this code once tablegen can handle it.
2449 static const unsigned SqrtOpc[2][2] = {
2450 {X86::SQRTSSr, X86::VSQRTSSr},
2451 {X86::SQRTSDr, X86::VSQRTSDr}
2453 bool HasAVX = Subtarget->hasAVX();
2455 const TargetRegisterClass *RC;
2456 switch (VT.SimpleTy) {
2457 default: return false;
2458 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2459 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2462 const Value *SrcVal = II->getArgOperand(0);
2463 unsigned SrcReg = getRegForValue(SrcVal);
2468 unsigned ImplicitDefReg = 0;
2470 ImplicitDefReg = createResultReg(RC);
2471 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2472 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2475 unsigned ResultReg = createResultReg(RC);
2476 MachineInstrBuilder MIB;
2477 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2481 MIB.addReg(ImplicitDefReg);
2485 updateValueMap(II, ResultReg);
2488 case Intrinsic::sadd_with_overflow:
2489 case Intrinsic::uadd_with_overflow:
2490 case Intrinsic::ssub_with_overflow:
2491 case Intrinsic::usub_with_overflow:
2492 case Intrinsic::smul_with_overflow:
2493 case Intrinsic::umul_with_overflow: {
2494 // This implements the basic lowering of the xalu with overflow intrinsics
2495 // into add/sub/mul followed by either seto or setb.
2496 const Function *Callee = II->getCalledFunction();
2497 auto *Ty = cast<StructType>(Callee->getReturnType());
2498 Type *RetTy = Ty->getTypeAtIndex(0U);
2499 Type *CondTy = Ty->getTypeAtIndex(1);
2502 if (!isTypeLegal(RetTy, VT))
2505 if (VT < MVT::i8 || VT > MVT::i64)
2508 const Value *LHS = II->getArgOperand(0);
2509 const Value *RHS = II->getArgOperand(1);
2511 // Canonicalize immediate to the RHS.
2512 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2513 isCommutativeIntrinsic(II))
2514 std::swap(LHS, RHS);
2516 bool UseIncDec = false;
2517 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2520 unsigned BaseOpc, CondOpc;
2521 switch (II->getIntrinsicID()) {
2522 default: llvm_unreachable("Unexpected intrinsic!");
2523 case Intrinsic::sadd_with_overflow:
2524 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2525 CondOpc = X86::SETOr;
2527 case Intrinsic::uadd_with_overflow:
2528 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2529 case Intrinsic::ssub_with_overflow:
2530 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2531 CondOpc = X86::SETOr;
2533 case Intrinsic::usub_with_overflow:
2534 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2535 case Intrinsic::smul_with_overflow:
2536 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2537 case Intrinsic::umul_with_overflow:
2538 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2541 unsigned LHSReg = getRegForValue(LHS);
2544 bool LHSIsKill = hasTrivialKill(LHS);
2546 unsigned ResultReg = 0;
2547 // Check if we have an immediate version.
2548 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2549 static const unsigned Opc[2][4] = {
2550 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2551 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2554 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2555 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2556 bool IsDec = BaseOpc == X86ISD::DEC;
2557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2558 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2559 .addReg(LHSReg, getKillRegState(LHSIsKill));
2561 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2562 CI->getZExtValue());
2568 RHSReg = getRegForValue(RHS);
2571 RHSIsKill = hasTrivialKill(RHS);
2572 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2576 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2578 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2579 static const unsigned MULOpc[] =
2580 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2581 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2582 // First copy the first operand into RAX, which is an implicit input to
2583 // the X86::MUL*r instruction.
2584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2585 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2586 .addReg(LHSReg, getKillRegState(LHSIsKill));
2587 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2588 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2589 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2590 static const unsigned MULOpc[] =
2591 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2592 if (VT == MVT::i8) {
2593 // Copy the first operand into AL, which is an implicit input to the
2594 // X86::IMUL8r instruction.
2595 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2596 TII.get(TargetOpcode::COPY), X86::AL)
2597 .addReg(LHSReg, getKillRegState(LHSIsKill));
2598 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2601 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2602 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2609 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2610 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2611 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2614 updateValueMap(II, ResultReg, 2);
2617 case Intrinsic::x86_sse_cvttss2si:
2618 case Intrinsic::x86_sse_cvttss2si64:
2619 case Intrinsic::x86_sse2_cvttsd2si:
2620 case Intrinsic::x86_sse2_cvttsd2si64: {
2622 switch (II->getIntrinsicID()) {
2623 default: llvm_unreachable("Unexpected intrinsic.");
2624 case Intrinsic::x86_sse_cvttss2si:
2625 case Intrinsic::x86_sse_cvttss2si64:
2626 if (!Subtarget->hasSSE1())
2628 IsInputDouble = false;
2630 case Intrinsic::x86_sse2_cvttsd2si:
2631 case Intrinsic::x86_sse2_cvttsd2si64:
2632 if (!Subtarget->hasSSE2())
2634 IsInputDouble = true;
2638 Type *RetTy = II->getCalledFunction()->getReturnType();
2640 if (!isTypeLegal(RetTy, VT))
2643 static const unsigned CvtOpc[2][2][2] = {
2644 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2645 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2646 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2647 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2649 bool HasAVX = Subtarget->hasAVX();
2651 switch (VT.SimpleTy) {
2652 default: llvm_unreachable("Unexpected result type.");
2653 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2654 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2657 // Check if we can fold insertelement instructions into the convert.
2658 const Value *Op = II->getArgOperand(0);
2659 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2660 const Value *Index = IE->getOperand(2);
2661 if (!isa<ConstantInt>(Index))
2663 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2666 Op = IE->getOperand(1);
2669 Op = IE->getOperand(0);
2672 unsigned Reg = getRegForValue(Op);
2676 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2680 updateValueMap(II, ResultReg);
2686 bool X86FastISel::fastLowerArguments() {
2687 if (!FuncInfo.CanLowerReturn)
2690 const Function *F = FuncInfo.Fn;
2694 CallingConv::ID CC = F->getCallingConv();
2695 if (CC != CallingConv::C)
2698 if (Subtarget->isCallingConvWin64(CC))
2701 if (!Subtarget->is64Bit())
2704 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2705 unsigned GPRCnt = 0;
2706 unsigned FPRCnt = 0;
2708 for (auto const &Arg : F->args()) {
2709 // The first argument is at index 1.
2711 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2712 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2713 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2714 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2717 Type *ArgTy = Arg.getType();
2718 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2721 EVT ArgVT = TLI.getValueType(DL, ArgTy);
2722 if (!ArgVT.isSimple()) return false;
2723 switch (ArgVT.getSimpleVT().SimpleTy) {
2724 default: return false;
2731 if (!Subtarget->hasSSE1())
2744 static const MCPhysReg GPR32ArgRegs[] = {
2745 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2747 static const MCPhysReg GPR64ArgRegs[] = {
2748 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2750 static const MCPhysReg XMMArgRegs[] = {
2751 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2752 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2755 unsigned GPRIdx = 0;
2756 unsigned FPRIdx = 0;
2757 for (auto const &Arg : F->args()) {
2758 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
2759 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2761 switch (VT.SimpleTy) {
2762 default: llvm_unreachable("Unexpected value type.");
2763 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2764 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2765 case MVT::f32: // fall-through
2766 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2768 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2769 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2770 // Without this, EmitLiveInCopies may eliminate the livein if its only
2771 // use is a bitcast (which isn't turned into an instruction).
2772 unsigned ResultReg = createResultReg(RC);
2773 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2774 TII.get(TargetOpcode::COPY), ResultReg)
2775 .addReg(DstReg, getKillRegState(true));
2776 updateValueMap(&Arg, ResultReg);
2781 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2783 ImmutableCallSite *CS) {
2784 if (Subtarget->is64Bit())
2786 if (Subtarget->getTargetTriple().isOSMSVCRT())
2788 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2789 CC == CallingConv::HiPE)
2791 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2793 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2798 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2799 auto &OutVals = CLI.OutVals;
2800 auto &OutFlags = CLI.OutFlags;
2801 auto &OutRegs = CLI.OutRegs;
2802 auto &Ins = CLI.Ins;
2803 auto &InRegs = CLI.InRegs;
2804 CallingConv::ID CC = CLI.CallConv;
2805 bool &IsTailCall = CLI.IsTailCall;
2806 bool IsVarArg = CLI.IsVarArg;
2807 const Value *Callee = CLI.Callee;
2808 MCSymbol *Symbol = CLI.Symbol;
2810 bool Is64Bit = Subtarget->is64Bit();
2811 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2813 // Handle only C, fastcc, and webkit_js calling conventions for now.
2815 default: return false;
2816 case CallingConv::C:
2817 case CallingConv::Fast:
2818 case CallingConv::WebKit_JS:
2819 case CallingConv::X86_FastCall:
2820 case CallingConv::X86_64_Win64:
2821 case CallingConv::X86_64_SysV:
2825 // Allow SelectionDAG isel to handle tail calls.
2829 // fastcc with -tailcallopt is intended to provide a guaranteed
2830 // tail call optimization. Fastisel doesn't know how to do that.
2831 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2834 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2835 // x86-32. Special handling for x86-64 is implemented.
2836 if (IsVarArg && IsWin64)
2839 // Don't know about inalloca yet.
2840 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2843 // Fast-isel doesn't know about callee-pop yet.
2844 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2845 TM.Options.GuaranteedTailCallOpt))
2848 SmallVector<MVT, 16> OutVTs;
2849 SmallVector<unsigned, 16> ArgRegs;
2851 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2852 // instruction. This is safe because it is common to all FastISel supported
2853 // calling conventions on x86.
2854 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2855 Value *&Val = OutVals[i];
2856 ISD::ArgFlagsTy Flags = OutFlags[i];
2857 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2858 if (CI->getBitWidth() < 32) {
2860 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2862 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2866 // Passing bools around ends up doing a trunc to i1 and passing it.
2867 // Codegen this as an argument + "and 1".
2869 auto *TI = dyn_cast<TruncInst>(Val);
2871 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2872 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2874 Value *PrevVal = TI->getOperand(0);
2875 ResultReg = getRegForValue(PrevVal);
2880 if (!isTypeLegal(PrevVal->getType(), VT))
2884 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2886 if (!isTypeLegal(Val->getType(), VT))
2888 ResultReg = getRegForValue(Val);
2894 ArgRegs.push_back(ResultReg);
2895 OutVTs.push_back(VT);
2898 // Analyze operands of the call, assigning locations to each operand.
2899 SmallVector<CCValAssign, 16> ArgLocs;
2900 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2902 // Allocate shadow area for Win64
2904 CCInfo.AllocateStack(32, 8);
2906 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2908 // Get a count of how many bytes are to be pushed on the stack.
2909 unsigned NumBytes = CCInfo.getNextStackOffset();
2911 // Issue CALLSEQ_START
2912 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2914 .addImm(NumBytes).addImm(0);
2916 // Walk the register/memloc assignments, inserting copies/loads.
2917 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2918 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2919 CCValAssign const &VA = ArgLocs[i];
2920 const Value *ArgVal = OutVals[VA.getValNo()];
2921 MVT ArgVT = OutVTs[VA.getValNo()];
2923 if (ArgVT == MVT::x86mmx)
2926 unsigned ArgReg = ArgRegs[VA.getValNo()];
2928 // Promote the value if needed.
2929 switch (VA.getLocInfo()) {
2930 case CCValAssign::Full: break;
2931 case CCValAssign::SExt: {
2932 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2933 "Unexpected extend");
2934 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2936 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2937 ArgVT = VA.getLocVT();
2940 case CCValAssign::ZExt: {
2941 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2942 "Unexpected extend");
2943 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2945 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2946 ArgVT = VA.getLocVT();
2949 case CCValAssign::AExt: {
2950 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2951 "Unexpected extend");
2952 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2955 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2958 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2961 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2962 ArgVT = VA.getLocVT();
2965 case CCValAssign::BCvt: {
2966 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2967 /*TODO: Kill=*/false);
2968 assert(ArgReg && "Failed to emit a bitcast!");
2969 ArgVT = VA.getLocVT();
2972 case CCValAssign::VExt:
2973 // VExt has not been implemented, so this should be impossible to reach
2974 // for now. However, fallback to Selection DAG isel once implemented.
2976 case CCValAssign::AExtUpper:
2977 case CCValAssign::SExtUpper:
2978 case CCValAssign::ZExtUpper:
2979 case CCValAssign::FPExt:
2980 llvm_unreachable("Unexpected loc info!");
2981 case CCValAssign::Indirect:
2982 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2987 if (VA.isRegLoc()) {
2988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2989 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2990 OutRegs.push_back(VA.getLocReg());
2992 assert(VA.isMemLoc());
2994 // Don't emit stores for undef values.
2995 if (isa<UndefValue>(ArgVal))
2998 unsigned LocMemOffset = VA.getLocMemOffset();
3000 AM.Base.Reg = RegInfo->getStackRegister();
3001 AM.Disp = LocMemOffset;
3002 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3003 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3004 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3005 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3006 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3007 if (Flags.isByVal()) {
3008 X86AddressMode SrcAM;
3009 SrcAM.Base.Reg = ArgReg;
3010 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3012 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3013 // If this is a really simple value, emit this with the Value* version
3014 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3015 // as it can cause us to reevaluate the argument.
3016 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3019 bool ValIsKill = hasTrivialKill(ArgVal);
3020 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3026 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3028 if (Subtarget->isPICStyleGOT()) {
3029 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3031 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3034 if (Is64Bit && IsVarArg && !IsWin64) {
3035 // From AMD64 ABI document:
3036 // For calls that may call functions that use varargs or stdargs
3037 // (prototype-less calls or calls to functions containing ellipsis (...) in
3038 // the declaration) %al is used as hidden argument to specify the number
3039 // of SSE registers used. The contents of %al do not need to match exactly
3040 // the number of registers, but must be an ubound on the number of SSE
3041 // registers used and is in the range 0 - 8 inclusive.
3043 // Count the number of XMM registers allocated.
3044 static const MCPhysReg XMMArgRegs[] = {
3045 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3046 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3048 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3049 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3050 && "SSE registers cannot be used when SSE is disabled");
3051 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3052 X86::AL).addImm(NumXMMRegs);
3055 // Materialize callee address in a register. FIXME: GV address can be
3056 // handled with a CALLpcrel32 instead.
3057 X86AddressMode CalleeAM;
3058 if (!X86SelectCallAddress(Callee, CalleeAM))
3061 unsigned CalleeOp = 0;
3062 const GlobalValue *GV = nullptr;
3063 if (CalleeAM.GV != nullptr) {
3065 } else if (CalleeAM.Base.Reg != 0) {
3066 CalleeOp = CalleeAM.Base.Reg;
3071 MachineInstrBuilder MIB;
3073 // Register-indirect call.
3074 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3075 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3079 assert(GV && "Not a direct call");
3080 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3082 // See if we need any target-specific flags on the GV operand.
3083 unsigned char OpFlags = 0;
3085 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3086 // external symbols most go through the PLT in PIC mode. If the symbol
3087 // has hidden or protected visibility, or if it is static or local, then
3088 // we don't need to use the PLT - we can directly call it.
3089 if (Subtarget->isTargetELF() &&
3090 TM.getRelocationModel() == Reloc::PIC_ &&
3091 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3092 OpFlags = X86II::MO_PLT;
3093 } else if (Subtarget->isPICStyleStubAny() &&
3094 !GV->isStrongDefinitionForLinker() &&
3095 (!Subtarget->getTargetTriple().isMacOSX() ||
3096 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3097 // PC-relative references to external symbols should go through $stub,
3098 // unless we're building with the leopard linker or later, which
3099 // automatically synthesizes these stubs.
3100 OpFlags = X86II::MO_DARWIN_STUB;
3103 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3105 MIB.addSym(Symbol, OpFlags);
3107 MIB.addGlobalAddress(GV, 0, OpFlags);
3110 // Add a register mask operand representing the call-preserved registers.
3111 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3112 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3114 // Add an implicit use GOT pointer in EBX.
3115 if (Subtarget->isPICStyleGOT())
3116 MIB.addReg(X86::EBX, RegState::Implicit);
3118 if (Is64Bit && IsVarArg && !IsWin64)
3119 MIB.addReg(X86::AL, RegState::Implicit);
3121 // Add implicit physical register uses to the call.
3122 for (auto Reg : OutRegs)
3123 MIB.addReg(Reg, RegState::Implicit);
3125 // Issue CALLSEQ_END
3126 unsigned NumBytesForCalleeToPop =
3127 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3128 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3130 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3132 // Now handle call return values.
3133 SmallVector<CCValAssign, 16> RVLocs;
3134 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3135 CLI.RetTy->getContext());
3136 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3138 // Copy all of the result registers out of their specified physreg.
3139 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3140 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3141 CCValAssign &VA = RVLocs[i];
3142 EVT CopyVT = VA.getValVT();
3143 unsigned CopyReg = ResultReg + i;
3145 // If this is x86-64, and we disabled SSE, we can't return FP values
3146 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3147 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3148 report_fatal_error("SSE register return with SSE disabled");
3151 // If we prefer to use the value in xmm registers, copy it out as f80 and
3152 // use a truncate to move it from fp stack reg to xmm reg.
3153 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3154 isScalarFPTypeInSSEReg(VA.getValVT())) {
3156 CopyReg = createResultReg(&X86::RFP80RegClass);
3159 // Copy out the result.
3160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3161 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3162 InRegs.push_back(VA.getLocReg());
3164 // Round the f80 to the right size, which also moves it to the appropriate
3165 // xmm register. This is accomplished by storing the f80 value in memory
3166 // and then loading it back.
3167 if (CopyVT != VA.getValVT()) {
3168 EVT ResVT = VA.getValVT();
3169 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3170 unsigned MemSize = ResVT.getSizeInBits()/8;
3171 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3172 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3175 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3176 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3177 TII.get(Opc), ResultReg + i), FI);
3181 CLI.ResultReg = ResultReg;
3182 CLI.NumResultRegs = RVLocs.size();
3189 X86FastISel::fastSelectInstruction(const Instruction *I) {
3190 switch (I->getOpcode()) {
3192 case Instruction::Load:
3193 return X86SelectLoad(I);
3194 case Instruction::Store:
3195 return X86SelectStore(I);
3196 case Instruction::Ret:
3197 return X86SelectRet(I);
3198 case Instruction::ICmp:
3199 case Instruction::FCmp:
3200 return X86SelectCmp(I);
3201 case Instruction::ZExt:
3202 return X86SelectZExt(I);
3203 case Instruction::Br:
3204 return X86SelectBranch(I);
3205 case Instruction::LShr:
3206 case Instruction::AShr:
3207 case Instruction::Shl:
3208 return X86SelectShift(I);
3209 case Instruction::SDiv:
3210 case Instruction::UDiv:
3211 case Instruction::SRem:
3212 case Instruction::URem:
3213 return X86SelectDivRem(I);
3214 case Instruction::Select:
3215 return X86SelectSelect(I);
3216 case Instruction::Trunc:
3217 return X86SelectTrunc(I);
3218 case Instruction::FPExt:
3219 return X86SelectFPExt(I);
3220 case Instruction::FPTrunc:
3221 return X86SelectFPTrunc(I);
3222 case Instruction::SIToFP:
3223 return X86SelectSIToFP(I);
3224 case Instruction::IntToPtr: // Deliberate fall-through.
3225 case Instruction::PtrToInt: {
3226 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3227 EVT DstVT = TLI.getValueType(DL, I->getType());
3228 if (DstVT.bitsGT(SrcVT))
3229 return X86SelectZExt(I);
3230 if (DstVT.bitsLT(SrcVT))
3231 return X86SelectTrunc(I);
3232 unsigned Reg = getRegForValue(I->getOperand(0));
3233 if (Reg == 0) return false;
3234 updateValueMap(I, Reg);
3242 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3246 uint64_t Imm = CI->getZExtValue();
3248 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3249 switch (VT.SimpleTy) {
3250 default: llvm_unreachable("Unexpected value type");
3253 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3256 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3261 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3263 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3264 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3271 switch (VT.SimpleTy) {
3272 default: llvm_unreachable("Unexpected value type");
3273 case MVT::i1: VT = MVT::i8; // fall-through
3274 case MVT::i8: Opc = X86::MOV8ri; break;
3275 case MVT::i16: Opc = X86::MOV16ri; break;
3276 case MVT::i32: Opc = X86::MOV32ri; break;
3278 if (isUInt<32>(Imm))
3280 else if (isInt<32>(Imm))
3281 Opc = X86::MOV64ri32;
3287 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3288 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3289 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3290 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3291 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3292 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3295 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3298 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3299 if (CFP->isNullValue())
3300 return fastMaterializeFloatZero(CFP);
3302 // Can't handle alternate code models yet.
3303 CodeModel::Model CM = TM.getCodeModel();
3304 if (CM != CodeModel::Small && CM != CodeModel::Large)
3307 // Get opcode and regclass of the output for the given load instruction.
3309 const TargetRegisterClass *RC = nullptr;
3310 switch (VT.SimpleTy) {
3313 if (X86ScalarSSEf32) {
3314 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3315 RC = &X86::FR32RegClass;
3317 Opc = X86::LD_Fp32m;
3318 RC = &X86::RFP32RegClass;
3322 if (X86ScalarSSEf64) {
3323 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3324 RC = &X86::FR64RegClass;
3326 Opc = X86::LD_Fp64m;
3327 RC = &X86::RFP64RegClass;
3331 // No f80 support yet.
3335 // MachineConstantPool wants an explicit alignment.
3336 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3338 // Alignment of vector types. FIXME!
3339 Align = DL.getTypeAllocSize(CFP->getType());
3342 // x86-32 PIC requires a PIC base register for constant pools.
3343 unsigned PICBase = 0;
3344 unsigned char OpFlag = 0;
3345 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3346 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3347 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3348 } else if (Subtarget->isPICStyleGOT()) {
3349 OpFlag = X86II::MO_GOTOFF;
3350 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3351 } else if (Subtarget->isPICStyleRIPRel() &&
3352 TM.getCodeModel() == CodeModel::Small) {
3356 // Create the load from the constant pool.
3357 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3358 unsigned ResultReg = createResultReg(RC);
3360 if (CM == CodeModel::Large) {
3361 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3364 .addConstantPoolIndex(CPI, 0, OpFlag);
3365 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3366 TII.get(Opc), ResultReg);
3367 addDirectMem(MIB, AddrReg);
3368 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3369 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3370 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
3371 MIB->addMemOperand(*FuncInfo.MF, MMO);
3375 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3376 TII.get(Opc), ResultReg),
3377 CPI, PICBase, OpFlag);
3381 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3382 // Can't handle alternate code models yet.
3383 if (TM.getCodeModel() != CodeModel::Small)
3386 // Materialize addresses with LEA/MOV instructions.
3388 if (X86SelectAddress(GV, AM)) {
3389 // If the expression is just a basereg, then we're done, otherwise we need
3391 if (AM.BaseType == X86AddressMode::RegBase &&
3392 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3395 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3396 if (TM.getRelocationModel() == Reloc::Static &&
3397 TLI.getPointerTy(DL) == MVT::i64) {
3398 // The displacement code could be more than 32 bits away so we need to use
3399 // an instruction with a 64 bit immediate
3400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3402 .addGlobalAddress(GV);
3405 TLI.getPointerTy(DL) == MVT::i32
3406 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3408 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3409 TII.get(Opc), ResultReg), AM);
3416 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3417 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3419 // Only handle simple types.
3420 if (!CEVT.isSimple())
3422 MVT VT = CEVT.getSimpleVT();
3424 if (const auto *CI = dyn_cast<ConstantInt>(C))
3425 return X86MaterializeInt(CI, VT);
3426 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3427 return X86MaterializeFP(CFP, VT);
3428 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3429 return X86MaterializeGV(GV, VT);
3434 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3435 // Fail on dynamic allocas. At this point, getRegForValue has already
3436 // checked its CSE maps, so if we're here trying to handle a dynamic
3437 // alloca, we're not going to succeed. X86SelectAddress has a
3438 // check for dynamic allocas, because it's called directly from
3439 // various places, but targetMaterializeAlloca also needs a check
3440 // in order to avoid recursion between getRegForValue,
3441 // X86SelectAddrss, and targetMaterializeAlloca.
3442 if (!FuncInfo.StaticAllocaMap.count(C))
3444 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3447 if (!X86SelectAddress(C, AM))
3450 TLI.getPointerTy(DL) == MVT::i32
3451 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3453 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3454 unsigned ResultReg = createResultReg(RC);
3455 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3456 TII.get(Opc), ResultReg), AM);
3460 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3462 if (!isTypeLegal(CF->getType(), VT))
3465 // Get opcode and regclass for the given zero.
3467 const TargetRegisterClass *RC = nullptr;
3468 switch (VT.SimpleTy) {
3471 if (X86ScalarSSEf32) {
3472 Opc = X86::FsFLD0SS;
3473 RC = &X86::FR32RegClass;
3475 Opc = X86::LD_Fp032;
3476 RC = &X86::RFP32RegClass;
3480 if (X86ScalarSSEf64) {
3481 Opc = X86::FsFLD0SD;
3482 RC = &X86::FR64RegClass;
3484 Opc = X86::LD_Fp064;
3485 RC = &X86::RFP64RegClass;
3489 // No f80 support yet.
3493 unsigned ResultReg = createResultReg(RC);
3494 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3499 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3500 const LoadInst *LI) {
3501 const Value *Ptr = LI->getPointerOperand();
3503 if (!X86SelectAddress(Ptr, AM))
3506 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3508 unsigned Size = DL.getTypeAllocSize(LI->getType());
3509 unsigned Alignment = LI->getAlignment();
3511 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3512 Alignment = DL.getABITypeAlignment(LI->getType());
3514 SmallVector<MachineOperand, 8> AddrOps;
3515 AM.getFullAddress(AddrOps);
3517 MachineInstr *Result = XII.foldMemoryOperandImpl(
3518 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3519 /*AllowCommute=*/true);
3523 // The index register could be in the wrong register class. Unfortunately,
3524 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3525 // to just look at OpNo + the offset to the index reg. We actually need to
3526 // scan the instruction to find the index reg and see if its the correct reg
3528 unsigned OperandNo = 0;
3529 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3530 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3531 MachineOperand &MO = *I;
3532 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3534 // Found the index reg, now try to rewrite it.
3535 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3536 MO.getReg(), OperandNo);
3537 if (IndexReg == MO.getReg())
3539 MO.setReg(IndexReg);
3542 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3543 MI->eraseFromParent();
3549 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3550 const TargetLibraryInfo *libInfo) {
3551 return new X86FastISel(funcInfo, libInfo);