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 // Obtain the branch weight and add the TrueBB to the successor list.
1435 uint32_t BranchWeight = 0;
1437 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1438 TrueMBB->getBasicBlock());
1439 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1441 // Emits an unconditional branch to the FalseBB, obtains the branch
1442 // weight, and adds it to the successor list.
1443 fastEmitBranch(FalseMBB, DbgLoc);
1447 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1448 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1449 // typically happen for _Bool and C++ bools.
1451 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1452 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1453 unsigned TestOpc = 0;
1454 switch (SourceVT.SimpleTy) {
1456 case MVT::i8: TestOpc = X86::TEST8ri; break;
1457 case MVT::i16: TestOpc = X86::TEST16ri; break;
1458 case MVT::i32: TestOpc = X86::TEST32ri; break;
1459 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1462 unsigned OpReg = getRegForValue(TI->getOperand(0));
1463 if (OpReg == 0) return false;
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1465 .addReg(OpReg).addImm(1);
1467 unsigned JmpOpc = X86::JNE_1;
1468 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1469 std::swap(TrueMBB, FalseMBB);
1473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1475 fastEmitBranch(FalseMBB, DbgLoc);
1476 uint32_t BranchWeight = 0;
1478 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1479 TrueMBB->getBasicBlock());
1480 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1484 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1485 // Fake request the condition, otherwise the intrinsic might be completely
1487 unsigned TmpReg = getRegForValue(BI->getCondition());
1491 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1495 fastEmitBranch(FalseMBB, DbgLoc);
1496 uint32_t BranchWeight = 0;
1498 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1499 TrueMBB->getBasicBlock());
1500 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1504 // Otherwise do a clumsy setcc and re-test it.
1505 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1506 // in an explicit cast, so make sure to handle that correctly.
1507 unsigned OpReg = getRegForValue(BI->getCondition());
1508 if (OpReg == 0) return false;
1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1511 .addReg(OpReg).addImm(1);
1512 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1514 fastEmitBranch(FalseMBB, DbgLoc);
1515 uint32_t BranchWeight = 0;
1517 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1518 TrueMBB->getBasicBlock());
1519 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1523 bool X86FastISel::X86SelectShift(const Instruction *I) {
1524 unsigned CReg = 0, OpReg = 0;
1525 const TargetRegisterClass *RC = nullptr;
1526 if (I->getType()->isIntegerTy(8)) {
1528 RC = &X86::GR8RegClass;
1529 switch (I->getOpcode()) {
1530 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1531 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1532 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1533 default: return false;
1535 } else if (I->getType()->isIntegerTy(16)) {
1537 RC = &X86::GR16RegClass;
1538 switch (I->getOpcode()) {
1539 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1540 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1541 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1542 default: return false;
1544 } else if (I->getType()->isIntegerTy(32)) {
1546 RC = &X86::GR32RegClass;
1547 switch (I->getOpcode()) {
1548 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1549 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1550 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1551 default: return false;
1553 } else if (I->getType()->isIntegerTy(64)) {
1555 RC = &X86::GR64RegClass;
1556 switch (I->getOpcode()) {
1557 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1558 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1559 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1560 default: return false;
1567 if (!isTypeLegal(I->getType(), VT))
1570 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1571 if (Op0Reg == 0) return false;
1573 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1574 if (Op1Reg == 0) return false;
1575 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1576 CReg).addReg(Op1Reg);
1578 // The shift instruction uses X86::CL. If we defined a super-register
1579 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1580 if (CReg != X86::CL)
1581 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1582 TII.get(TargetOpcode::KILL), X86::CL)
1583 .addReg(CReg, RegState::Kill);
1585 unsigned ResultReg = createResultReg(RC);
1586 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1588 updateValueMap(I, ResultReg);
1592 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1593 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1594 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1595 const static bool S = true; // IsSigned
1596 const static bool U = false; // !IsSigned
1597 const static unsigned Copy = TargetOpcode::COPY;
1598 // For the X86 DIV/IDIV instruction, in most cases the dividend
1599 // (numerator) must be in a specific register pair highreg:lowreg,
1600 // producing the quotient in lowreg and the remainder in highreg.
1601 // For most data types, to set up the instruction, the dividend is
1602 // copied into lowreg, and lowreg is sign-extended or zero-extended
1603 // into highreg. The exception is i8, where the dividend is defined
1604 // as a single register rather than a register pair, and we
1605 // therefore directly sign-extend or zero-extend the dividend into
1606 // lowreg, instead of copying, and ignore the highreg.
1607 const static struct DivRemEntry {
1608 // The following portion depends only on the data type.
1609 const TargetRegisterClass *RC;
1610 unsigned LowInReg; // low part of the register pair
1611 unsigned HighInReg; // high part of the register pair
1612 // The following portion depends on both the data type and the operation.
1613 struct DivRemResult {
1614 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1615 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1616 // highreg, or copying a zero into highreg.
1617 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1618 // zero/sign-extending into lowreg for i8.
1619 unsigned DivRemResultReg; // Register containing the desired result.
1620 bool IsOpSigned; // Whether to use signed or unsigned form.
1621 } ResultTable[NumOps];
1622 } OpTable[NumTypes] = {
1623 { &X86::GR8RegClass, X86::AX, 0, {
1624 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1625 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1626 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1627 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1630 { &X86::GR16RegClass, X86::AX, X86::DX, {
1631 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1632 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1633 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1634 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1637 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1638 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1639 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1640 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1641 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1644 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1645 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1646 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1647 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1648 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1654 if (!isTypeLegal(I->getType(), VT))
1657 unsigned TypeIndex, OpIndex;
1658 switch (VT.SimpleTy) {
1659 default: return false;
1660 case MVT::i8: TypeIndex = 0; break;
1661 case MVT::i16: TypeIndex = 1; break;
1662 case MVT::i32: TypeIndex = 2; break;
1663 case MVT::i64: TypeIndex = 3;
1664 if (!Subtarget->is64Bit())
1669 switch (I->getOpcode()) {
1670 default: llvm_unreachable("Unexpected div/rem opcode");
1671 case Instruction::SDiv: OpIndex = 0; break;
1672 case Instruction::SRem: OpIndex = 1; break;
1673 case Instruction::UDiv: OpIndex = 2; break;
1674 case Instruction::URem: OpIndex = 3; break;
1677 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1678 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1679 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1682 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1686 // Move op0 into low-order input register.
1687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1688 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1689 // Zero-extend or sign-extend into high-order input register.
1690 if (OpEntry.OpSignExtend) {
1691 if (OpEntry.IsOpSigned)
1692 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1693 TII.get(OpEntry.OpSignExtend));
1695 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1697 TII.get(X86::MOV32r0), Zero32);
1699 // Copy the zero into the appropriate sub/super/identical physical
1700 // register. Unfortunately the operations needed are not uniform enough
1701 // to fit neatly into the table above.
1702 if (VT.SimpleTy == MVT::i16) {
1703 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1704 TII.get(Copy), TypeEntry.HighInReg)
1705 .addReg(Zero32, 0, X86::sub_16bit);
1706 } else if (VT.SimpleTy == MVT::i32) {
1707 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1708 TII.get(Copy), TypeEntry.HighInReg)
1710 } else if (VT.SimpleTy == MVT::i64) {
1711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1712 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1713 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1717 // Generate the DIV/IDIV instruction.
1718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1719 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1720 // For i8 remainder, we can't reference AH directly, as we'll end
1721 // up with bogus copies like %R9B = COPY %AH. Reference AX
1722 // instead to prevent AH references in a REX instruction.
1724 // The current assumption of the fast register allocator is that isel
1725 // won't generate explicit references to the GPR8_NOREX registers. If
1726 // the allocator and/or the backend get enhanced to be more robust in
1727 // that regard, this can be, and should be, removed.
1728 unsigned ResultReg = 0;
1729 if ((I->getOpcode() == Instruction::SRem ||
1730 I->getOpcode() == Instruction::URem) &&
1731 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1732 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1733 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1734 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1735 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1737 // Shift AX right by 8 bits instead of using AH.
1738 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1739 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1741 // Now reference the 8-bit subreg of the result.
1742 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1743 /*Kill=*/true, X86::sub_8bit);
1745 // Copy the result out of the physreg if we haven't already.
1747 ResultReg = createResultReg(TypeEntry.RC);
1748 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1749 .addReg(OpEntry.DivRemResultReg);
1751 updateValueMap(I, ResultReg);
1756 /// \brief Emit a conditional move instruction (if the are supported) to lower
1758 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1759 // Check if the subtarget supports these instructions.
1760 if (!Subtarget->hasCMov())
1763 // FIXME: Add support for i8.
1764 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1767 const Value *Cond = I->getOperand(0);
1768 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1769 bool NeedTest = true;
1770 X86::CondCode CC = X86::COND_NE;
1772 // Optimize conditions coming from a compare if both instructions are in the
1773 // same basic block (values defined in other basic blocks may not have
1774 // initialized registers).
1775 const auto *CI = dyn_cast<CmpInst>(Cond);
1776 if (CI && (CI->getParent() == I->getParent())) {
1777 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1779 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1780 static unsigned SETFOpcTable[2][3] = {
1781 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1782 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1784 unsigned *SETFOpc = nullptr;
1785 switch (Predicate) {
1787 case CmpInst::FCMP_OEQ:
1788 SETFOpc = &SETFOpcTable[0][0];
1789 Predicate = CmpInst::ICMP_NE;
1791 case CmpInst::FCMP_UNE:
1792 SETFOpc = &SETFOpcTable[1][0];
1793 Predicate = CmpInst::ICMP_NE;
1798 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1799 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1801 const Value *CmpLHS = CI->getOperand(0);
1802 const Value *CmpRHS = CI->getOperand(1);
1804 std::swap(CmpLHS, CmpRHS);
1806 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
1807 // Emit a compare of the LHS and RHS, setting the flags.
1808 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1812 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1813 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1816 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1818 auto const &II = TII.get(SETFOpc[2]);
1819 if (II.getNumDefs()) {
1820 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1821 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1822 .addReg(FlagReg2).addReg(FlagReg1);
1824 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1825 .addReg(FlagReg2).addReg(FlagReg1);
1829 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1830 // Fake request the condition, otherwise the intrinsic might be completely
1832 unsigned TmpReg = getRegForValue(Cond);
1840 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1841 // garbage. Indeed, only the less significant bit is supposed to be
1842 // accurate. If we read more than the lsb, we may see non-zero values
1843 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1844 // the select. This is achieved by performing TEST against 1.
1845 unsigned CondReg = getRegForValue(Cond);
1848 bool CondIsKill = hasTrivialKill(Cond);
1850 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1851 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1854 const Value *LHS = I->getOperand(1);
1855 const Value *RHS = I->getOperand(2);
1857 unsigned RHSReg = getRegForValue(RHS);
1858 bool RHSIsKill = hasTrivialKill(RHS);
1860 unsigned LHSReg = getRegForValue(LHS);
1861 bool LHSIsKill = hasTrivialKill(LHS);
1863 if (!LHSReg || !RHSReg)
1866 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1867 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1869 updateValueMap(I, ResultReg);
1873 /// \brief Emit SSE or AVX instructions to lower the select.
1875 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1876 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1877 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1878 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1879 // Optimize conditions coming from a compare if both instructions are in the
1880 // same basic block (values defined in other basic blocks may not have
1881 // initialized registers).
1882 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1883 if (!CI || (CI->getParent() != I->getParent()))
1886 if (I->getType() != CI->getOperand(0)->getType() ||
1887 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1888 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1891 const Value *CmpLHS = CI->getOperand(0);
1892 const Value *CmpRHS = CI->getOperand(1);
1893 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1895 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1896 // We don't have to materialize a zero constant for this case and can just use
1897 // %x again on the RHS.
1898 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1899 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1900 if (CmpRHSC && CmpRHSC->isNullValue())
1906 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1911 std::swap(CmpLHS, CmpRHS);
1913 // Choose the SSE instruction sequence based on data type (float or double).
1914 static unsigned OpcTable[2][4] = {
1915 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1916 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1919 unsigned *Opc = nullptr;
1920 switch (RetVT.SimpleTy) {
1921 default: return false;
1922 case MVT::f32: Opc = &OpcTable[0][0]; break;
1923 case MVT::f64: Opc = &OpcTable[1][0]; break;
1926 const Value *LHS = I->getOperand(1);
1927 const Value *RHS = I->getOperand(2);
1929 unsigned LHSReg = getRegForValue(LHS);
1930 bool LHSIsKill = hasTrivialKill(LHS);
1932 unsigned RHSReg = getRegForValue(RHS);
1933 bool RHSIsKill = hasTrivialKill(RHS);
1935 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1936 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1938 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1939 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1941 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1944 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1947 if (Subtarget->hasAVX()) {
1948 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1949 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1950 // uses XMM0 as the selection register. That may need just as many
1951 // instructions as the AND/ANDN/OR sequence due to register moves, so
1953 unsigned CmpOpcode =
1954 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1955 unsigned BlendOpcode =
1956 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1958 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
1959 CmpRHSReg, CmpRHSIsKill, CC);
1960 ResultReg = fastEmitInst_rrr(BlendOpcode, RC, RHSReg, RHSIsKill,
1961 LHSReg, LHSIsKill, CmpReg, true);
1963 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1964 CmpRHSReg, CmpRHSIsKill, CC);
1965 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1967 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1969 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1970 AndReg, /*IsKill=*/true);
1972 updateValueMap(I, ResultReg);
1976 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1977 // These are pseudo CMOV instructions and will be later expanded into control-
1980 switch (RetVT.SimpleTy) {
1981 default: return false;
1982 case MVT::i8: Opc = X86::CMOV_GR8; break;
1983 case MVT::i16: Opc = X86::CMOV_GR16; break;
1984 case MVT::i32: Opc = X86::CMOV_GR32; break;
1985 case MVT::f32: Opc = X86::CMOV_FR32; break;
1986 case MVT::f64: Opc = X86::CMOV_FR64; break;
1989 const Value *Cond = I->getOperand(0);
1990 X86::CondCode CC = X86::COND_NE;
1992 // Optimize conditions coming from a compare if both instructions are in the
1993 // same basic block (values defined in other basic blocks may not have
1994 // initialized registers).
1995 const auto *CI = dyn_cast<CmpInst>(Cond);
1996 if (CI && (CI->getParent() == I->getParent())) {
1998 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1999 if (CC > X86::LAST_VALID_COND)
2002 const Value *CmpLHS = CI->getOperand(0);
2003 const Value *CmpRHS = CI->getOperand(1);
2006 std::swap(CmpLHS, CmpRHS);
2008 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2009 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2012 unsigned CondReg = getRegForValue(Cond);
2015 bool CondIsKill = hasTrivialKill(Cond);
2016 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2017 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2020 const Value *LHS = I->getOperand(1);
2021 const Value *RHS = I->getOperand(2);
2023 unsigned LHSReg = getRegForValue(LHS);
2024 bool LHSIsKill = hasTrivialKill(LHS);
2026 unsigned RHSReg = getRegForValue(RHS);
2027 bool RHSIsKill = hasTrivialKill(RHS);
2029 if (!LHSReg || !RHSReg)
2032 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2034 unsigned ResultReg =
2035 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2036 updateValueMap(I, ResultReg);
2040 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2042 if (!isTypeLegal(I->getType(), RetVT))
2045 // Check if we can fold the select.
2046 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2047 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2048 const Value *Opnd = nullptr;
2049 switch (Predicate) {
2051 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2052 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2054 // No need for a select anymore - this is an unconditional move.
2056 unsigned OpReg = getRegForValue(Opnd);
2059 bool OpIsKill = hasTrivialKill(Opnd);
2060 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2061 unsigned ResultReg = createResultReg(RC);
2062 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2063 TII.get(TargetOpcode::COPY), ResultReg)
2064 .addReg(OpReg, getKillRegState(OpIsKill));
2065 updateValueMap(I, ResultReg);
2070 // First try to use real conditional move instructions.
2071 if (X86FastEmitCMoveSelect(RetVT, I))
2074 // Try to use a sequence of SSE instructions to simulate a conditional move.
2075 if (X86FastEmitSSESelect(RetVT, I))
2078 // Fall-back to pseudo conditional move instructions, which will be later
2079 // converted to control-flow.
2080 if (X86FastEmitPseudoSelect(RetVT, I))
2086 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2087 // The target-independent selection algorithm in FastISel already knows how
2088 // to select a SINT_TO_FP if the target is SSE but not AVX.
2089 // Early exit if the subtarget doesn't have AVX.
2090 if (!Subtarget->hasAVX())
2093 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2096 // Select integer to float/double conversion.
2097 unsigned OpReg = getRegForValue(I->getOperand(0));
2101 const TargetRegisterClass *RC = nullptr;
2104 if (I->getType()->isDoubleTy()) {
2105 // sitofp int -> double
2106 Opcode = X86::VCVTSI2SDrr;
2107 RC = &X86::FR64RegClass;
2108 } else if (I->getType()->isFloatTy()) {
2109 // sitofp int -> float
2110 Opcode = X86::VCVTSI2SSrr;
2111 RC = &X86::FR32RegClass;
2115 unsigned ImplicitDefReg = createResultReg(RC);
2116 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2117 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2118 unsigned ResultReg =
2119 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2120 updateValueMap(I, ResultReg);
2124 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2125 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2127 const TargetRegisterClass *RC) {
2128 assert((I->getOpcode() == Instruction::FPExt ||
2129 I->getOpcode() == Instruction::FPTrunc) &&
2130 "Instruction must be an FPExt or FPTrunc!");
2132 unsigned OpReg = getRegForValue(I->getOperand(0));
2136 unsigned ResultReg = createResultReg(RC);
2137 MachineInstrBuilder MIB;
2138 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2140 if (Subtarget->hasAVX())
2143 updateValueMap(I, ResultReg);
2147 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2148 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2149 I->getOperand(0)->getType()->isFloatTy()) {
2150 // fpext from float to double.
2151 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2152 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2158 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2159 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2160 I->getOperand(0)->getType()->isDoubleTy()) {
2161 // fptrunc from double to float.
2162 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2163 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2169 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2170 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2171 EVT DstVT = TLI.getValueType(DL, I->getType());
2173 // This code only handles truncation to byte.
2174 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2176 if (!TLI.isTypeLegal(SrcVT))
2179 unsigned InputReg = getRegForValue(I->getOperand(0));
2181 // Unhandled operand. Halt "fast" selection and bail.
2184 if (SrcVT == MVT::i8) {
2185 // Truncate from i8 to i1; no code needed.
2186 updateValueMap(I, InputReg);
2190 bool KillInputReg = false;
2191 if (!Subtarget->is64Bit()) {
2192 // If we're on x86-32; we can't extract an i8 from a general register.
2193 // First issue a copy to GR16_ABCD or GR32_ABCD.
2194 const TargetRegisterClass *CopyRC =
2195 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2196 unsigned CopyReg = createResultReg(CopyRC);
2197 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2198 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2200 KillInputReg = true;
2203 // Issue an extract_subreg.
2204 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2205 InputReg, KillInputReg,
2210 updateValueMap(I, ResultReg);
2214 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2215 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2218 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2219 X86AddressMode SrcAM, uint64_t Len) {
2221 // Make sure we don't bloat code by inlining very large memcpy's.
2222 if (!IsMemcpySmall(Len))
2225 bool i64Legal = Subtarget->is64Bit();
2227 // We don't care about alignment here since we just emit integer accesses.
2230 if (Len >= 8 && i64Legal)
2240 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2241 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2242 assert(RV && "Failed to emit load or store??");
2244 unsigned Size = VT.getSizeInBits()/8;
2246 DestAM.Disp += Size;
2253 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2254 // FIXME: Handle more intrinsics.
2255 switch (II->getIntrinsicID()) {
2256 default: return false;
2257 case Intrinsic::convert_from_fp16:
2258 case Intrinsic::convert_to_fp16: {
2259 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2262 const Value *Op = II->getArgOperand(0);
2263 unsigned InputReg = getRegForValue(Op);
2267 // F16C only allows converting from float to half and from half to float.
2268 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2269 if (IsFloatToHalf) {
2270 if (!Op->getType()->isFloatTy())
2273 if (!II->getType()->isFloatTy())
2277 unsigned ResultReg = 0;
2278 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2279 if (IsFloatToHalf) {
2280 // 'InputReg' is implicitly promoted from register class FR32 to
2281 // register class VR128 by method 'constrainOperandRegClass' which is
2282 // directly called by 'fastEmitInst_ri'.
2283 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2284 // used to provide rounding control.
2285 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2287 // Move the lower 32-bits of ResultReg to another register of class GR32.
2288 ResultReg = createResultReg(&X86::GR32RegClass);
2289 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2290 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2291 .addReg(InputReg, RegState::Kill);
2293 // The result value is in the lower 16-bits of ResultReg.
2294 unsigned RegIdx = X86::sub_16bit;
2295 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2297 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2298 // Explicitly sign-extend the input to 32-bit.
2299 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2302 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2303 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2304 InputReg, /*Kill=*/true);
2306 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2308 // The result value is in the lower 32-bits of ResultReg.
2309 // Emit an explicit copy from register class VR128 to register class FR32.
2310 ResultReg = createResultReg(&X86::FR32RegClass);
2311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2312 TII.get(TargetOpcode::COPY), ResultReg)
2313 .addReg(InputReg, RegState::Kill);
2316 updateValueMap(II, ResultReg);
2319 case Intrinsic::frameaddress: {
2320 MachineFunction *MF = FuncInfo.MF;
2321 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2324 Type *RetTy = II->getCalledFunction()->getReturnType();
2327 if (!isTypeLegal(RetTy, VT))
2331 const TargetRegisterClass *RC = nullptr;
2333 switch (VT.SimpleTy) {
2334 default: llvm_unreachable("Invalid result type for frameaddress.");
2335 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2336 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2339 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2340 // we get the wrong frame register.
2341 MachineFrameInfo *MFI = MF->getFrameInfo();
2342 MFI->setFrameAddressIsTaken(true);
2344 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2345 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2346 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2347 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2348 "Invalid Frame Register!");
2350 // Always make a copy of the frame register to to a vreg first, so that we
2351 // never directly reference the frame register (the TwoAddressInstruction-
2352 // Pass doesn't like that).
2353 unsigned SrcReg = createResultReg(RC);
2354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2355 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2357 // Now recursively load from the frame address.
2358 // movq (%rbp), %rax
2359 // movq (%rax), %rax
2360 // movq (%rax), %rax
2363 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2365 DestReg = createResultReg(RC);
2366 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2367 TII.get(Opc), DestReg), SrcReg);
2371 updateValueMap(II, SrcReg);
2374 case Intrinsic::memcpy: {
2375 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2376 // Don't handle volatile or variable length memcpys.
2377 if (MCI->isVolatile())
2380 if (isa<ConstantInt>(MCI->getLength())) {
2381 // Small memcpy's are common enough that we want to do them
2382 // without a call if possible.
2383 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2384 if (IsMemcpySmall(Len)) {
2385 X86AddressMode DestAM, SrcAM;
2386 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2387 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2389 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2394 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2395 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2398 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2401 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2403 case Intrinsic::memset: {
2404 const MemSetInst *MSI = cast<MemSetInst>(II);
2406 if (MSI->isVolatile())
2409 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2410 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2413 if (MSI->getDestAddressSpace() > 255)
2416 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2418 case Intrinsic::stackprotector: {
2419 // Emit code to store the stack guard onto the stack.
2420 EVT PtrTy = TLI.getPointerTy(DL);
2422 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2423 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2425 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2427 // Grab the frame index.
2429 if (!X86SelectAddress(Slot, AM)) return false;
2430 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2433 case Intrinsic::dbg_declare: {
2434 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2436 assert(DI->getAddress() && "Null address should be checked earlier!");
2437 if (!X86SelectAddress(DI->getAddress(), AM))
2439 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2440 // FIXME may need to add RegState::Debug to any registers produced,
2441 // although ESP/EBP should be the only ones at the moment.
2442 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2443 "Expected inlined-at fields to agree");
2444 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2446 .addMetadata(DI->getVariable())
2447 .addMetadata(DI->getExpression());
2450 case Intrinsic::trap: {
2451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2454 case Intrinsic::sqrt: {
2455 if (!Subtarget->hasSSE1())
2458 Type *RetTy = II->getCalledFunction()->getReturnType();
2461 if (!isTypeLegal(RetTy, VT))
2464 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2465 // is not generated by FastISel yet.
2466 // FIXME: Update this code once tablegen can handle it.
2467 static const unsigned SqrtOpc[2][2] = {
2468 {X86::SQRTSSr, X86::VSQRTSSr},
2469 {X86::SQRTSDr, X86::VSQRTSDr}
2471 bool HasAVX = Subtarget->hasAVX();
2473 const TargetRegisterClass *RC;
2474 switch (VT.SimpleTy) {
2475 default: return false;
2476 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2477 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2480 const Value *SrcVal = II->getArgOperand(0);
2481 unsigned SrcReg = getRegForValue(SrcVal);
2486 unsigned ImplicitDefReg = 0;
2488 ImplicitDefReg = createResultReg(RC);
2489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2490 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2493 unsigned ResultReg = createResultReg(RC);
2494 MachineInstrBuilder MIB;
2495 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2499 MIB.addReg(ImplicitDefReg);
2503 updateValueMap(II, ResultReg);
2506 case Intrinsic::sadd_with_overflow:
2507 case Intrinsic::uadd_with_overflow:
2508 case Intrinsic::ssub_with_overflow:
2509 case Intrinsic::usub_with_overflow:
2510 case Intrinsic::smul_with_overflow:
2511 case Intrinsic::umul_with_overflow: {
2512 // This implements the basic lowering of the xalu with overflow intrinsics
2513 // into add/sub/mul followed by either seto or setb.
2514 const Function *Callee = II->getCalledFunction();
2515 auto *Ty = cast<StructType>(Callee->getReturnType());
2516 Type *RetTy = Ty->getTypeAtIndex(0U);
2517 Type *CondTy = Ty->getTypeAtIndex(1);
2520 if (!isTypeLegal(RetTy, VT))
2523 if (VT < MVT::i8 || VT > MVT::i64)
2526 const Value *LHS = II->getArgOperand(0);
2527 const Value *RHS = II->getArgOperand(1);
2529 // Canonicalize immediate to the RHS.
2530 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2531 isCommutativeIntrinsic(II))
2532 std::swap(LHS, RHS);
2534 bool UseIncDec = false;
2535 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2538 unsigned BaseOpc, CondOpc;
2539 switch (II->getIntrinsicID()) {
2540 default: llvm_unreachable("Unexpected intrinsic!");
2541 case Intrinsic::sadd_with_overflow:
2542 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2543 CondOpc = X86::SETOr;
2545 case Intrinsic::uadd_with_overflow:
2546 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2547 case Intrinsic::ssub_with_overflow:
2548 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2549 CondOpc = X86::SETOr;
2551 case Intrinsic::usub_with_overflow:
2552 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2553 case Intrinsic::smul_with_overflow:
2554 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2555 case Intrinsic::umul_with_overflow:
2556 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2559 unsigned LHSReg = getRegForValue(LHS);
2562 bool LHSIsKill = hasTrivialKill(LHS);
2564 unsigned ResultReg = 0;
2565 // Check if we have an immediate version.
2566 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2567 static const unsigned Opc[2][4] = {
2568 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2569 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2572 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2573 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2574 bool IsDec = BaseOpc == X86ISD::DEC;
2575 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2576 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2577 .addReg(LHSReg, getKillRegState(LHSIsKill));
2579 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2580 CI->getZExtValue());
2586 RHSReg = getRegForValue(RHS);
2589 RHSIsKill = hasTrivialKill(RHS);
2590 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2594 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2596 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2597 static const unsigned MULOpc[] =
2598 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2599 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2600 // First copy the first operand into RAX, which is an implicit input to
2601 // the X86::MUL*r instruction.
2602 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2603 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2604 .addReg(LHSReg, getKillRegState(LHSIsKill));
2605 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2606 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2607 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2608 static const unsigned MULOpc[] =
2609 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2610 if (VT == MVT::i8) {
2611 // Copy the first operand into AL, which is an implicit input to the
2612 // X86::IMUL8r instruction.
2613 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2614 TII.get(TargetOpcode::COPY), X86::AL)
2615 .addReg(LHSReg, getKillRegState(LHSIsKill));
2616 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2619 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2620 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2627 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2628 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2629 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2632 updateValueMap(II, ResultReg, 2);
2635 case Intrinsic::x86_sse_cvttss2si:
2636 case Intrinsic::x86_sse_cvttss2si64:
2637 case Intrinsic::x86_sse2_cvttsd2si:
2638 case Intrinsic::x86_sse2_cvttsd2si64: {
2640 switch (II->getIntrinsicID()) {
2641 default: llvm_unreachable("Unexpected intrinsic.");
2642 case Intrinsic::x86_sse_cvttss2si:
2643 case Intrinsic::x86_sse_cvttss2si64:
2644 if (!Subtarget->hasSSE1())
2646 IsInputDouble = false;
2648 case Intrinsic::x86_sse2_cvttsd2si:
2649 case Intrinsic::x86_sse2_cvttsd2si64:
2650 if (!Subtarget->hasSSE2())
2652 IsInputDouble = true;
2656 Type *RetTy = II->getCalledFunction()->getReturnType();
2658 if (!isTypeLegal(RetTy, VT))
2661 static const unsigned CvtOpc[2][2][2] = {
2662 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2663 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2664 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2665 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2667 bool HasAVX = Subtarget->hasAVX();
2669 switch (VT.SimpleTy) {
2670 default: llvm_unreachable("Unexpected result type.");
2671 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2672 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2675 // Check if we can fold insertelement instructions into the convert.
2676 const Value *Op = II->getArgOperand(0);
2677 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2678 const Value *Index = IE->getOperand(2);
2679 if (!isa<ConstantInt>(Index))
2681 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2684 Op = IE->getOperand(1);
2687 Op = IE->getOperand(0);
2690 unsigned Reg = getRegForValue(Op);
2694 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2695 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2698 updateValueMap(II, ResultReg);
2704 bool X86FastISel::fastLowerArguments() {
2705 if (!FuncInfo.CanLowerReturn)
2708 const Function *F = FuncInfo.Fn;
2712 CallingConv::ID CC = F->getCallingConv();
2713 if (CC != CallingConv::C)
2716 if (Subtarget->isCallingConvWin64(CC))
2719 if (!Subtarget->is64Bit())
2722 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2723 unsigned GPRCnt = 0;
2724 unsigned FPRCnt = 0;
2726 for (auto const &Arg : F->args()) {
2727 // The first argument is at index 1.
2729 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2730 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2731 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2732 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2735 Type *ArgTy = Arg.getType();
2736 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2739 EVT ArgVT = TLI.getValueType(DL, ArgTy);
2740 if (!ArgVT.isSimple()) return false;
2741 switch (ArgVT.getSimpleVT().SimpleTy) {
2742 default: return false;
2749 if (!Subtarget->hasSSE1())
2762 static const MCPhysReg GPR32ArgRegs[] = {
2763 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2765 static const MCPhysReg GPR64ArgRegs[] = {
2766 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2768 static const MCPhysReg XMMArgRegs[] = {
2769 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2770 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2773 unsigned GPRIdx = 0;
2774 unsigned FPRIdx = 0;
2775 for (auto const &Arg : F->args()) {
2776 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
2777 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2779 switch (VT.SimpleTy) {
2780 default: llvm_unreachable("Unexpected value type.");
2781 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2782 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2783 case MVT::f32: // fall-through
2784 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2786 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2787 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2788 // Without this, EmitLiveInCopies may eliminate the livein if its only
2789 // use is a bitcast (which isn't turned into an instruction).
2790 unsigned ResultReg = createResultReg(RC);
2791 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2792 TII.get(TargetOpcode::COPY), ResultReg)
2793 .addReg(DstReg, getKillRegState(true));
2794 updateValueMap(&Arg, ResultReg);
2799 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2801 ImmutableCallSite *CS) {
2802 if (Subtarget->is64Bit())
2804 if (Subtarget->getTargetTriple().isOSMSVCRT())
2806 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2807 CC == CallingConv::HiPE)
2809 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2811 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2816 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2817 auto &OutVals = CLI.OutVals;
2818 auto &OutFlags = CLI.OutFlags;
2819 auto &OutRegs = CLI.OutRegs;
2820 auto &Ins = CLI.Ins;
2821 auto &InRegs = CLI.InRegs;
2822 CallingConv::ID CC = CLI.CallConv;
2823 bool &IsTailCall = CLI.IsTailCall;
2824 bool IsVarArg = CLI.IsVarArg;
2825 const Value *Callee = CLI.Callee;
2826 MCSymbol *Symbol = CLI.Symbol;
2828 bool Is64Bit = Subtarget->is64Bit();
2829 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2831 // Handle only C, fastcc, and webkit_js calling conventions for now.
2833 default: return false;
2834 case CallingConv::C:
2835 case CallingConv::Fast:
2836 case CallingConv::WebKit_JS:
2837 case CallingConv::X86_FastCall:
2838 case CallingConv::X86_64_Win64:
2839 case CallingConv::X86_64_SysV:
2843 // Allow SelectionDAG isel to handle tail calls.
2847 // fastcc with -tailcallopt is intended to provide a guaranteed
2848 // tail call optimization. Fastisel doesn't know how to do that.
2849 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2852 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2853 // x86-32. Special handling for x86-64 is implemented.
2854 if (IsVarArg && IsWin64)
2857 // Don't know about inalloca yet.
2858 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2861 // Fast-isel doesn't know about callee-pop yet.
2862 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2863 TM.Options.GuaranteedTailCallOpt))
2866 SmallVector<MVT, 16> OutVTs;
2867 SmallVector<unsigned, 16> ArgRegs;
2869 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2870 // instruction. This is safe because it is common to all FastISel supported
2871 // calling conventions on x86.
2872 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2873 Value *&Val = OutVals[i];
2874 ISD::ArgFlagsTy Flags = OutFlags[i];
2875 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2876 if (CI->getBitWidth() < 32) {
2878 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2880 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2884 // Passing bools around ends up doing a trunc to i1 and passing it.
2885 // Codegen this as an argument + "and 1".
2887 auto *TI = dyn_cast<TruncInst>(Val);
2889 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2890 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2892 Value *PrevVal = TI->getOperand(0);
2893 ResultReg = getRegForValue(PrevVal);
2898 if (!isTypeLegal(PrevVal->getType(), VT))
2902 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2904 if (!isTypeLegal(Val->getType(), VT))
2906 ResultReg = getRegForValue(Val);
2912 ArgRegs.push_back(ResultReg);
2913 OutVTs.push_back(VT);
2916 // Analyze operands of the call, assigning locations to each operand.
2917 SmallVector<CCValAssign, 16> ArgLocs;
2918 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2920 // Allocate shadow area for Win64
2922 CCInfo.AllocateStack(32, 8);
2924 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2926 // Get a count of how many bytes are to be pushed on the stack.
2927 unsigned NumBytes = CCInfo.getNextStackOffset();
2929 // Issue CALLSEQ_START
2930 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2931 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2932 .addImm(NumBytes).addImm(0);
2934 // Walk the register/memloc assignments, inserting copies/loads.
2935 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2936 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2937 CCValAssign const &VA = ArgLocs[i];
2938 const Value *ArgVal = OutVals[VA.getValNo()];
2939 MVT ArgVT = OutVTs[VA.getValNo()];
2941 if (ArgVT == MVT::x86mmx)
2944 unsigned ArgReg = ArgRegs[VA.getValNo()];
2946 // Promote the value if needed.
2947 switch (VA.getLocInfo()) {
2948 case CCValAssign::Full: break;
2949 case CCValAssign::SExt: {
2950 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2951 "Unexpected extend");
2952 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2954 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2955 ArgVT = VA.getLocVT();
2958 case CCValAssign::ZExt: {
2959 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2960 "Unexpected extend");
2961 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2963 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2964 ArgVT = VA.getLocVT();
2967 case CCValAssign::AExt: {
2968 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2969 "Unexpected extend");
2970 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2973 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2976 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2979 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2980 ArgVT = VA.getLocVT();
2983 case CCValAssign::BCvt: {
2984 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2985 /*TODO: Kill=*/false);
2986 assert(ArgReg && "Failed to emit a bitcast!");
2987 ArgVT = VA.getLocVT();
2990 case CCValAssign::VExt:
2991 // VExt has not been implemented, so this should be impossible to reach
2992 // for now. However, fallback to Selection DAG isel once implemented.
2994 case CCValAssign::AExtUpper:
2995 case CCValAssign::SExtUpper:
2996 case CCValAssign::ZExtUpper:
2997 case CCValAssign::FPExt:
2998 llvm_unreachable("Unexpected loc info!");
2999 case CCValAssign::Indirect:
3000 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3005 if (VA.isRegLoc()) {
3006 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3007 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3008 OutRegs.push_back(VA.getLocReg());
3010 assert(VA.isMemLoc());
3012 // Don't emit stores for undef values.
3013 if (isa<UndefValue>(ArgVal))
3016 unsigned LocMemOffset = VA.getLocMemOffset();
3018 AM.Base.Reg = RegInfo->getStackRegister();
3019 AM.Disp = LocMemOffset;
3020 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3021 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3022 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3023 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3024 ArgVT.getStoreSize(), Alignment);
3025 if (Flags.isByVal()) {
3026 X86AddressMode SrcAM;
3027 SrcAM.Base.Reg = ArgReg;
3028 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3030 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3031 // If this is a really simple value, emit this with the Value* version
3032 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3033 // as it can cause us to reevaluate the argument.
3034 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3037 bool ValIsKill = hasTrivialKill(ArgVal);
3038 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3044 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3046 if (Subtarget->isPICStyleGOT()) {
3047 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3049 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3052 if (Is64Bit && IsVarArg && !IsWin64) {
3053 // From AMD64 ABI document:
3054 // For calls that may call functions that use varargs or stdargs
3055 // (prototype-less calls or calls to functions containing ellipsis (...) in
3056 // the declaration) %al is used as hidden argument to specify the number
3057 // of SSE registers used. The contents of %al do not need to match exactly
3058 // the number of registers, but must be an ubound on the number of SSE
3059 // registers used and is in the range 0 - 8 inclusive.
3061 // Count the number of XMM registers allocated.
3062 static const MCPhysReg XMMArgRegs[] = {
3063 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3064 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3066 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3067 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3068 && "SSE registers cannot be used when SSE is disabled");
3069 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3070 X86::AL).addImm(NumXMMRegs);
3073 // Materialize callee address in a register. FIXME: GV address can be
3074 // handled with a CALLpcrel32 instead.
3075 X86AddressMode CalleeAM;
3076 if (!X86SelectCallAddress(Callee, CalleeAM))
3079 unsigned CalleeOp = 0;
3080 const GlobalValue *GV = nullptr;
3081 if (CalleeAM.GV != nullptr) {
3083 } else if (CalleeAM.Base.Reg != 0) {
3084 CalleeOp = CalleeAM.Base.Reg;
3089 MachineInstrBuilder MIB;
3091 // Register-indirect call.
3092 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3093 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3097 assert(GV && "Not a direct call");
3098 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3100 // See if we need any target-specific flags on the GV operand.
3101 unsigned char OpFlags = 0;
3103 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3104 // external symbols most go through the PLT in PIC mode. If the symbol
3105 // has hidden or protected visibility, or if it is static or local, then
3106 // we don't need to use the PLT - we can directly call it.
3107 if (Subtarget->isTargetELF() &&
3108 TM.getRelocationModel() == Reloc::PIC_ &&
3109 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3110 OpFlags = X86II::MO_PLT;
3111 } else if (Subtarget->isPICStyleStubAny() &&
3112 !GV->isStrongDefinitionForLinker() &&
3113 (!Subtarget->getTargetTriple().isMacOSX() ||
3114 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115 // PC-relative references to external symbols should go through $stub,
3116 // unless we're building with the leopard linker or later, which
3117 // automatically synthesizes these stubs.
3118 OpFlags = X86II::MO_DARWIN_STUB;
3121 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3123 MIB.addSym(Symbol, OpFlags);
3125 MIB.addGlobalAddress(GV, 0, OpFlags);
3128 // Add a register mask operand representing the call-preserved registers.
3129 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3130 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3132 // Add an implicit use GOT pointer in EBX.
3133 if (Subtarget->isPICStyleGOT())
3134 MIB.addReg(X86::EBX, RegState::Implicit);
3136 if (Is64Bit && IsVarArg && !IsWin64)
3137 MIB.addReg(X86::AL, RegState::Implicit);
3139 // Add implicit physical register uses to the call.
3140 for (auto Reg : OutRegs)
3141 MIB.addReg(Reg, RegState::Implicit);
3143 // Issue CALLSEQ_END
3144 unsigned NumBytesForCalleeToPop =
3145 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3146 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3147 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3148 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3150 // Now handle call return values.
3151 SmallVector<CCValAssign, 16> RVLocs;
3152 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3153 CLI.RetTy->getContext());
3154 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3156 // Copy all of the result registers out of their specified physreg.
3157 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3158 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3159 CCValAssign &VA = RVLocs[i];
3160 EVT CopyVT = VA.getValVT();
3161 unsigned CopyReg = ResultReg + i;
3163 // If this is x86-64, and we disabled SSE, we can't return FP values
3164 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3165 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3166 report_fatal_error("SSE register return with SSE disabled");
3169 // If we prefer to use the value in xmm registers, copy it out as f80 and
3170 // use a truncate to move it from fp stack reg to xmm reg.
3171 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3172 isScalarFPTypeInSSEReg(VA.getValVT())) {
3174 CopyReg = createResultReg(&X86::RFP80RegClass);
3177 // Copy out the result.
3178 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3179 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3180 InRegs.push_back(VA.getLocReg());
3182 // Round the f80 to the right size, which also moves it to the appropriate
3183 // xmm register. This is accomplished by storing the f80 value in memory
3184 // and then loading it back.
3185 if (CopyVT != VA.getValVT()) {
3186 EVT ResVT = VA.getValVT();
3187 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3188 unsigned MemSize = ResVT.getSizeInBits()/8;
3189 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3190 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3193 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3194 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3195 TII.get(Opc), ResultReg + i), FI);
3199 CLI.ResultReg = ResultReg;
3200 CLI.NumResultRegs = RVLocs.size();
3207 X86FastISel::fastSelectInstruction(const Instruction *I) {
3208 switch (I->getOpcode()) {
3210 case Instruction::Load:
3211 return X86SelectLoad(I);
3212 case Instruction::Store:
3213 return X86SelectStore(I);
3214 case Instruction::Ret:
3215 return X86SelectRet(I);
3216 case Instruction::ICmp:
3217 case Instruction::FCmp:
3218 return X86SelectCmp(I);
3219 case Instruction::ZExt:
3220 return X86SelectZExt(I);
3221 case Instruction::Br:
3222 return X86SelectBranch(I);
3223 case Instruction::LShr:
3224 case Instruction::AShr:
3225 case Instruction::Shl:
3226 return X86SelectShift(I);
3227 case Instruction::SDiv:
3228 case Instruction::UDiv:
3229 case Instruction::SRem:
3230 case Instruction::URem:
3231 return X86SelectDivRem(I);
3232 case Instruction::Select:
3233 return X86SelectSelect(I);
3234 case Instruction::Trunc:
3235 return X86SelectTrunc(I);
3236 case Instruction::FPExt:
3237 return X86SelectFPExt(I);
3238 case Instruction::FPTrunc:
3239 return X86SelectFPTrunc(I);
3240 case Instruction::SIToFP:
3241 return X86SelectSIToFP(I);
3242 case Instruction::IntToPtr: // Deliberate fall-through.
3243 case Instruction::PtrToInt: {
3244 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3245 EVT DstVT = TLI.getValueType(DL, I->getType());
3246 if (DstVT.bitsGT(SrcVT))
3247 return X86SelectZExt(I);
3248 if (DstVT.bitsLT(SrcVT))
3249 return X86SelectTrunc(I);
3250 unsigned Reg = getRegForValue(I->getOperand(0));
3251 if (Reg == 0) return false;
3252 updateValueMap(I, Reg);
3260 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3264 uint64_t Imm = CI->getZExtValue();
3266 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3267 switch (VT.SimpleTy) {
3268 default: llvm_unreachable("Unexpected value type");
3271 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3274 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3279 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3281 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3282 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3289 switch (VT.SimpleTy) {
3290 default: llvm_unreachable("Unexpected value type");
3291 case MVT::i1: VT = MVT::i8; // fall-through
3292 case MVT::i8: Opc = X86::MOV8ri; break;
3293 case MVT::i16: Opc = X86::MOV16ri; break;
3294 case MVT::i32: Opc = X86::MOV32ri; break;
3296 if (isUInt<32>(Imm))
3298 else if (isInt<32>(Imm))
3299 Opc = X86::MOV64ri32;
3305 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3306 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3307 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3308 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3309 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3310 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3313 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3316 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3317 if (CFP->isNullValue())
3318 return fastMaterializeFloatZero(CFP);
3320 // Can't handle alternate code models yet.
3321 CodeModel::Model CM = TM.getCodeModel();
3322 if (CM != CodeModel::Small && CM != CodeModel::Large)
3325 // Get opcode and regclass of the output for the given load instruction.
3327 const TargetRegisterClass *RC = nullptr;
3328 switch (VT.SimpleTy) {
3331 if (X86ScalarSSEf32) {
3332 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3333 RC = &X86::FR32RegClass;
3335 Opc = X86::LD_Fp32m;
3336 RC = &X86::RFP32RegClass;
3340 if (X86ScalarSSEf64) {
3341 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3342 RC = &X86::FR64RegClass;
3344 Opc = X86::LD_Fp64m;
3345 RC = &X86::RFP64RegClass;
3349 // No f80 support yet.
3353 // MachineConstantPool wants an explicit alignment.
3354 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3356 // Alignment of vector types. FIXME!
3357 Align = DL.getTypeAllocSize(CFP->getType());
3360 // x86-32 PIC requires a PIC base register for constant pools.
3361 unsigned PICBase = 0;
3362 unsigned char OpFlag = 0;
3363 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3364 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3365 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3366 } else if (Subtarget->isPICStyleGOT()) {
3367 OpFlag = X86II::MO_GOTOFF;
3368 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3369 } else if (Subtarget->isPICStyleRIPRel() &&
3370 TM.getCodeModel() == CodeModel::Small) {
3374 // Create the load from the constant pool.
3375 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3376 unsigned ResultReg = createResultReg(RC);
3378 if (CM == CodeModel::Large) {
3379 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3382 .addConstantPoolIndex(CPI, 0, OpFlag);
3383 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3384 TII.get(Opc), ResultReg);
3385 addDirectMem(MIB, AddrReg);
3386 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3387 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3388 DL.getPointerSize(), Align);
3389 MIB->addMemOperand(*FuncInfo.MF, MMO);
3393 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3394 TII.get(Opc), ResultReg),
3395 CPI, PICBase, OpFlag);
3399 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3400 // Can't handle alternate code models yet.
3401 if (TM.getCodeModel() != CodeModel::Small)
3404 // Materialize addresses with LEA/MOV instructions.
3406 if (X86SelectAddress(GV, AM)) {
3407 // If the expression is just a basereg, then we're done, otherwise we need
3409 if (AM.BaseType == X86AddressMode::RegBase &&
3410 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3413 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3414 if (TM.getRelocationModel() == Reloc::Static &&
3415 TLI.getPointerTy(DL) == MVT::i64) {
3416 // The displacement code could be more than 32 bits away so we need to use
3417 // an instruction with a 64 bit immediate
3418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3420 .addGlobalAddress(GV);
3423 TLI.getPointerTy(DL) == MVT::i32
3424 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3426 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3427 TII.get(Opc), ResultReg), AM);
3434 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3435 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3437 // Only handle simple types.
3438 if (!CEVT.isSimple())
3440 MVT VT = CEVT.getSimpleVT();
3442 if (const auto *CI = dyn_cast<ConstantInt>(C))
3443 return X86MaterializeInt(CI, VT);
3444 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3445 return X86MaterializeFP(CFP, VT);
3446 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3447 return X86MaterializeGV(GV, VT);
3452 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3453 // Fail on dynamic allocas. At this point, getRegForValue has already
3454 // checked its CSE maps, so if we're here trying to handle a dynamic
3455 // alloca, we're not going to succeed. X86SelectAddress has a
3456 // check for dynamic allocas, because it's called directly from
3457 // various places, but targetMaterializeAlloca also needs a check
3458 // in order to avoid recursion between getRegForValue,
3459 // X86SelectAddrss, and targetMaterializeAlloca.
3460 if (!FuncInfo.StaticAllocaMap.count(C))
3462 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3465 if (!X86SelectAddress(C, AM))
3468 TLI.getPointerTy(DL) == MVT::i32
3469 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3471 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3472 unsigned ResultReg = createResultReg(RC);
3473 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3474 TII.get(Opc), ResultReg), AM);
3478 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3480 if (!isTypeLegal(CF->getType(), VT))
3483 // Get opcode and regclass for the given zero.
3485 const TargetRegisterClass *RC = nullptr;
3486 switch (VT.SimpleTy) {
3489 if (X86ScalarSSEf32) {
3490 Opc = X86::FsFLD0SS;
3491 RC = &X86::FR32RegClass;
3493 Opc = X86::LD_Fp032;
3494 RC = &X86::RFP32RegClass;
3498 if (X86ScalarSSEf64) {
3499 Opc = X86::FsFLD0SD;
3500 RC = &X86::FR64RegClass;
3502 Opc = X86::LD_Fp064;
3503 RC = &X86::RFP64RegClass;
3507 // No f80 support yet.
3511 unsigned ResultReg = createResultReg(RC);
3512 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3517 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3518 const LoadInst *LI) {
3519 const Value *Ptr = LI->getPointerOperand();
3521 if (!X86SelectAddress(Ptr, AM))
3524 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3526 unsigned Size = DL.getTypeAllocSize(LI->getType());
3527 unsigned Alignment = LI->getAlignment();
3529 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3530 Alignment = DL.getABITypeAlignment(LI->getType());
3532 SmallVector<MachineOperand, 8> AddrOps;
3533 AM.getFullAddress(AddrOps);
3535 MachineInstr *Result = XII.foldMemoryOperandImpl(
3536 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3537 /*AllowCommute=*/true);
3541 // The index register could be in the wrong register class. Unfortunately,
3542 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3543 // to just look at OpNo + the offset to the index reg. We actually need to
3544 // scan the instruction to find the index reg and see if its the correct reg
3546 unsigned OperandNo = 0;
3547 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3548 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3549 MachineOperand &MO = *I;
3550 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3552 // Found the index reg, now try to rewrite it.
3553 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3554 MO.getReg(), OperandNo);
3555 if (IndexReg == MO.getReg())
3557 MO.setReg(IndexReg);
3560 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3561 MI->eraseFromParent();
3567 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3568 const TargetLibraryInfo *libInfo) {
3569 return new X86FastISel(funcInfo, libInfo);