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 bool HasSSE2 = Subtarget->hasSSE2();
437 bool HasAVX = Subtarget->hasAVX();
438 bool IsNonTemporal = MMO && MMO->isNonTemporal();
440 // Get opcode and regclass of the output for the given store instruction.
442 switch (VT.getSimpleVT().SimpleTy) {
443 case MVT::f80: // No f80 support yet.
444 default: return false;
446 // Mask out all but lowest bit.
447 unsigned AndResult = createResultReg(&X86::GR8RegClass);
448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
449 TII.get(X86::AND8ri), AndResult)
450 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
453 // FALLTHROUGH, handling i1 as i8.
454 case MVT::i8: Opc = X86::MOV8mr; break;
455 case MVT::i16: Opc = X86::MOV16mr; break;
457 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
460 // Must be in x86-64 mode.
461 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
464 Opc = X86ScalarSSEf32 ?
465 (HasAVX ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
468 Opc = X86ScalarSSEf64 ?
469 (HasAVX ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
474 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
476 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
478 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
483 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
485 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
487 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
495 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
497 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
499 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
503 MachineInstrBuilder MIB =
504 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
505 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
507 MIB->addMemOperand(*FuncInfo.MF, MMO);
512 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
514 MachineMemOperand *MMO, bool Aligned) {
515 // Handle 'null' like i32/i64 0.
516 if (isa<ConstantPointerNull>(Val))
517 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
519 // If this is a store of a simple constant, fold the constant into the store.
520 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
523 switch (VT.getSimpleVT().SimpleTy) {
525 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
526 case MVT::i8: Opc = X86::MOV8mi; break;
527 case MVT::i16: Opc = X86::MOV16mi; break;
528 case MVT::i32: Opc = X86::MOV32mi; break;
530 // Must be a 32-bit sign extended value.
531 if (isInt<32>(CI->getSExtValue()))
532 Opc = X86::MOV64mi32;
537 MachineInstrBuilder MIB =
538 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
539 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
540 : CI->getZExtValue());
542 MIB->addMemOperand(*FuncInfo.MF, MMO);
547 unsigned ValReg = getRegForValue(Val);
551 bool ValKill = hasTrivialKill(Val);
552 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
555 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
556 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
557 /// ISD::SIGN_EXTEND).
558 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
559 unsigned Src, EVT SrcVT,
560 unsigned &ResultReg) {
561 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
562 Src, /*TODO: Kill=*/false);
570 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
571 // Handle constant address.
572 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
573 // Can't handle alternate code models yet.
574 if (TM.getCodeModel() != CodeModel::Small)
577 // Can't handle TLS yet.
578 if (GV->isThreadLocal())
581 // RIP-relative addresses can't have additional register operands, so if
582 // we've already folded stuff into the addressing mode, just force the
583 // global value into its own register, which we can use as the basereg.
584 if (!Subtarget->isPICStyleRIPRel() ||
585 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
586 // Okay, we've committed to selecting this global. Set up the address.
589 // Allow the subtarget to classify the global.
590 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
592 // If this reference is relative to the pic base, set it now.
593 if (isGlobalRelativeToPICBase(GVFlags)) {
594 // FIXME: How do we know Base.Reg is free??
595 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
598 // Unless the ABI requires an extra load, return a direct reference to
600 if (!isGlobalStubReference(GVFlags)) {
601 if (Subtarget->isPICStyleRIPRel()) {
602 // Use rip-relative addressing if we can. Above we verified that the
603 // base and index registers are unused.
604 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
605 AM.Base.Reg = X86::RIP;
607 AM.GVOpFlags = GVFlags;
611 // Ok, we need to do a load from a stub. If we've already loaded from
612 // this stub, reuse the loaded pointer, otherwise emit the load now.
613 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
615 if (I != LocalValueMap.end() && I->second != 0) {
618 // Issue load from stub.
620 const TargetRegisterClass *RC = nullptr;
621 X86AddressMode StubAM;
622 StubAM.Base.Reg = AM.Base.Reg;
624 StubAM.GVOpFlags = GVFlags;
626 // Prepare for inserting code in the local-value area.
627 SavePoint SaveInsertPt = enterLocalValueArea();
629 if (TLI.getPointerTy(DL) == MVT::i64) {
631 RC = &X86::GR64RegClass;
633 if (Subtarget->isPICStyleRIPRel())
634 StubAM.Base.Reg = X86::RIP;
637 RC = &X86::GR32RegClass;
640 LoadReg = createResultReg(RC);
641 MachineInstrBuilder LoadMI =
642 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
643 addFullAddress(LoadMI, StubAM);
645 // Ok, back to normal mode.
646 leaveLocalValueArea(SaveInsertPt);
648 // Prevent loading GV stub multiple times in same MBB.
649 LocalValueMap[V] = LoadReg;
652 // Now construct the final address. Note that the Disp, Scale,
653 // and Index values may already be set here.
654 AM.Base.Reg = LoadReg;
660 // If all else fails, try to materialize the value in a register.
661 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
662 if (AM.Base.Reg == 0) {
663 AM.Base.Reg = getRegForValue(V);
664 return AM.Base.Reg != 0;
666 if (AM.IndexReg == 0) {
667 assert(AM.Scale == 1 && "Scale with no index!");
668 AM.IndexReg = getRegForValue(V);
669 return AM.IndexReg != 0;
676 /// X86SelectAddress - Attempt to fill in an address from the given value.
678 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
679 SmallVector<const Value *, 32> GEPs;
681 const User *U = nullptr;
682 unsigned Opcode = Instruction::UserOp1;
683 if (const Instruction *I = dyn_cast<Instruction>(V)) {
684 // Don't walk into other basic blocks; it's possible we haven't
685 // visited them yet, so the instructions may not yet be assigned
686 // virtual registers.
687 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
688 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
689 Opcode = I->getOpcode();
692 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
693 Opcode = C->getOpcode();
697 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
698 if (Ty->getAddressSpace() > 255)
699 // Fast instruction selection doesn't support the special
705 case Instruction::BitCast:
706 // Look past bitcasts.
707 return X86SelectAddress(U->getOperand(0), AM);
709 case Instruction::IntToPtr:
710 // Look past no-op inttoptrs.
711 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
712 TLI.getPointerTy(DL))
713 return X86SelectAddress(U->getOperand(0), AM);
716 case Instruction::PtrToInt:
717 // Look past no-op ptrtoints.
718 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
719 return X86SelectAddress(U->getOperand(0), AM);
722 case Instruction::Alloca: {
723 // Do static allocas.
724 const AllocaInst *A = cast<AllocaInst>(V);
725 DenseMap<const AllocaInst *, int>::iterator SI =
726 FuncInfo.StaticAllocaMap.find(A);
727 if (SI != FuncInfo.StaticAllocaMap.end()) {
728 AM.BaseType = X86AddressMode::FrameIndexBase;
729 AM.Base.FrameIndex = SI->second;
735 case Instruction::Add: {
736 // Adds of constants are common and easy enough.
737 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
738 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
739 // They have to fit in the 32-bit signed displacement field though.
740 if (isInt<32>(Disp)) {
741 AM.Disp = (uint32_t)Disp;
742 return X86SelectAddress(U->getOperand(0), AM);
748 case Instruction::GetElementPtr: {
749 X86AddressMode SavedAM = AM;
751 // Pattern-match simple GEPs.
752 uint64_t Disp = (int32_t)AM.Disp;
753 unsigned IndexReg = AM.IndexReg;
754 unsigned Scale = AM.Scale;
755 gep_type_iterator GTI = gep_type_begin(U);
756 // Iterate through the indices, folding what we can. Constants can be
757 // folded, and one dynamic index can be handled, if the scale is supported.
758 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
759 i != e; ++i, ++GTI) {
760 const Value *Op = *i;
761 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
762 const StructLayout *SL = DL.getStructLayout(STy);
763 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
767 // A array/variable index is always of the form i*S where S is the
768 // constant scale size. See if we can push the scale into immediates.
769 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
771 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
772 // Constant-offset addressing.
773 Disp += CI->getSExtValue() * S;
776 if (canFoldAddIntoGEP(U, Op)) {
777 // A compatible add with a constant operand. Fold the constant.
779 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
780 Disp += CI->getSExtValue() * S;
781 // Iterate on the other operand.
782 Op = cast<AddOperator>(Op)->getOperand(0);
786 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
787 (S == 1 || S == 2 || S == 4 || S == 8)) {
788 // Scaled-index addressing.
790 IndexReg = getRegForGEPIndex(Op).first;
796 goto unsupported_gep;
800 // Check for displacement overflow.
801 if (!isInt<32>(Disp))
804 AM.IndexReg = IndexReg;
806 AM.Disp = (uint32_t)Disp;
809 if (const GetElementPtrInst *GEP =
810 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
811 // Ok, the GEP indices were covered by constant-offset and scaled-index
812 // addressing. Update the address state and move on to examining the base.
815 } else if (X86SelectAddress(U->getOperand(0), AM)) {
819 // If we couldn't merge the gep value into this addr mode, revert back to
820 // our address and just match the value instead of completely failing.
823 for (SmallVectorImpl<const Value *>::reverse_iterator
824 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
825 if (handleConstantAddresses(*I, AM))
830 // Ok, the GEP indices weren't all covered.
835 return handleConstantAddresses(V, AM);
838 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
840 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
841 const User *U = nullptr;
842 unsigned Opcode = Instruction::UserOp1;
843 const Instruction *I = dyn_cast<Instruction>(V);
844 // Record if the value is defined in the same basic block.
846 // This information is crucial to know whether or not folding an
848 // Indeed, FastISel generates or reuses a virtual register for all
849 // operands of all instructions it selects. Obviously, the definition and
850 // its uses must use the same virtual register otherwise the produced
851 // code is incorrect.
852 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
853 // registers for values that are alive across basic blocks. This ensures
854 // that the values are consistently set between across basic block, even
855 // if different instruction selection mechanisms are used (e.g., a mix of
856 // SDISel and FastISel).
857 // For values local to a basic block, the instruction selection process
858 // generates these virtual registers with whatever method is appropriate
859 // for its needs. In particular, FastISel and SDISel do not share the way
860 // local virtual registers are set.
861 // Therefore, this is impossible (or at least unsafe) to share values
862 // between basic blocks unless they use the same instruction selection
863 // method, which is not guarantee for X86.
864 // Moreover, things like hasOneUse could not be used accurately, if we
865 // allow to reference values across basic blocks whereas they are not
866 // alive across basic blocks initially.
869 Opcode = I->getOpcode();
871 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
872 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
873 Opcode = C->getOpcode();
879 case Instruction::BitCast:
880 // Look past bitcasts if its operand is in the same BB.
882 return X86SelectCallAddress(U->getOperand(0), AM);
885 case Instruction::IntToPtr:
886 // Look past no-op inttoptrs if its operand is in the same BB.
888 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
889 TLI.getPointerTy(DL))
890 return X86SelectCallAddress(U->getOperand(0), AM);
893 case Instruction::PtrToInt:
894 // Look past no-op ptrtoints if its operand is in the same BB.
895 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
896 return X86SelectCallAddress(U->getOperand(0), AM);
900 // Handle constant address.
901 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
902 // Can't handle alternate code models yet.
903 if (TM.getCodeModel() != CodeModel::Small)
906 // RIP-relative addresses can't have additional register operands.
907 if (Subtarget->isPICStyleRIPRel() &&
908 (AM.Base.Reg != 0 || AM.IndexReg != 0))
911 // Can't handle DLL Import.
912 if (GV->hasDLLImportStorageClass())
916 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
917 if (GVar->isThreadLocal())
920 // Okay, we've committed to selecting this global. Set up the basic address.
923 // No ABI requires an extra load for anything other than DLLImport, which
924 // we rejected above. Return a direct reference to the global.
925 if (Subtarget->isPICStyleRIPRel()) {
926 // Use rip-relative addressing if we can. Above we verified that the
927 // base and index registers are unused.
928 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
929 AM.Base.Reg = X86::RIP;
930 } else if (Subtarget->isPICStyleStubPIC()) {
931 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
932 } else if (Subtarget->isPICStyleGOT()) {
933 AM.GVOpFlags = X86II::MO_GOTOFF;
939 // If all else fails, try to materialize the value in a register.
940 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
941 if (AM.Base.Reg == 0) {
942 AM.Base.Reg = getRegForValue(V);
943 return AM.Base.Reg != 0;
945 if (AM.IndexReg == 0) {
946 assert(AM.Scale == 1 && "Scale with no index!");
947 AM.IndexReg = getRegForValue(V);
948 return AM.IndexReg != 0;
956 /// X86SelectStore - Select and emit code to implement store instructions.
957 bool X86FastISel::X86SelectStore(const Instruction *I) {
958 // Atomic stores need special handling.
959 const StoreInst *S = cast<StoreInst>(I);
964 const Value *Val = S->getValueOperand();
965 const Value *Ptr = S->getPointerOperand();
968 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
971 unsigned Alignment = S->getAlignment();
972 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
973 if (Alignment == 0) // Ensure that codegen never sees alignment 0
974 Alignment = ABIAlignment;
975 bool Aligned = Alignment >= ABIAlignment;
978 if (!X86SelectAddress(Ptr, AM))
981 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
984 /// X86SelectRet - Select and emit code to implement ret instructions.
985 bool X86FastISel::X86SelectRet(const Instruction *I) {
986 const ReturnInst *Ret = cast<ReturnInst>(I);
987 const Function &F = *I->getParent()->getParent();
988 const X86MachineFunctionInfo *X86MFInfo =
989 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
991 if (!FuncInfo.CanLowerReturn)
994 CallingConv::ID CC = F.getCallingConv();
995 if (CC != CallingConv::C &&
996 CC != CallingConv::Fast &&
997 CC != CallingConv::X86_FastCall &&
998 CC != CallingConv::X86_64_SysV)
1001 if (Subtarget->isCallingConvWin64(CC))
1004 // Don't handle popping bytes on return for now.
1005 if (X86MFInfo->getBytesToPopOnReturn() != 0)
1008 // fastcc with -tailcallopt is intended to provide a guaranteed
1009 // tail call optimization. Fastisel doesn't know how to do that.
1010 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1013 // Let SDISel handle vararg functions.
1017 // Build a list of return value registers.
1018 SmallVector<unsigned, 4> RetRegs;
1020 if (Ret->getNumOperands() > 0) {
1021 SmallVector<ISD::OutputArg, 4> Outs;
1022 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1024 // Analyze operands of the call, assigning locations to each operand.
1025 SmallVector<CCValAssign, 16> ValLocs;
1026 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1027 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1029 const Value *RV = Ret->getOperand(0);
1030 unsigned Reg = getRegForValue(RV);
1034 // Only handle a single return value for now.
1035 if (ValLocs.size() != 1)
1038 CCValAssign &VA = ValLocs[0];
1040 // Don't bother handling odd stuff for now.
1041 if (VA.getLocInfo() != CCValAssign::Full)
1043 // Only handle register returns for now.
1047 // The calling-convention tables for x87 returns don't tell
1049 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1052 unsigned SrcReg = Reg + VA.getValNo();
1053 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1054 EVT DstVT = VA.getValVT();
1055 // Special handling for extended integers.
1056 if (SrcVT != DstVT) {
1057 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1060 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1063 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1065 if (SrcVT == MVT::i1) {
1066 if (Outs[0].Flags.isSExt())
1068 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1071 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1073 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1074 SrcReg, /*TODO: Kill=*/false);
1078 unsigned DstReg = VA.getLocReg();
1079 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1080 // Avoid a cross-class copy. This is very unlikely.
1081 if (!SrcRC->contains(DstReg))
1083 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1084 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1086 // Add register to return instruction.
1087 RetRegs.push_back(VA.getLocReg());
1090 // The x86-64 ABI for returning structs by value requires that we copy
1091 // the sret argument into %rax for the return. We saved the argument into
1092 // a virtual register in the entry block, so now we copy the value out
1093 // and into %rax. We also do the same with %eax for Win32.
1094 if (F.hasStructRetAttr() &&
1095 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1096 unsigned Reg = X86MFInfo->getSRetReturnReg();
1098 "SRetReturnReg should have been set in LowerFormalArguments()!");
1099 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1100 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1101 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1102 RetRegs.push_back(RetReg);
1105 // Now emit the RET.
1106 MachineInstrBuilder MIB =
1107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1108 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1109 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1110 MIB.addReg(RetRegs[i], RegState::Implicit);
1114 /// X86SelectLoad - Select and emit code to implement load instructions.
1116 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1117 const LoadInst *LI = cast<LoadInst>(I);
1119 // Atomic loads need special handling.
1124 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1127 const Value *Ptr = LI->getPointerOperand();
1130 if (!X86SelectAddress(Ptr, AM))
1133 unsigned Alignment = LI->getAlignment();
1134 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1135 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1136 Alignment = ABIAlignment;
1138 unsigned ResultReg = 0;
1139 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1143 updateValueMap(I, ResultReg);
1147 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1148 bool HasAVX = Subtarget->hasAVX();
1149 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1150 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1152 switch (VT.getSimpleVT().SimpleTy) {
1154 case MVT::i8: return X86::CMP8rr;
1155 case MVT::i16: return X86::CMP16rr;
1156 case MVT::i32: return X86::CMP32rr;
1157 case MVT::i64: return X86::CMP64rr;
1159 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1161 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1165 /// If we have a comparison with RHS as the RHS of the comparison, return an
1166 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1167 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1168 int64_t Val = RHSC->getSExtValue();
1169 switch (VT.getSimpleVT().SimpleTy) {
1170 // Otherwise, we can't fold the immediate into this comparison.
1177 return X86::CMP16ri8;
1178 return X86::CMP16ri;
1181 return X86::CMP32ri8;
1182 return X86::CMP32ri;
1185 return X86::CMP64ri8;
1186 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1189 return X86::CMP64ri32;
1194 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1195 EVT VT, DebugLoc CurDbgLoc) {
1196 unsigned Op0Reg = getRegForValue(Op0);
1197 if (Op0Reg == 0) return false;
1199 // Handle 'null' like i32/i64 0.
1200 if (isa<ConstantPointerNull>(Op1))
1201 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1203 // We have two options: compare with register or immediate. If the RHS of
1204 // the compare is an immediate that we can fold into this compare, use
1205 // CMPri, otherwise use CMPrr.
1206 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1207 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1210 .addImm(Op1C->getSExtValue());
1215 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1216 if (CompareOpc == 0) return false;
1218 unsigned Op1Reg = getRegForValue(Op1);
1219 if (Op1Reg == 0) return false;
1220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1227 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1228 const CmpInst *CI = cast<CmpInst>(I);
1231 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1234 // Try to optimize or fold the cmp.
1235 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1236 unsigned ResultReg = 0;
1237 switch (Predicate) {
1239 case CmpInst::FCMP_FALSE: {
1240 ResultReg = createResultReg(&X86::GR32RegClass);
1241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1243 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1249 case CmpInst::FCMP_TRUE: {
1250 ResultReg = createResultReg(&X86::GR8RegClass);
1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1252 ResultReg).addImm(1);
1258 updateValueMap(I, ResultReg);
1262 const Value *LHS = CI->getOperand(0);
1263 const Value *RHS = CI->getOperand(1);
1265 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1266 // We don't have to materialize a zero constant for this case and can just use
1267 // %x again on the RHS.
1268 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1269 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1270 if (RHSC && RHSC->isNullValue())
1274 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1275 static unsigned SETFOpcTable[2][3] = {
1276 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1277 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1279 unsigned *SETFOpc = nullptr;
1280 switch (Predicate) {
1282 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1283 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1286 ResultReg = createResultReg(&X86::GR8RegClass);
1288 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1291 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1292 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1298 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1299 updateValueMap(I, ResultReg);
1305 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1306 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1307 unsigned Opc = X86::getSETFromCond(CC);
1310 std::swap(LHS, RHS);
1312 // Emit a compare of LHS/RHS.
1313 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1317 updateValueMap(I, ResultReg);
1321 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1322 EVT DstVT = TLI.getValueType(DL, I->getType());
1323 if (!TLI.isTypeLegal(DstVT))
1326 unsigned ResultReg = getRegForValue(I->getOperand(0));
1330 // Handle zero-extension from i1 to i8, which is common.
1331 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1332 if (SrcVT.SimpleTy == MVT::i1) {
1333 // Set the high bits to zero.
1334 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1341 if (DstVT == MVT::i64) {
1342 // Handle extension to 64-bits via sub-register shenanigans.
1345 switch (SrcVT.SimpleTy) {
1346 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1347 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1348 case MVT::i32: MovInst = X86::MOV32rr; break;
1349 default: llvm_unreachable("Unexpected zext to i64 source type");
1352 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1353 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1356 ResultReg = createResultReg(&X86::GR64RegClass);
1357 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1359 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1360 } else if (DstVT != MVT::i8) {
1361 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1362 ResultReg, /*Kill=*/true);
1367 updateValueMap(I, ResultReg);
1371 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1372 // Unconditional branches are selected by tablegen-generated code.
1373 // Handle a conditional branch.
1374 const BranchInst *BI = cast<BranchInst>(I);
1375 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1376 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1378 // Fold the common case of a conditional branch with a comparison
1379 // in the same block (values defined on other blocks may not have
1380 // initialized registers).
1382 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1383 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1384 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1386 // Try to optimize or fold the cmp.
1387 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1388 switch (Predicate) {
1390 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1391 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1394 const Value *CmpLHS = CI->getOperand(0);
1395 const Value *CmpRHS = CI->getOperand(1);
1397 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1399 // We don't have to materialize a zero constant for this case and can just
1400 // use %x again on the RHS.
1401 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1402 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1403 if (CmpRHSC && CmpRHSC->isNullValue())
1407 // Try to take advantage of fallthrough opportunities.
1408 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1409 std::swap(TrueMBB, FalseMBB);
1410 Predicate = CmpInst::getInversePredicate(Predicate);
1413 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1414 // code check. Instead two branch instructions are required to check all
1415 // the flags. First we change the predicate to a supported condition code,
1416 // which will be the first branch. Later one we will emit the second
1418 bool NeedExtraBranch = false;
1419 switch (Predicate) {
1421 case CmpInst::FCMP_OEQ:
1422 std::swap(TrueMBB, FalseMBB); // fall-through
1423 case CmpInst::FCMP_UNE:
1424 NeedExtraBranch = true;
1425 Predicate = CmpInst::FCMP_ONE;
1431 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1432 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1434 BranchOpc = X86::GetCondBranchFromCond(CC);
1436 std::swap(CmpLHS, CmpRHS);
1438 // Emit a compare of the LHS and RHS, setting the flags.
1439 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1445 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1447 if (NeedExtraBranch) {
1448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1452 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1455 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1456 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1457 // typically happen for _Bool and C++ bools.
1459 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1460 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1461 unsigned TestOpc = 0;
1462 switch (SourceVT.SimpleTy) {
1464 case MVT::i8: TestOpc = X86::TEST8ri; break;
1465 case MVT::i16: TestOpc = X86::TEST16ri; break;
1466 case MVT::i32: TestOpc = X86::TEST32ri; break;
1467 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1470 unsigned OpReg = getRegForValue(TI->getOperand(0));
1471 if (OpReg == 0) return false;
1472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1473 .addReg(OpReg).addImm(1);
1475 unsigned JmpOpc = X86::JNE_1;
1476 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1477 std::swap(TrueMBB, FalseMBB);
1481 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1484 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1488 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1489 // Fake request the condition, otherwise the intrinsic might be completely
1491 unsigned TmpReg = getRegForValue(BI->getCondition());
1495 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1499 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1503 // Otherwise do a clumsy setcc and re-test it.
1504 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1505 // in an explicit cast, so make sure to handle that correctly.
1506 unsigned OpReg = getRegForValue(BI->getCondition());
1507 if (OpReg == 0) return false;
1509 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1510 .addReg(OpReg).addImm(1);
1511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1513 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1517 bool X86FastISel::X86SelectShift(const Instruction *I) {
1518 unsigned CReg = 0, OpReg = 0;
1519 const TargetRegisterClass *RC = nullptr;
1520 if (I->getType()->isIntegerTy(8)) {
1522 RC = &X86::GR8RegClass;
1523 switch (I->getOpcode()) {
1524 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1525 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1526 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1527 default: return false;
1529 } else if (I->getType()->isIntegerTy(16)) {
1531 RC = &X86::GR16RegClass;
1532 switch (I->getOpcode()) {
1533 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1534 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1535 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1536 default: return false;
1538 } else if (I->getType()->isIntegerTy(32)) {
1540 RC = &X86::GR32RegClass;
1541 switch (I->getOpcode()) {
1542 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1543 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1544 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1545 default: return false;
1547 } else if (I->getType()->isIntegerTy(64)) {
1549 RC = &X86::GR64RegClass;
1550 switch (I->getOpcode()) {
1551 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1552 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1553 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1554 default: return false;
1561 if (!isTypeLegal(I->getType(), VT))
1564 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1565 if (Op0Reg == 0) return false;
1567 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1568 if (Op1Reg == 0) return false;
1569 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1570 CReg).addReg(Op1Reg);
1572 // The shift instruction uses X86::CL. If we defined a super-register
1573 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1574 if (CReg != X86::CL)
1575 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1576 TII.get(TargetOpcode::KILL), X86::CL)
1577 .addReg(CReg, RegState::Kill);
1579 unsigned ResultReg = createResultReg(RC);
1580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1582 updateValueMap(I, ResultReg);
1586 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1587 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1588 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1589 const static bool S = true; // IsSigned
1590 const static bool U = false; // !IsSigned
1591 const static unsigned Copy = TargetOpcode::COPY;
1592 // For the X86 DIV/IDIV instruction, in most cases the dividend
1593 // (numerator) must be in a specific register pair highreg:lowreg,
1594 // producing the quotient in lowreg and the remainder in highreg.
1595 // For most data types, to set up the instruction, the dividend is
1596 // copied into lowreg, and lowreg is sign-extended or zero-extended
1597 // into highreg. The exception is i8, where the dividend is defined
1598 // as a single register rather than a register pair, and we
1599 // therefore directly sign-extend or zero-extend the dividend into
1600 // lowreg, instead of copying, and ignore the highreg.
1601 const static struct DivRemEntry {
1602 // The following portion depends only on the data type.
1603 const TargetRegisterClass *RC;
1604 unsigned LowInReg; // low part of the register pair
1605 unsigned HighInReg; // high part of the register pair
1606 // The following portion depends on both the data type and the operation.
1607 struct DivRemResult {
1608 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1609 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1610 // highreg, or copying a zero into highreg.
1611 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1612 // zero/sign-extending into lowreg for i8.
1613 unsigned DivRemResultReg; // Register containing the desired result.
1614 bool IsOpSigned; // Whether to use signed or unsigned form.
1615 } ResultTable[NumOps];
1616 } OpTable[NumTypes] = {
1617 { &X86::GR8RegClass, X86::AX, 0, {
1618 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1619 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1620 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1621 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1624 { &X86::GR16RegClass, X86::AX, X86::DX, {
1625 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1626 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1627 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1628 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1631 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1632 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1633 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1634 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1635 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1638 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1639 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1640 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1641 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1642 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1648 if (!isTypeLegal(I->getType(), VT))
1651 unsigned TypeIndex, OpIndex;
1652 switch (VT.SimpleTy) {
1653 default: return false;
1654 case MVT::i8: TypeIndex = 0; break;
1655 case MVT::i16: TypeIndex = 1; break;
1656 case MVT::i32: TypeIndex = 2; break;
1657 case MVT::i64: TypeIndex = 3;
1658 if (!Subtarget->is64Bit())
1663 switch (I->getOpcode()) {
1664 default: llvm_unreachable("Unexpected div/rem opcode");
1665 case Instruction::SDiv: OpIndex = 0; break;
1666 case Instruction::SRem: OpIndex = 1; break;
1667 case Instruction::UDiv: OpIndex = 2; break;
1668 case Instruction::URem: OpIndex = 3; break;
1671 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1672 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1673 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1676 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1680 // Move op0 into low-order input register.
1681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1682 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1683 // Zero-extend or sign-extend into high-order input register.
1684 if (OpEntry.OpSignExtend) {
1685 if (OpEntry.IsOpSigned)
1686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1687 TII.get(OpEntry.OpSignExtend));
1689 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1690 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1691 TII.get(X86::MOV32r0), Zero32);
1693 // Copy the zero into the appropriate sub/super/identical physical
1694 // register. Unfortunately the operations needed are not uniform enough
1695 // to fit neatly into the table above.
1696 if (VT.SimpleTy == MVT::i16) {
1697 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1698 TII.get(Copy), TypeEntry.HighInReg)
1699 .addReg(Zero32, 0, X86::sub_16bit);
1700 } else if (VT.SimpleTy == MVT::i32) {
1701 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1702 TII.get(Copy), TypeEntry.HighInReg)
1704 } else if (VT.SimpleTy == MVT::i64) {
1705 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1706 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1707 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1711 // Generate the DIV/IDIV instruction.
1712 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1713 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1714 // For i8 remainder, we can't reference AH directly, as we'll end
1715 // up with bogus copies like %R9B = COPY %AH. Reference AX
1716 // instead to prevent AH references in a REX instruction.
1718 // The current assumption of the fast register allocator is that isel
1719 // won't generate explicit references to the GPR8_NOREX registers. If
1720 // the allocator and/or the backend get enhanced to be more robust in
1721 // that regard, this can be, and should be, removed.
1722 unsigned ResultReg = 0;
1723 if ((I->getOpcode() == Instruction::SRem ||
1724 I->getOpcode() == Instruction::URem) &&
1725 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1726 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1727 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1728 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1729 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1731 // Shift AX right by 8 bits instead of using AH.
1732 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1733 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1735 // Now reference the 8-bit subreg of the result.
1736 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1737 /*Kill=*/true, X86::sub_8bit);
1739 // Copy the result out of the physreg if we haven't already.
1741 ResultReg = createResultReg(TypeEntry.RC);
1742 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1743 .addReg(OpEntry.DivRemResultReg);
1745 updateValueMap(I, ResultReg);
1750 /// \brief Emit a conditional move instruction (if the are supported) to lower
1752 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1753 // Check if the subtarget supports these instructions.
1754 if (!Subtarget->hasCMov())
1757 // FIXME: Add support for i8.
1758 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1761 const Value *Cond = I->getOperand(0);
1762 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1763 bool NeedTest = true;
1764 X86::CondCode CC = X86::COND_NE;
1766 // Optimize conditions coming from a compare if both instructions are in the
1767 // same basic block (values defined in other basic blocks may not have
1768 // initialized registers).
1769 const auto *CI = dyn_cast<CmpInst>(Cond);
1770 if (CI && (CI->getParent() == I->getParent())) {
1771 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1773 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1774 static unsigned SETFOpcTable[2][3] = {
1775 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1776 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1778 unsigned *SETFOpc = nullptr;
1779 switch (Predicate) {
1781 case CmpInst::FCMP_OEQ:
1782 SETFOpc = &SETFOpcTable[0][0];
1783 Predicate = CmpInst::ICMP_NE;
1785 case CmpInst::FCMP_UNE:
1786 SETFOpc = &SETFOpcTable[1][0];
1787 Predicate = CmpInst::ICMP_NE;
1792 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1793 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1795 const Value *CmpLHS = CI->getOperand(0);
1796 const Value *CmpRHS = CI->getOperand(1);
1798 std::swap(CmpLHS, CmpRHS);
1800 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
1801 // Emit a compare of the LHS and RHS, setting the flags.
1802 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1806 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1807 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1808 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1810 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1812 auto const &II = TII.get(SETFOpc[2]);
1813 if (II.getNumDefs()) {
1814 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1815 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1816 .addReg(FlagReg2).addReg(FlagReg1);
1818 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1819 .addReg(FlagReg2).addReg(FlagReg1);
1823 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1824 // Fake request the condition, otherwise the intrinsic might be completely
1826 unsigned TmpReg = getRegForValue(Cond);
1834 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1835 // garbage. Indeed, only the less significant bit is supposed to be
1836 // accurate. If we read more than the lsb, we may see non-zero values
1837 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1838 // the select. This is achieved by performing TEST against 1.
1839 unsigned CondReg = getRegForValue(Cond);
1842 bool CondIsKill = hasTrivialKill(Cond);
1844 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1845 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1848 const Value *LHS = I->getOperand(1);
1849 const Value *RHS = I->getOperand(2);
1851 unsigned RHSReg = getRegForValue(RHS);
1852 bool RHSIsKill = hasTrivialKill(RHS);
1854 unsigned LHSReg = getRegForValue(LHS);
1855 bool LHSIsKill = hasTrivialKill(LHS);
1857 if (!LHSReg || !RHSReg)
1860 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1861 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1863 updateValueMap(I, ResultReg);
1867 /// \brief Emit SSE or AVX instructions to lower the select.
1869 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1870 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1871 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1872 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1873 // Optimize conditions coming from a compare if both instructions are in the
1874 // same basic block (values defined in other basic blocks may not have
1875 // initialized registers).
1876 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1877 if (!CI || (CI->getParent() != I->getParent()))
1880 if (I->getType() != CI->getOperand(0)->getType() ||
1881 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1882 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1885 const Value *CmpLHS = CI->getOperand(0);
1886 const Value *CmpRHS = CI->getOperand(1);
1887 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1889 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1890 // We don't have to materialize a zero constant for this case and can just use
1891 // %x again on the RHS.
1892 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1893 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1894 if (CmpRHSC && CmpRHSC->isNullValue())
1900 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1905 std::swap(CmpLHS, CmpRHS);
1907 // Choose the SSE instruction sequence based on data type (float or double).
1908 static unsigned OpcTable[2][4] = {
1909 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1910 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1913 unsigned *Opc = nullptr;
1914 switch (RetVT.SimpleTy) {
1915 default: return false;
1916 case MVT::f32: Opc = &OpcTable[0][0]; break;
1917 case MVT::f64: Opc = &OpcTable[1][0]; break;
1920 const Value *LHS = I->getOperand(1);
1921 const Value *RHS = I->getOperand(2);
1923 unsigned LHSReg = getRegForValue(LHS);
1924 bool LHSIsKill = hasTrivialKill(LHS);
1926 unsigned RHSReg = getRegForValue(RHS);
1927 bool RHSIsKill = hasTrivialKill(RHS);
1929 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1930 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1932 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1933 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1935 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1938 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1941 if (Subtarget->hasAVX()) {
1942 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
1943 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
1945 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1946 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1947 // uses XMM0 as the selection register. That may need just as many
1948 // instructions as the AND/ANDN/OR sequence due to register moves, so
1950 unsigned CmpOpcode =
1951 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1952 unsigned BlendOpcode =
1953 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1955 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
1956 CmpRHSReg, CmpRHSIsKill, CC);
1957 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
1958 LHSReg, LHSIsKill, CmpReg, true);
1959 ResultReg = createResultReg(RC);
1960 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1961 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
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.getAlignedCallFrameSize();
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(*FuncInfo.MF, LocMemOffset),
3024 MachineMemOperand::MOStore, 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);
3255 case Instruction::BitCast: {
3256 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3257 if (!Subtarget->hasSSE2())
3260 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3261 EVT DstVT = TLI.getValueType(DL, I->getType());
3263 if (!SrcVT.isSimple() || !DstVT.isSimple())
3266 if (!SrcVT.is128BitVector() &&
3267 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3270 unsigned Reg = getRegForValue(I->getOperand(0));
3274 // No instruction is needed for conversion. Reuse the register used by
3275 // the fist operand.
3276 updateValueMap(I, Reg);
3284 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3288 uint64_t Imm = CI->getZExtValue();
3290 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3291 switch (VT.SimpleTy) {
3292 default: llvm_unreachable("Unexpected value type");
3295 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3298 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3303 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3305 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3306 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3313 switch (VT.SimpleTy) {
3314 default: llvm_unreachable("Unexpected value type");
3315 case MVT::i1: VT = MVT::i8; // fall-through
3316 case MVT::i8: Opc = X86::MOV8ri; break;
3317 case MVT::i16: Opc = X86::MOV16ri; break;
3318 case MVT::i32: Opc = X86::MOV32ri; break;
3320 if (isUInt<32>(Imm))
3322 else if (isInt<32>(Imm))
3323 Opc = X86::MOV64ri32;
3329 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3330 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3331 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3332 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3333 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3334 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3337 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3340 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3341 if (CFP->isNullValue())
3342 return fastMaterializeFloatZero(CFP);
3344 // Can't handle alternate code models yet.
3345 CodeModel::Model CM = TM.getCodeModel();
3346 if (CM != CodeModel::Small && CM != CodeModel::Large)
3349 // Get opcode and regclass of the output for the given load instruction.
3351 const TargetRegisterClass *RC = nullptr;
3352 switch (VT.SimpleTy) {
3355 if (X86ScalarSSEf32) {
3356 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3357 RC = &X86::FR32RegClass;
3359 Opc = X86::LD_Fp32m;
3360 RC = &X86::RFP32RegClass;
3364 if (X86ScalarSSEf64) {
3365 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3366 RC = &X86::FR64RegClass;
3368 Opc = X86::LD_Fp64m;
3369 RC = &X86::RFP64RegClass;
3373 // No f80 support yet.
3377 // MachineConstantPool wants an explicit alignment.
3378 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3380 // Alignment of vector types. FIXME!
3381 Align = DL.getTypeAllocSize(CFP->getType());
3384 // x86-32 PIC requires a PIC base register for constant pools.
3385 unsigned PICBase = 0;
3386 unsigned char OpFlag = 0;
3387 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3388 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3389 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3390 } else if (Subtarget->isPICStyleGOT()) {
3391 OpFlag = X86II::MO_GOTOFF;
3392 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3393 } else if (Subtarget->isPICStyleRIPRel() &&
3394 TM.getCodeModel() == CodeModel::Small) {
3398 // Create the load from the constant pool.
3399 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3400 unsigned ResultReg = createResultReg(RC);
3402 if (CM == CodeModel::Large) {
3403 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3406 .addConstantPoolIndex(CPI, 0, OpFlag);
3407 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3408 TII.get(Opc), ResultReg);
3409 addDirectMem(MIB, AddrReg);
3410 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3411 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3412 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
3413 MIB->addMemOperand(*FuncInfo.MF, MMO);
3417 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3418 TII.get(Opc), ResultReg),
3419 CPI, PICBase, OpFlag);
3423 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3424 // Can't handle alternate code models yet.
3425 if (TM.getCodeModel() != CodeModel::Small)
3428 // Materialize addresses with LEA/MOV instructions.
3430 if (X86SelectAddress(GV, AM)) {
3431 // If the expression is just a basereg, then we're done, otherwise we need
3433 if (AM.BaseType == X86AddressMode::RegBase &&
3434 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3437 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3438 if (TM.getRelocationModel() == Reloc::Static &&
3439 TLI.getPointerTy(DL) == MVT::i64) {
3440 // The displacement code could be more than 32 bits away so we need to use
3441 // an instruction with a 64 bit immediate
3442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3444 .addGlobalAddress(GV);
3447 TLI.getPointerTy(DL) == MVT::i32
3448 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3450 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3451 TII.get(Opc), ResultReg), AM);
3458 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3459 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3461 // Only handle simple types.
3462 if (!CEVT.isSimple())
3464 MVT VT = CEVT.getSimpleVT();
3466 if (const auto *CI = dyn_cast<ConstantInt>(C))
3467 return X86MaterializeInt(CI, VT);
3468 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3469 return X86MaterializeFP(CFP, VT);
3470 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3471 return X86MaterializeGV(GV, VT);
3476 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3477 // Fail on dynamic allocas. At this point, getRegForValue has already
3478 // checked its CSE maps, so if we're here trying to handle a dynamic
3479 // alloca, we're not going to succeed. X86SelectAddress has a
3480 // check for dynamic allocas, because it's called directly from
3481 // various places, but targetMaterializeAlloca also needs a check
3482 // in order to avoid recursion between getRegForValue,
3483 // X86SelectAddrss, and targetMaterializeAlloca.
3484 if (!FuncInfo.StaticAllocaMap.count(C))
3486 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3489 if (!X86SelectAddress(C, AM))
3492 TLI.getPointerTy(DL) == MVT::i32
3493 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3495 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3496 unsigned ResultReg = createResultReg(RC);
3497 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3498 TII.get(Opc), ResultReg), AM);
3502 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3504 if (!isTypeLegal(CF->getType(), VT))
3507 // Get opcode and regclass for the given zero.
3509 const TargetRegisterClass *RC = nullptr;
3510 switch (VT.SimpleTy) {
3513 if (X86ScalarSSEf32) {
3514 Opc = X86::FsFLD0SS;
3515 RC = &X86::FR32RegClass;
3517 Opc = X86::LD_Fp032;
3518 RC = &X86::RFP32RegClass;
3522 if (X86ScalarSSEf64) {
3523 Opc = X86::FsFLD0SD;
3524 RC = &X86::FR64RegClass;
3526 Opc = X86::LD_Fp064;
3527 RC = &X86::RFP64RegClass;
3531 // No f80 support yet.
3535 unsigned ResultReg = createResultReg(RC);
3536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3541 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3542 const LoadInst *LI) {
3543 const Value *Ptr = LI->getPointerOperand();
3545 if (!X86SelectAddress(Ptr, AM))
3548 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3550 unsigned Size = DL.getTypeAllocSize(LI->getType());
3551 unsigned Alignment = LI->getAlignment();
3553 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3554 Alignment = DL.getABITypeAlignment(LI->getType());
3556 SmallVector<MachineOperand, 8> AddrOps;
3557 AM.getFullAddress(AddrOps);
3559 MachineInstr *Result = XII.foldMemoryOperandImpl(
3560 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3561 /*AllowCommute=*/true);
3565 // The index register could be in the wrong register class. Unfortunately,
3566 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3567 // to just look at OpNo + the offset to the index reg. We actually need to
3568 // scan the instruction to find the index reg and see if its the correct reg
3570 unsigned OperandNo = 0;
3571 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3572 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3573 MachineOperand &MO = *I;
3574 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3576 // Found the index reg, now try to rewrite it.
3577 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3578 MO.getReg(), OperandNo);
3579 if (IndexReg == MO.getReg())
3581 MO.setReg(IndexReg);
3584 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3585 MI->eraseFromParent();
3591 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3592 const TargetLibraryInfo *libInfo) {
3593 return new X86FastISel(funcInfo, libInfo);