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(Ty, /*HandleUnknown=*/true);
321 if (evt == MVT::Other || !evt.isSimple())
322 // Unhandled type. Halt "fast" selection and bail.
325 VT = evt.getSimpleVT();
326 // For now, require SSE/SSE2 for performing floating-point operations,
327 // since x87 requires additional work.
328 if (VT == MVT::f64 && !X86ScalarSSEf64)
330 if (VT == MVT::f32 && !X86ScalarSSEf32)
332 // Similarly, no f80 support yet.
335 // We only handle legal types. For example, on x86-32 the instruction
336 // selector contains all of the 64-bit instructions from x86-64,
337 // under the assumption that i64 won't be used if the target doesn't
339 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
342 #include "X86GenCallingConv.inc"
344 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
345 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
346 /// Return true and the result register by reference if it is possible.
347 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
348 MachineMemOperand *MMO, unsigned &ResultReg,
349 unsigned Alignment) {
350 // Get opcode and regclass of the output for the given load instruction.
352 const TargetRegisterClass *RC = nullptr;
353 switch (VT.getSimpleVT().SimpleTy) {
354 default: return false;
358 RC = &X86::GR8RegClass;
362 RC = &X86::GR16RegClass;
366 RC = &X86::GR32RegClass;
369 // Must be in x86-64 mode.
371 RC = &X86::GR64RegClass;
374 if (X86ScalarSSEf32) {
375 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
376 RC = &X86::FR32RegClass;
379 RC = &X86::RFP32RegClass;
383 if (X86ScalarSSEf64) {
384 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
385 RC = &X86::FR64RegClass;
388 RC = &X86::RFP64RegClass;
392 // No f80 support yet.
396 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
398 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
399 RC = &X86::VR128RegClass;
403 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
405 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
406 RC = &X86::VR128RegClass;
413 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
415 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
416 RC = &X86::VR128RegClass;
420 ResultReg = createResultReg(RC);
421 MachineInstrBuilder MIB =
422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
423 addFullAddress(MIB, AM);
425 MIB->addMemOperand(*FuncInfo.MF, MMO);
429 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
430 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
431 /// and a displacement offset, or a GlobalAddress,
432 /// i.e. V. Return true if it is possible.
433 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
435 MachineMemOperand *MMO, bool Aligned) {
436 // Get opcode and regclass of the output for the given store instruction.
438 switch (VT.getSimpleVT().SimpleTy) {
439 case MVT::f80: // No f80 support yet.
440 default: return false;
442 // Mask out all but lowest bit.
443 unsigned AndResult = createResultReg(&X86::GR8RegClass);
444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
445 TII.get(X86::AND8ri), AndResult)
446 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
449 // FALLTHROUGH, handling i1 as i8.
450 case MVT::i8: Opc = X86::MOV8mr; break;
451 case MVT::i16: Opc = X86::MOV16mr; break;
452 case MVT::i32: Opc = X86::MOV32mr; break;
453 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
455 Opc = X86ScalarSSEf32 ?
456 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
459 Opc = X86ScalarSSEf64 ?
460 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
464 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
466 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
470 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
472 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
479 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
481 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
485 MachineInstrBuilder MIB =
486 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
487 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
489 MIB->addMemOperand(*FuncInfo.MF, MMO);
494 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
496 MachineMemOperand *MMO, bool Aligned) {
497 // Handle 'null' like i32/i64 0.
498 if (isa<ConstantPointerNull>(Val))
499 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
501 // If this is a store of a simple constant, fold the constant into the store.
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
505 switch (VT.getSimpleVT().SimpleTy) {
507 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
508 case MVT::i8: Opc = X86::MOV8mi; break;
509 case MVT::i16: Opc = X86::MOV16mi; break;
510 case MVT::i32: Opc = X86::MOV32mi; break;
512 // Must be a 32-bit sign extended value.
513 if (isInt<32>(CI->getSExtValue()))
514 Opc = X86::MOV64mi32;
519 MachineInstrBuilder MIB =
520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
521 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
522 : CI->getZExtValue());
524 MIB->addMemOperand(*FuncInfo.MF, MMO);
529 unsigned ValReg = getRegForValue(Val);
533 bool ValKill = hasTrivialKill(Val);
534 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
537 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
538 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
539 /// ISD::SIGN_EXTEND).
540 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
541 unsigned Src, EVT SrcVT,
542 unsigned &ResultReg) {
543 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
544 Src, /*TODO: Kill=*/false);
552 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
553 // Handle constant address.
554 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
555 // Can't handle alternate code models yet.
556 if (TM.getCodeModel() != CodeModel::Small)
559 // Can't handle TLS yet.
560 if (GV->isThreadLocal())
563 // RIP-relative addresses can't have additional register operands, so if
564 // we've already folded stuff into the addressing mode, just force the
565 // global value into its own register, which we can use as the basereg.
566 if (!Subtarget->isPICStyleRIPRel() ||
567 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
568 // Okay, we've committed to selecting this global. Set up the address.
571 // Allow the subtarget to classify the global.
572 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
574 // If this reference is relative to the pic base, set it now.
575 if (isGlobalRelativeToPICBase(GVFlags)) {
576 // FIXME: How do we know Base.Reg is free??
577 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
580 // Unless the ABI requires an extra load, return a direct reference to
582 if (!isGlobalStubReference(GVFlags)) {
583 if (Subtarget->isPICStyleRIPRel()) {
584 // Use rip-relative addressing if we can. Above we verified that the
585 // base and index registers are unused.
586 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
587 AM.Base.Reg = X86::RIP;
589 AM.GVOpFlags = GVFlags;
593 // Ok, we need to do a load from a stub. If we've already loaded from
594 // this stub, reuse the loaded pointer, otherwise emit the load now.
595 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
597 if (I != LocalValueMap.end() && I->second != 0) {
600 // Issue load from stub.
602 const TargetRegisterClass *RC = nullptr;
603 X86AddressMode StubAM;
604 StubAM.Base.Reg = AM.Base.Reg;
606 StubAM.GVOpFlags = GVFlags;
608 // Prepare for inserting code in the local-value area.
609 SavePoint SaveInsertPt = enterLocalValueArea();
611 if (TLI.getPointerTy() == MVT::i64) {
613 RC = &X86::GR64RegClass;
615 if (Subtarget->isPICStyleRIPRel())
616 StubAM.Base.Reg = X86::RIP;
619 RC = &X86::GR32RegClass;
622 LoadReg = createResultReg(RC);
623 MachineInstrBuilder LoadMI =
624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
625 addFullAddress(LoadMI, StubAM);
627 // Ok, back to normal mode.
628 leaveLocalValueArea(SaveInsertPt);
630 // Prevent loading GV stub multiple times in same MBB.
631 LocalValueMap[V] = LoadReg;
634 // Now construct the final address. Note that the Disp, Scale,
635 // and Index values may already be set here.
636 AM.Base.Reg = LoadReg;
642 // If all else fails, try to materialize the value in a register.
643 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
644 if (AM.Base.Reg == 0) {
645 AM.Base.Reg = getRegForValue(V);
646 return AM.Base.Reg != 0;
648 if (AM.IndexReg == 0) {
649 assert(AM.Scale == 1 && "Scale with no index!");
650 AM.IndexReg = getRegForValue(V);
651 return AM.IndexReg != 0;
658 /// X86SelectAddress - Attempt to fill in an address from the given value.
660 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
661 SmallVector<const Value *, 32> GEPs;
663 const User *U = nullptr;
664 unsigned Opcode = Instruction::UserOp1;
665 if (const Instruction *I = dyn_cast<Instruction>(V)) {
666 // Don't walk into other basic blocks; it's possible we haven't
667 // visited them yet, so the instructions may not yet be assigned
668 // virtual registers.
669 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
670 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
671 Opcode = I->getOpcode();
674 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
675 Opcode = C->getOpcode();
679 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
680 if (Ty->getAddressSpace() > 255)
681 // Fast instruction selection doesn't support the special
687 case Instruction::BitCast:
688 // Look past bitcasts.
689 return X86SelectAddress(U->getOperand(0), AM);
691 case Instruction::IntToPtr:
692 // Look past no-op inttoptrs.
693 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
694 return X86SelectAddress(U->getOperand(0), AM);
697 case Instruction::PtrToInt:
698 // Look past no-op ptrtoints.
699 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
700 return X86SelectAddress(U->getOperand(0), AM);
703 case Instruction::Alloca: {
704 // Do static allocas.
705 const AllocaInst *A = cast<AllocaInst>(V);
706 DenseMap<const AllocaInst *, int>::iterator SI =
707 FuncInfo.StaticAllocaMap.find(A);
708 if (SI != FuncInfo.StaticAllocaMap.end()) {
709 AM.BaseType = X86AddressMode::FrameIndexBase;
710 AM.Base.FrameIndex = SI->second;
716 case Instruction::Add: {
717 // Adds of constants are common and easy enough.
718 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
719 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
720 // They have to fit in the 32-bit signed displacement field though.
721 if (isInt<32>(Disp)) {
722 AM.Disp = (uint32_t)Disp;
723 return X86SelectAddress(U->getOperand(0), AM);
729 case Instruction::GetElementPtr: {
730 X86AddressMode SavedAM = AM;
732 // Pattern-match simple GEPs.
733 uint64_t Disp = (int32_t)AM.Disp;
734 unsigned IndexReg = AM.IndexReg;
735 unsigned Scale = AM.Scale;
736 gep_type_iterator GTI = gep_type_begin(U);
737 // Iterate through the indices, folding what we can. Constants can be
738 // folded, and one dynamic index can be handled, if the scale is supported.
739 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
740 i != e; ++i, ++GTI) {
741 const Value *Op = *i;
742 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
743 const StructLayout *SL = DL.getStructLayout(STy);
744 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
748 // A array/variable index is always of the form i*S where S is the
749 // constant scale size. See if we can push the scale into immediates.
750 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
752 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
753 // Constant-offset addressing.
754 Disp += CI->getSExtValue() * S;
757 if (canFoldAddIntoGEP(U, Op)) {
758 // A compatible add with a constant operand. Fold the constant.
760 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
761 Disp += CI->getSExtValue() * S;
762 // Iterate on the other operand.
763 Op = cast<AddOperator>(Op)->getOperand(0);
767 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
768 (S == 1 || S == 2 || S == 4 || S == 8)) {
769 // Scaled-index addressing.
771 IndexReg = getRegForGEPIndex(Op).first;
777 goto unsupported_gep;
781 // Check for displacement overflow.
782 if (!isInt<32>(Disp))
785 AM.IndexReg = IndexReg;
787 AM.Disp = (uint32_t)Disp;
790 if (const GetElementPtrInst *GEP =
791 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
792 // Ok, the GEP indices were covered by constant-offset and scaled-index
793 // addressing. Update the address state and move on to examining the base.
796 } else if (X86SelectAddress(U->getOperand(0), AM)) {
800 // If we couldn't merge the gep value into this addr mode, revert back to
801 // our address and just match the value instead of completely failing.
804 for (SmallVectorImpl<const Value *>::reverse_iterator
805 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
806 if (handleConstantAddresses(*I, AM))
811 // Ok, the GEP indices weren't all covered.
816 return handleConstantAddresses(V, AM);
819 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
821 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
822 const User *U = nullptr;
823 unsigned Opcode = Instruction::UserOp1;
824 const Instruction *I = dyn_cast<Instruction>(V);
825 // Record if the value is defined in the same basic block.
827 // This information is crucial to know whether or not folding an
829 // Indeed, FastISel generates or reuses a virtual register for all
830 // operands of all instructions it selects. Obviously, the definition and
831 // its uses must use the same virtual register otherwise the produced
832 // code is incorrect.
833 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
834 // registers for values that are alive across basic blocks. This ensures
835 // that the values are consistently set between across basic block, even
836 // if different instruction selection mechanisms are used (e.g., a mix of
837 // SDISel and FastISel).
838 // For values local to a basic block, the instruction selection process
839 // generates these virtual registers with whatever method is appropriate
840 // for its needs. In particular, FastISel and SDISel do not share the way
841 // local virtual registers are set.
842 // Therefore, this is impossible (or at least unsafe) to share values
843 // between basic blocks unless they use the same instruction selection
844 // method, which is not guarantee for X86.
845 // Moreover, things like hasOneUse could not be used accurately, if we
846 // allow to reference values across basic blocks whereas they are not
847 // alive across basic blocks initially.
850 Opcode = I->getOpcode();
852 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
853 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
854 Opcode = C->getOpcode();
860 case Instruction::BitCast:
861 // Look past bitcasts if its operand is in the same BB.
863 return X86SelectCallAddress(U->getOperand(0), AM);
866 case Instruction::IntToPtr:
867 // Look past no-op inttoptrs if its operand is in the same BB.
869 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
870 return X86SelectCallAddress(U->getOperand(0), AM);
873 case Instruction::PtrToInt:
874 // Look past no-op ptrtoints if its operand is in the same BB.
876 TLI.getValueType(U->getType()) == TLI.getPointerTy())
877 return X86SelectCallAddress(U->getOperand(0), AM);
881 // Handle constant address.
882 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
883 // Can't handle alternate code models yet.
884 if (TM.getCodeModel() != CodeModel::Small)
887 // RIP-relative addresses can't have additional register operands.
888 if (Subtarget->isPICStyleRIPRel() &&
889 (AM.Base.Reg != 0 || AM.IndexReg != 0))
892 // Can't handle DLL Import.
893 if (GV->hasDLLImportStorageClass())
897 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
898 if (GVar->isThreadLocal())
901 // Okay, we've committed to selecting this global. Set up the basic address.
904 // No ABI requires an extra load for anything other than DLLImport, which
905 // we rejected above. Return a direct reference to the global.
906 if (Subtarget->isPICStyleRIPRel()) {
907 // Use rip-relative addressing if we can. Above we verified that the
908 // base and index registers are unused.
909 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
910 AM.Base.Reg = X86::RIP;
911 } else if (Subtarget->isPICStyleStubPIC()) {
912 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
913 } else if (Subtarget->isPICStyleGOT()) {
914 AM.GVOpFlags = X86II::MO_GOTOFF;
920 // If all else fails, try to materialize the value in a register.
921 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
922 if (AM.Base.Reg == 0) {
923 AM.Base.Reg = getRegForValue(V);
924 return AM.Base.Reg != 0;
926 if (AM.IndexReg == 0) {
927 assert(AM.Scale == 1 && "Scale with no index!");
928 AM.IndexReg = getRegForValue(V);
929 return AM.IndexReg != 0;
937 /// X86SelectStore - Select and emit code to implement store instructions.
938 bool X86FastISel::X86SelectStore(const Instruction *I) {
939 // Atomic stores need special handling.
940 const StoreInst *S = cast<StoreInst>(I);
945 const Value *Val = S->getValueOperand();
946 const Value *Ptr = S->getPointerOperand();
949 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
952 unsigned Alignment = S->getAlignment();
953 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
954 if (Alignment == 0) // Ensure that codegen never sees alignment 0
955 Alignment = ABIAlignment;
956 bool Aligned = Alignment >= ABIAlignment;
959 if (!X86SelectAddress(Ptr, AM))
962 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
965 /// X86SelectRet - Select and emit code to implement ret instructions.
966 bool X86FastISel::X86SelectRet(const Instruction *I) {
967 const ReturnInst *Ret = cast<ReturnInst>(I);
968 const Function &F = *I->getParent()->getParent();
969 const X86MachineFunctionInfo *X86MFInfo =
970 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
972 if (!FuncInfo.CanLowerReturn)
975 CallingConv::ID CC = F.getCallingConv();
976 if (CC != CallingConv::C &&
977 CC != CallingConv::Fast &&
978 CC != CallingConv::X86_FastCall &&
979 CC != CallingConv::X86_64_SysV)
982 if (Subtarget->isCallingConvWin64(CC))
985 // Don't handle popping bytes on return for now.
986 if (X86MFInfo->getBytesToPopOnReturn() != 0)
989 // fastcc with -tailcallopt is intended to provide a guaranteed
990 // tail call optimization. Fastisel doesn't know how to do that.
991 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
994 // Let SDISel handle vararg functions.
998 // Build a list of return value registers.
999 SmallVector<unsigned, 4> RetRegs;
1001 if (Ret->getNumOperands() > 0) {
1002 SmallVector<ISD::OutputArg, 4> Outs;
1003 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1005 // Analyze operands of the call, assigning locations to each operand.
1006 SmallVector<CCValAssign, 16> ValLocs;
1007 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1008 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1010 const Value *RV = Ret->getOperand(0);
1011 unsigned Reg = getRegForValue(RV);
1015 // Only handle a single return value for now.
1016 if (ValLocs.size() != 1)
1019 CCValAssign &VA = ValLocs[0];
1021 // Don't bother handling odd stuff for now.
1022 if (VA.getLocInfo() != CCValAssign::Full)
1024 // Only handle register returns for now.
1028 // The calling-convention tables for x87 returns don't tell
1030 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1033 unsigned SrcReg = Reg + VA.getValNo();
1034 EVT SrcVT = TLI.getValueType(RV->getType());
1035 EVT DstVT = VA.getValVT();
1036 // Special handling for extended integers.
1037 if (SrcVT != DstVT) {
1038 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1041 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1044 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1046 if (SrcVT == MVT::i1) {
1047 if (Outs[0].Flags.isSExt())
1049 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1052 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1054 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1055 SrcReg, /*TODO: Kill=*/false);
1059 unsigned DstReg = VA.getLocReg();
1060 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1061 // Avoid a cross-class copy. This is very unlikely.
1062 if (!SrcRC->contains(DstReg))
1064 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1065 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1067 // Add register to return instruction.
1068 RetRegs.push_back(VA.getLocReg());
1071 // The x86-64 ABI for returning structs by value requires that we copy
1072 // the sret argument into %rax for the return. We saved the argument into
1073 // a virtual register in the entry block, so now we copy the value out
1074 // and into %rax. We also do the same with %eax for Win32.
1075 if (F.hasStructRetAttr() &&
1076 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1077 unsigned Reg = X86MFInfo->getSRetReturnReg();
1079 "SRetReturnReg should have been set in LowerFormalArguments()!");
1080 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1081 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1082 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1083 RetRegs.push_back(RetReg);
1086 // Now emit the RET.
1087 MachineInstrBuilder MIB =
1088 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1089 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1090 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1091 MIB.addReg(RetRegs[i], RegState::Implicit);
1095 /// X86SelectLoad - Select and emit code to implement load instructions.
1097 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1098 const LoadInst *LI = cast<LoadInst>(I);
1100 // Atomic loads need special handling.
1105 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1108 const Value *Ptr = LI->getPointerOperand();
1111 if (!X86SelectAddress(Ptr, AM))
1114 unsigned Alignment = LI->getAlignment();
1115 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1116 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1117 Alignment = ABIAlignment;
1119 unsigned ResultReg = 0;
1120 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1124 updateValueMap(I, ResultReg);
1128 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1129 bool HasAVX = Subtarget->hasAVX();
1130 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1131 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1133 switch (VT.getSimpleVT().SimpleTy) {
1135 case MVT::i8: return X86::CMP8rr;
1136 case MVT::i16: return X86::CMP16rr;
1137 case MVT::i32: return X86::CMP32rr;
1138 case MVT::i64: return X86::CMP64rr;
1140 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1142 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1146 /// If we have a comparison with RHS as the RHS of the comparison, return an
1147 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1148 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1149 int64_t Val = RHSC->getSExtValue();
1150 switch (VT.getSimpleVT().SimpleTy) {
1151 // Otherwise, we can't fold the immediate into this comparison.
1158 return X86::CMP16ri8;
1159 return X86::CMP16ri;
1162 return X86::CMP32ri8;
1163 return X86::CMP32ri;
1166 return X86::CMP64ri8;
1167 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1170 return X86::CMP64ri32;
1175 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1176 EVT VT, DebugLoc CurDbgLoc) {
1177 unsigned Op0Reg = getRegForValue(Op0);
1178 if (Op0Reg == 0) return false;
1180 // Handle 'null' like i32/i64 0.
1181 if (isa<ConstantPointerNull>(Op1))
1182 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1184 // We have two options: compare with register or immediate. If the RHS of
1185 // the compare is an immediate that we can fold into this compare, use
1186 // CMPri, otherwise use CMPrr.
1187 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1188 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1191 .addImm(Op1C->getSExtValue());
1196 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1197 if (CompareOpc == 0) return false;
1199 unsigned Op1Reg = getRegForValue(Op1);
1200 if (Op1Reg == 0) return false;
1201 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1208 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1209 const CmpInst *CI = cast<CmpInst>(I);
1212 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1215 // Try to optimize or fold the cmp.
1216 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1217 unsigned ResultReg = 0;
1218 switch (Predicate) {
1220 case CmpInst::FCMP_FALSE: {
1221 ResultReg = createResultReg(&X86::GR32RegClass);
1222 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1224 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1230 case CmpInst::FCMP_TRUE: {
1231 ResultReg = createResultReg(&X86::GR8RegClass);
1232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1233 ResultReg).addImm(1);
1239 updateValueMap(I, ResultReg);
1243 const Value *LHS = CI->getOperand(0);
1244 const Value *RHS = CI->getOperand(1);
1246 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1247 // We don't have to materialize a zero constant for this case and can just use
1248 // %x again on the RHS.
1249 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1250 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1251 if (RHSC && RHSC->isNullValue())
1255 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1256 static unsigned SETFOpcTable[2][3] = {
1257 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1258 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1260 unsigned *SETFOpc = nullptr;
1261 switch (Predicate) {
1263 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1264 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1267 ResultReg = createResultReg(&X86::GR8RegClass);
1269 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1272 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1273 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1279 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1280 updateValueMap(I, ResultReg);
1286 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1287 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1288 unsigned Opc = X86::getSETFromCond(CC);
1291 std::swap(LHS, RHS);
1293 // Emit a compare of LHS/RHS.
1294 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1298 updateValueMap(I, ResultReg);
1302 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1303 EVT DstVT = TLI.getValueType(I->getType());
1304 if (!TLI.isTypeLegal(DstVT))
1307 unsigned ResultReg = getRegForValue(I->getOperand(0));
1311 // Handle zero-extension from i1 to i8, which is common.
1312 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1313 if (SrcVT.SimpleTy == MVT::i1) {
1314 // Set the high bits to zero.
1315 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1322 if (DstVT == MVT::i64) {
1323 // Handle extension to 64-bits via sub-register shenanigans.
1326 switch (SrcVT.SimpleTy) {
1327 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1328 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1329 case MVT::i32: MovInst = X86::MOV32rr; break;
1330 default: llvm_unreachable("Unexpected zext to i64 source type");
1333 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1334 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1337 ResultReg = createResultReg(&X86::GR64RegClass);
1338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1340 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1341 } else if (DstVT != MVT::i8) {
1342 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1343 ResultReg, /*Kill=*/true);
1348 updateValueMap(I, ResultReg);
1352 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1353 // Unconditional branches are selected by tablegen-generated code.
1354 // Handle a conditional branch.
1355 const BranchInst *BI = cast<BranchInst>(I);
1356 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1357 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1359 // Fold the common case of a conditional branch with a comparison
1360 // in the same block (values defined on other blocks may not have
1361 // initialized registers).
1363 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1364 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1365 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1367 // Try to optimize or fold the cmp.
1368 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1369 switch (Predicate) {
1371 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1372 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1375 const Value *CmpLHS = CI->getOperand(0);
1376 const Value *CmpRHS = CI->getOperand(1);
1378 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1380 // We don't have to materialize a zero constant for this case and can just
1381 // use %x again on the RHS.
1382 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1383 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1384 if (CmpRHSC && CmpRHSC->isNullValue())
1388 // Try to take advantage of fallthrough opportunities.
1389 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1390 std::swap(TrueMBB, FalseMBB);
1391 Predicate = CmpInst::getInversePredicate(Predicate);
1394 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1395 // code check. Instead two branch instructions are required to check all
1396 // the flags. First we change the predicate to a supported condition code,
1397 // which will be the first branch. Later one we will emit the second
1399 bool NeedExtraBranch = false;
1400 switch (Predicate) {
1402 case CmpInst::FCMP_OEQ:
1403 std::swap(TrueMBB, FalseMBB); // fall-through
1404 case CmpInst::FCMP_UNE:
1405 NeedExtraBranch = true;
1406 Predicate = CmpInst::FCMP_ONE;
1412 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1413 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1415 BranchOpc = X86::GetCondBranchFromCond(CC);
1417 std::swap(CmpLHS, CmpRHS);
1419 // Emit a compare of the LHS and RHS, setting the flags.
1420 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1426 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1428 if (NeedExtraBranch) {
1429 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1433 // Obtain the branch weight and add the TrueBB to the successor list.
1434 uint32_t BranchWeight = 0;
1436 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1437 TrueMBB->getBasicBlock());
1438 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1440 // Emits an unconditional branch to the FalseBB, obtains the branch
1441 // weight, and adds it to the successor list.
1442 fastEmitBranch(FalseMBB, DbgLoc);
1446 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1447 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1448 // typically happen for _Bool and C++ bools.
1450 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1451 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1452 unsigned TestOpc = 0;
1453 switch (SourceVT.SimpleTy) {
1455 case MVT::i8: TestOpc = X86::TEST8ri; break;
1456 case MVT::i16: TestOpc = X86::TEST16ri; break;
1457 case MVT::i32: TestOpc = X86::TEST32ri; break;
1458 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1461 unsigned OpReg = getRegForValue(TI->getOperand(0));
1462 if (OpReg == 0) return false;
1463 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1464 .addReg(OpReg).addImm(1);
1466 unsigned JmpOpc = X86::JNE_1;
1467 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1468 std::swap(TrueMBB, FalseMBB);
1472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1474 fastEmitBranch(FalseMBB, DbgLoc);
1475 uint32_t BranchWeight = 0;
1477 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1478 TrueMBB->getBasicBlock());
1479 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1483 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1484 // Fake request the condition, otherwise the intrinsic might be completely
1486 unsigned TmpReg = getRegForValue(BI->getCondition());
1490 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1494 fastEmitBranch(FalseMBB, DbgLoc);
1495 uint32_t BranchWeight = 0;
1497 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1498 TrueMBB->getBasicBlock());
1499 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
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 fastEmitBranch(FalseMBB, DbgLoc);
1514 uint32_t BranchWeight = 0;
1516 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1517 TrueMBB->getBasicBlock());
1518 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1522 bool X86FastISel::X86SelectShift(const Instruction *I) {
1523 unsigned CReg = 0, OpReg = 0;
1524 const TargetRegisterClass *RC = nullptr;
1525 if (I->getType()->isIntegerTy(8)) {
1527 RC = &X86::GR8RegClass;
1528 switch (I->getOpcode()) {
1529 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1530 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1531 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1532 default: return false;
1534 } else if (I->getType()->isIntegerTy(16)) {
1536 RC = &X86::GR16RegClass;
1537 switch (I->getOpcode()) {
1538 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1539 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1540 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1541 default: return false;
1543 } else if (I->getType()->isIntegerTy(32)) {
1545 RC = &X86::GR32RegClass;
1546 switch (I->getOpcode()) {
1547 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1548 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1549 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1550 default: return false;
1552 } else if (I->getType()->isIntegerTy(64)) {
1554 RC = &X86::GR64RegClass;
1555 switch (I->getOpcode()) {
1556 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1557 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1558 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1559 default: return false;
1566 if (!isTypeLegal(I->getType(), VT))
1569 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1570 if (Op0Reg == 0) return false;
1572 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1573 if (Op1Reg == 0) return false;
1574 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1575 CReg).addReg(Op1Reg);
1577 // The shift instruction uses X86::CL. If we defined a super-register
1578 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1579 if (CReg != X86::CL)
1580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1581 TII.get(TargetOpcode::KILL), X86::CL)
1582 .addReg(CReg, RegState::Kill);
1584 unsigned ResultReg = createResultReg(RC);
1585 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1587 updateValueMap(I, ResultReg);
1591 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1592 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1593 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1594 const static bool S = true; // IsSigned
1595 const static bool U = false; // !IsSigned
1596 const static unsigned Copy = TargetOpcode::COPY;
1597 // For the X86 DIV/IDIV instruction, in most cases the dividend
1598 // (numerator) must be in a specific register pair highreg:lowreg,
1599 // producing the quotient in lowreg and the remainder in highreg.
1600 // For most data types, to set up the instruction, the dividend is
1601 // copied into lowreg, and lowreg is sign-extended or zero-extended
1602 // into highreg. The exception is i8, where the dividend is defined
1603 // as a single register rather than a register pair, and we
1604 // therefore directly sign-extend or zero-extend the dividend into
1605 // lowreg, instead of copying, and ignore the highreg.
1606 const static struct DivRemEntry {
1607 // The following portion depends only on the data type.
1608 const TargetRegisterClass *RC;
1609 unsigned LowInReg; // low part of the register pair
1610 unsigned HighInReg; // high part of the register pair
1611 // The following portion depends on both the data type and the operation.
1612 struct DivRemResult {
1613 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1614 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1615 // highreg, or copying a zero into highreg.
1616 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1617 // zero/sign-extending into lowreg for i8.
1618 unsigned DivRemResultReg; // Register containing the desired result.
1619 bool IsOpSigned; // Whether to use signed or unsigned form.
1620 } ResultTable[NumOps];
1621 } OpTable[NumTypes] = {
1622 { &X86::GR8RegClass, X86::AX, 0, {
1623 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1624 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1625 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1626 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1629 { &X86::GR16RegClass, X86::AX, X86::DX, {
1630 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1631 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1632 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1633 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1636 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1637 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1638 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1639 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1640 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1643 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1644 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1645 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1646 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1647 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1653 if (!isTypeLegal(I->getType(), VT))
1656 unsigned TypeIndex, OpIndex;
1657 switch (VT.SimpleTy) {
1658 default: return false;
1659 case MVT::i8: TypeIndex = 0; break;
1660 case MVT::i16: TypeIndex = 1; break;
1661 case MVT::i32: TypeIndex = 2; break;
1662 case MVT::i64: TypeIndex = 3;
1663 if (!Subtarget->is64Bit())
1668 switch (I->getOpcode()) {
1669 default: llvm_unreachable("Unexpected div/rem opcode");
1670 case Instruction::SDiv: OpIndex = 0; break;
1671 case Instruction::SRem: OpIndex = 1; break;
1672 case Instruction::UDiv: OpIndex = 2; break;
1673 case Instruction::URem: OpIndex = 3; break;
1676 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1677 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1678 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1681 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1685 // Move op0 into low-order input register.
1686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1687 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1688 // Zero-extend or sign-extend into high-order input register.
1689 if (OpEntry.OpSignExtend) {
1690 if (OpEntry.IsOpSigned)
1691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1692 TII.get(OpEntry.OpSignExtend));
1694 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1695 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1696 TII.get(X86::MOV32r0), Zero32);
1698 // Copy the zero into the appropriate sub/super/identical physical
1699 // register. Unfortunately the operations needed are not uniform enough
1700 // to fit neatly into the table above.
1701 if (VT.SimpleTy == MVT::i16) {
1702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1703 TII.get(Copy), TypeEntry.HighInReg)
1704 .addReg(Zero32, 0, X86::sub_16bit);
1705 } else if (VT.SimpleTy == MVT::i32) {
1706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1707 TII.get(Copy), TypeEntry.HighInReg)
1709 } else if (VT.SimpleTy == MVT::i64) {
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1711 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1712 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1716 // Generate the DIV/IDIV instruction.
1717 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1718 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1719 // For i8 remainder, we can't reference AH directly, as we'll end
1720 // up with bogus copies like %R9B = COPY %AH. Reference AX
1721 // instead to prevent AH references in a REX instruction.
1723 // The current assumption of the fast register allocator is that isel
1724 // won't generate explicit references to the GPR8_NOREX registers. If
1725 // the allocator and/or the backend get enhanced to be more robust in
1726 // that regard, this can be, and should be, removed.
1727 unsigned ResultReg = 0;
1728 if ((I->getOpcode() == Instruction::SRem ||
1729 I->getOpcode() == Instruction::URem) &&
1730 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1731 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1732 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1733 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1734 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1736 // Shift AX right by 8 bits instead of using AH.
1737 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1738 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1740 // Now reference the 8-bit subreg of the result.
1741 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1742 /*Kill=*/true, X86::sub_8bit);
1744 // Copy the result out of the physreg if we haven't already.
1746 ResultReg = createResultReg(TypeEntry.RC);
1747 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1748 .addReg(OpEntry.DivRemResultReg);
1750 updateValueMap(I, ResultReg);
1755 /// \brief Emit a conditional move instruction (if the are supported) to lower
1757 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1758 // Check if the subtarget supports these instructions.
1759 if (!Subtarget->hasCMov())
1762 // FIXME: Add support for i8.
1763 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1766 const Value *Cond = I->getOperand(0);
1767 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1768 bool NeedTest = true;
1769 X86::CondCode CC = X86::COND_NE;
1771 // Optimize conditions coming from a compare if both instructions are in the
1772 // same basic block (values defined in other basic blocks may not have
1773 // initialized registers).
1774 const auto *CI = dyn_cast<CmpInst>(Cond);
1775 if (CI && (CI->getParent() == I->getParent())) {
1776 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1778 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1779 static unsigned SETFOpcTable[2][3] = {
1780 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1781 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1783 unsigned *SETFOpc = nullptr;
1784 switch (Predicate) {
1786 case CmpInst::FCMP_OEQ:
1787 SETFOpc = &SETFOpcTable[0][0];
1788 Predicate = CmpInst::ICMP_NE;
1790 case CmpInst::FCMP_UNE:
1791 SETFOpc = &SETFOpcTable[1][0];
1792 Predicate = CmpInst::ICMP_NE;
1797 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1798 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1800 const Value *CmpLHS = CI->getOperand(0);
1801 const Value *CmpRHS = CI->getOperand(1);
1803 std::swap(CmpLHS, CmpRHS);
1805 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1806 // Emit a compare of the LHS and RHS, setting the flags.
1807 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1811 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1812 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1813 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1815 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1817 auto const &II = TII.get(SETFOpc[2]);
1818 if (II.getNumDefs()) {
1819 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1821 .addReg(FlagReg2).addReg(FlagReg1);
1823 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1824 .addReg(FlagReg2).addReg(FlagReg1);
1828 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1829 // Fake request the condition, otherwise the intrinsic might be completely
1831 unsigned TmpReg = getRegForValue(Cond);
1839 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1840 // garbage. Indeed, only the less significant bit is supposed to be
1841 // accurate. If we read more than the lsb, we may see non-zero values
1842 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1843 // the select. This is achieved by performing TEST against 1.
1844 unsigned CondReg = getRegForValue(Cond);
1847 bool CondIsKill = hasTrivialKill(Cond);
1849 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1850 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1853 const Value *LHS = I->getOperand(1);
1854 const Value *RHS = I->getOperand(2);
1856 unsigned RHSReg = getRegForValue(RHS);
1857 bool RHSIsKill = hasTrivialKill(RHS);
1859 unsigned LHSReg = getRegForValue(LHS);
1860 bool LHSIsKill = hasTrivialKill(LHS);
1862 if (!LHSReg || !RHSReg)
1865 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1866 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1868 updateValueMap(I, ResultReg);
1872 /// \brief Emit SSE or AVX instructions to lower the select.
1874 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1875 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1876 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1877 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1878 // Optimize conditions coming from a compare if both instructions are in the
1879 // same basic block (values defined in other basic blocks may not have
1880 // initialized registers).
1881 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1882 if (!CI || (CI->getParent() != I->getParent()))
1885 if (I->getType() != CI->getOperand(0)->getType() ||
1886 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1887 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1890 const Value *CmpLHS = CI->getOperand(0);
1891 const Value *CmpRHS = CI->getOperand(1);
1892 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1894 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1895 // We don't have to materialize a zero constant for this case and can just use
1896 // %x again on the RHS.
1897 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1898 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1899 if (CmpRHSC && CmpRHSC->isNullValue())
1905 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1910 std::swap(CmpLHS, CmpRHS);
1912 // Choose the SSE instruction sequence based on data type (float or double).
1913 static unsigned OpcTable[2][4] = {
1914 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1915 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1918 unsigned *Opc = nullptr;
1919 switch (RetVT.SimpleTy) {
1920 default: return false;
1921 case MVT::f32: Opc = &OpcTable[0][0]; break;
1922 case MVT::f64: Opc = &OpcTable[1][0]; break;
1925 const Value *LHS = I->getOperand(1);
1926 const Value *RHS = I->getOperand(2);
1928 unsigned LHSReg = getRegForValue(LHS);
1929 bool LHSIsKill = hasTrivialKill(LHS);
1931 unsigned RHSReg = getRegForValue(RHS);
1932 bool RHSIsKill = hasTrivialKill(RHS);
1934 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1935 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1937 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1938 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1940 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1943 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1946 if (Subtarget->hasAVX()) {
1947 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1948 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1949 // uses XMM0 as the selection register. That may need just as many
1950 // instructions as the AND/ANDN/OR sequence due to register moves, so
1952 unsigned CmpOpcode =
1953 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1954 unsigned BlendOpcode =
1955 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1957 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
1958 CmpRHSReg, CmpRHSIsKill, CC);
1959 ResultReg = fastEmitInst_rrr(BlendOpcode, RC, RHSReg, RHSIsKill,
1960 LHSReg, LHSIsKill, CmpReg, true);
1962 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1963 CmpRHSReg, CmpRHSIsKill, CC);
1964 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1966 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1968 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1969 AndReg, /*IsKill=*/true);
1971 updateValueMap(I, ResultReg);
1975 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1976 // These are pseudo CMOV instructions and will be later expanded into control-
1979 switch (RetVT.SimpleTy) {
1980 default: return false;
1981 case MVT::i8: Opc = X86::CMOV_GR8; break;
1982 case MVT::i16: Opc = X86::CMOV_GR16; break;
1983 case MVT::i32: Opc = X86::CMOV_GR32; break;
1984 case MVT::f32: Opc = X86::CMOV_FR32; break;
1985 case MVT::f64: Opc = X86::CMOV_FR64; break;
1988 const Value *Cond = I->getOperand(0);
1989 X86::CondCode CC = X86::COND_NE;
1991 // Optimize conditions coming from a compare if both instructions are in the
1992 // same basic block (values defined in other basic blocks may not have
1993 // initialized registers).
1994 const auto *CI = dyn_cast<CmpInst>(Cond);
1995 if (CI && (CI->getParent() == I->getParent())) {
1997 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1998 if (CC > X86::LAST_VALID_COND)
2001 const Value *CmpLHS = CI->getOperand(0);
2002 const Value *CmpRHS = CI->getOperand(1);
2005 std::swap(CmpLHS, CmpRHS);
2007 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
2008 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2011 unsigned CondReg = getRegForValue(Cond);
2014 bool CondIsKill = hasTrivialKill(Cond);
2015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2016 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2019 const Value *LHS = I->getOperand(1);
2020 const Value *RHS = I->getOperand(2);
2022 unsigned LHSReg = getRegForValue(LHS);
2023 bool LHSIsKill = hasTrivialKill(LHS);
2025 unsigned RHSReg = getRegForValue(RHS);
2026 bool RHSIsKill = hasTrivialKill(RHS);
2028 if (!LHSReg || !RHSReg)
2031 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2033 unsigned ResultReg =
2034 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2035 updateValueMap(I, ResultReg);
2039 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2041 if (!isTypeLegal(I->getType(), RetVT))
2044 // Check if we can fold the select.
2045 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2046 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2047 const Value *Opnd = nullptr;
2048 switch (Predicate) {
2050 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2051 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2053 // No need for a select anymore - this is an unconditional move.
2055 unsigned OpReg = getRegForValue(Opnd);
2058 bool OpIsKill = hasTrivialKill(Opnd);
2059 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2060 unsigned ResultReg = createResultReg(RC);
2061 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2062 TII.get(TargetOpcode::COPY), ResultReg)
2063 .addReg(OpReg, getKillRegState(OpIsKill));
2064 updateValueMap(I, ResultReg);
2069 // First try to use real conditional move instructions.
2070 if (X86FastEmitCMoveSelect(RetVT, I))
2073 // Try to use a sequence of SSE instructions to simulate a conditional move.
2074 if (X86FastEmitSSESelect(RetVT, I))
2077 // Fall-back to pseudo conditional move instructions, which will be later
2078 // converted to control-flow.
2079 if (X86FastEmitPseudoSelect(RetVT, I))
2085 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2086 // The target-independent selection algorithm in FastISel already knows how
2087 // to select a SINT_TO_FP if the target is SSE but not AVX.
2088 // Early exit if the subtarget doesn't have AVX.
2089 if (!Subtarget->hasAVX())
2092 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2095 // Select integer to float/double conversion.
2096 unsigned OpReg = getRegForValue(I->getOperand(0));
2100 const TargetRegisterClass *RC = nullptr;
2103 if (I->getType()->isDoubleTy()) {
2104 // sitofp int -> double
2105 Opcode = X86::VCVTSI2SDrr;
2106 RC = &X86::FR64RegClass;
2107 } else if (I->getType()->isFloatTy()) {
2108 // sitofp int -> float
2109 Opcode = X86::VCVTSI2SSrr;
2110 RC = &X86::FR32RegClass;
2114 unsigned ImplicitDefReg = createResultReg(RC);
2115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2116 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2117 unsigned ResultReg =
2118 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2119 updateValueMap(I, ResultReg);
2123 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2124 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2126 const TargetRegisterClass *RC) {
2127 assert((I->getOpcode() == Instruction::FPExt ||
2128 I->getOpcode() == Instruction::FPTrunc) &&
2129 "Instruction must be an FPExt or FPTrunc!");
2131 unsigned OpReg = getRegForValue(I->getOperand(0));
2135 unsigned ResultReg = createResultReg(RC);
2136 MachineInstrBuilder MIB;
2137 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2139 if (Subtarget->hasAVX())
2142 updateValueMap(I, ResultReg);
2146 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2147 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2148 I->getOperand(0)->getType()->isFloatTy()) {
2149 // fpext from float to double.
2150 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2151 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2157 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2158 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2159 I->getOperand(0)->getType()->isDoubleTy()) {
2160 // fptrunc from double to float.
2161 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2162 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2168 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2169 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2170 EVT DstVT = TLI.getValueType(I->getType());
2172 // This code only handles truncation to byte.
2173 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2175 if (!TLI.isTypeLegal(SrcVT))
2178 unsigned InputReg = getRegForValue(I->getOperand(0));
2180 // Unhandled operand. Halt "fast" selection and bail.
2183 if (SrcVT == MVT::i8) {
2184 // Truncate from i8 to i1; no code needed.
2185 updateValueMap(I, InputReg);
2189 bool KillInputReg = false;
2190 if (!Subtarget->is64Bit()) {
2191 // If we're on x86-32; we can't extract an i8 from a general register.
2192 // First issue a copy to GR16_ABCD or GR32_ABCD.
2193 const TargetRegisterClass *CopyRC =
2194 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2195 unsigned CopyReg = createResultReg(CopyRC);
2196 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2197 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2199 KillInputReg = true;
2202 // Issue an extract_subreg.
2203 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2204 InputReg, KillInputReg,
2209 updateValueMap(I, ResultReg);
2213 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2214 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2217 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2218 X86AddressMode SrcAM, uint64_t Len) {
2220 // Make sure we don't bloat code by inlining very large memcpy's.
2221 if (!IsMemcpySmall(Len))
2224 bool i64Legal = Subtarget->is64Bit();
2226 // We don't care about alignment here since we just emit integer accesses.
2229 if (Len >= 8 && i64Legal)
2239 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2240 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2241 assert(RV && "Failed to emit load or store??");
2243 unsigned Size = VT.getSizeInBits()/8;
2245 DestAM.Disp += Size;
2252 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2253 // FIXME: Handle more intrinsics.
2254 switch (II->getIntrinsicID()) {
2255 default: return false;
2256 case Intrinsic::convert_from_fp16:
2257 case Intrinsic::convert_to_fp16: {
2258 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2261 const Value *Op = II->getArgOperand(0);
2262 unsigned InputReg = getRegForValue(Op);
2266 // F16C only allows converting from float to half and from half to float.
2267 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2268 if (IsFloatToHalf) {
2269 if (!Op->getType()->isFloatTy())
2272 if (!II->getType()->isFloatTy())
2276 unsigned ResultReg = 0;
2277 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2278 if (IsFloatToHalf) {
2279 // 'InputReg' is implicitly promoted from register class FR32 to
2280 // register class VR128 by method 'constrainOperandRegClass' which is
2281 // directly called by 'fastEmitInst_ri'.
2282 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2283 // used to provide rounding control.
2284 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2286 // Move the lower 32-bits of ResultReg to another register of class GR32.
2287 ResultReg = createResultReg(&X86::GR32RegClass);
2288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2289 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2290 .addReg(InputReg, RegState::Kill);
2292 // The result value is in the lower 16-bits of ResultReg.
2293 unsigned RegIdx = X86::sub_16bit;
2294 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2296 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2297 // Explicitly sign-extend the input to 32-bit.
2298 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2301 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2302 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2303 InputReg, /*Kill=*/true);
2305 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2307 // The result value is in the lower 32-bits of ResultReg.
2308 // Emit an explicit copy from register class VR128 to register class FR32.
2309 ResultReg = createResultReg(&X86::FR32RegClass);
2310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2311 TII.get(TargetOpcode::COPY), ResultReg)
2312 .addReg(InputReg, RegState::Kill);
2315 updateValueMap(II, ResultReg);
2318 case Intrinsic::frameaddress: {
2319 MachineFunction *MF = FuncInfo.MF;
2320 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2323 Type *RetTy = II->getCalledFunction()->getReturnType();
2326 if (!isTypeLegal(RetTy, VT))
2330 const TargetRegisterClass *RC = nullptr;
2332 switch (VT.SimpleTy) {
2333 default: llvm_unreachable("Invalid result type for frameaddress.");
2334 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2335 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2338 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2339 // we get the wrong frame register.
2340 MachineFrameInfo *MFI = MF->getFrameInfo();
2341 MFI->setFrameAddressIsTaken(true);
2343 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2344 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2345 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2346 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2347 "Invalid Frame Register!");
2349 // Always make a copy of the frame register to to a vreg first, so that we
2350 // never directly reference the frame register (the TwoAddressInstruction-
2351 // Pass doesn't like that).
2352 unsigned SrcReg = createResultReg(RC);
2353 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2354 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2356 // Now recursively load from the frame address.
2357 // movq (%rbp), %rax
2358 // movq (%rax), %rax
2359 // movq (%rax), %rax
2362 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2364 DestReg = createResultReg(RC);
2365 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2366 TII.get(Opc), DestReg), SrcReg);
2370 updateValueMap(II, SrcReg);
2373 case Intrinsic::memcpy: {
2374 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2375 // Don't handle volatile or variable length memcpys.
2376 if (MCI->isVolatile())
2379 if (isa<ConstantInt>(MCI->getLength())) {
2380 // Small memcpy's are common enough that we want to do them
2381 // without a call if possible.
2382 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2383 if (IsMemcpySmall(Len)) {
2384 X86AddressMode DestAM, SrcAM;
2385 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2386 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2388 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2393 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2394 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2397 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2400 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2402 case Intrinsic::memset: {
2403 const MemSetInst *MSI = cast<MemSetInst>(II);
2405 if (MSI->isVolatile())
2408 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2409 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2412 if (MSI->getDestAddressSpace() > 255)
2415 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2417 case Intrinsic::stackprotector: {
2418 // Emit code to store the stack guard onto the stack.
2419 EVT PtrTy = TLI.getPointerTy();
2421 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2422 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2424 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2426 // Grab the frame index.
2428 if (!X86SelectAddress(Slot, AM)) return false;
2429 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2432 case Intrinsic::dbg_declare: {
2433 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2435 assert(DI->getAddress() && "Null address should be checked earlier!");
2436 if (!X86SelectAddress(DI->getAddress(), AM))
2438 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2439 // FIXME may need to add RegState::Debug to any registers produced,
2440 // although ESP/EBP should be the only ones at the moment.
2441 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2442 "Expected inlined-at fields to agree");
2443 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2445 .addMetadata(DI->getVariable())
2446 .addMetadata(DI->getExpression());
2449 case Intrinsic::trap: {
2450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2453 case Intrinsic::sqrt: {
2454 if (!Subtarget->hasSSE1())
2457 Type *RetTy = II->getCalledFunction()->getReturnType();
2460 if (!isTypeLegal(RetTy, VT))
2463 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2464 // is not generated by FastISel yet.
2465 // FIXME: Update this code once tablegen can handle it.
2466 static const unsigned SqrtOpc[2][2] = {
2467 {X86::SQRTSSr, X86::VSQRTSSr},
2468 {X86::SQRTSDr, X86::VSQRTSDr}
2470 bool HasAVX = Subtarget->hasAVX();
2472 const TargetRegisterClass *RC;
2473 switch (VT.SimpleTy) {
2474 default: return false;
2475 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2476 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2479 const Value *SrcVal = II->getArgOperand(0);
2480 unsigned SrcReg = getRegForValue(SrcVal);
2485 unsigned ImplicitDefReg = 0;
2487 ImplicitDefReg = createResultReg(RC);
2488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2489 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2492 unsigned ResultReg = createResultReg(RC);
2493 MachineInstrBuilder MIB;
2494 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2498 MIB.addReg(ImplicitDefReg);
2502 updateValueMap(II, ResultReg);
2505 case Intrinsic::sadd_with_overflow:
2506 case Intrinsic::uadd_with_overflow:
2507 case Intrinsic::ssub_with_overflow:
2508 case Intrinsic::usub_with_overflow:
2509 case Intrinsic::smul_with_overflow:
2510 case Intrinsic::umul_with_overflow: {
2511 // This implements the basic lowering of the xalu with overflow intrinsics
2512 // into add/sub/mul followed by either seto or setb.
2513 const Function *Callee = II->getCalledFunction();
2514 auto *Ty = cast<StructType>(Callee->getReturnType());
2515 Type *RetTy = Ty->getTypeAtIndex(0U);
2516 Type *CondTy = Ty->getTypeAtIndex(1);
2519 if (!isTypeLegal(RetTy, VT))
2522 if (VT < MVT::i8 || VT > MVT::i64)
2525 const Value *LHS = II->getArgOperand(0);
2526 const Value *RHS = II->getArgOperand(1);
2528 // Canonicalize immediate to the RHS.
2529 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2530 isCommutativeIntrinsic(II))
2531 std::swap(LHS, RHS);
2533 bool UseIncDec = false;
2534 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2537 unsigned BaseOpc, CondOpc;
2538 switch (II->getIntrinsicID()) {
2539 default: llvm_unreachable("Unexpected intrinsic!");
2540 case Intrinsic::sadd_with_overflow:
2541 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2542 CondOpc = X86::SETOr;
2544 case Intrinsic::uadd_with_overflow:
2545 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2546 case Intrinsic::ssub_with_overflow:
2547 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2548 CondOpc = X86::SETOr;
2550 case Intrinsic::usub_with_overflow:
2551 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2552 case Intrinsic::smul_with_overflow:
2553 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2554 case Intrinsic::umul_with_overflow:
2555 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2558 unsigned LHSReg = getRegForValue(LHS);
2561 bool LHSIsKill = hasTrivialKill(LHS);
2563 unsigned ResultReg = 0;
2564 // Check if we have an immediate version.
2565 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2566 static const unsigned Opc[2][4] = {
2567 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2568 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2571 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2572 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2573 bool IsDec = BaseOpc == X86ISD::DEC;
2574 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2575 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2576 .addReg(LHSReg, getKillRegState(LHSIsKill));
2578 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2579 CI->getZExtValue());
2585 RHSReg = getRegForValue(RHS);
2588 RHSIsKill = hasTrivialKill(RHS);
2589 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2593 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2595 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2596 static const unsigned MULOpc[] =
2597 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2598 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2599 // First copy the first operand into RAX, which is an implicit input to
2600 // the X86::MUL*r instruction.
2601 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2602 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2603 .addReg(LHSReg, getKillRegState(LHSIsKill));
2604 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2605 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2606 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2607 static const unsigned MULOpc[] =
2608 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2609 if (VT == MVT::i8) {
2610 // Copy the first operand into AL, which is an implicit input to the
2611 // X86::IMUL8r instruction.
2612 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2613 TII.get(TargetOpcode::COPY), X86::AL)
2614 .addReg(LHSReg, getKillRegState(LHSIsKill));
2615 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2618 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2619 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2626 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2627 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2631 updateValueMap(II, ResultReg, 2);
2634 case Intrinsic::x86_sse_cvttss2si:
2635 case Intrinsic::x86_sse_cvttss2si64:
2636 case Intrinsic::x86_sse2_cvttsd2si:
2637 case Intrinsic::x86_sse2_cvttsd2si64: {
2639 switch (II->getIntrinsicID()) {
2640 default: llvm_unreachable("Unexpected intrinsic.");
2641 case Intrinsic::x86_sse_cvttss2si:
2642 case Intrinsic::x86_sse_cvttss2si64:
2643 if (!Subtarget->hasSSE1())
2645 IsInputDouble = false;
2647 case Intrinsic::x86_sse2_cvttsd2si:
2648 case Intrinsic::x86_sse2_cvttsd2si64:
2649 if (!Subtarget->hasSSE2())
2651 IsInputDouble = true;
2655 Type *RetTy = II->getCalledFunction()->getReturnType();
2657 if (!isTypeLegal(RetTy, VT))
2660 static const unsigned CvtOpc[2][2][2] = {
2661 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2662 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2663 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2664 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2666 bool HasAVX = Subtarget->hasAVX();
2668 switch (VT.SimpleTy) {
2669 default: llvm_unreachable("Unexpected result type.");
2670 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2671 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2674 // Check if we can fold insertelement instructions into the convert.
2675 const Value *Op = II->getArgOperand(0);
2676 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2677 const Value *Index = IE->getOperand(2);
2678 if (!isa<ConstantInt>(Index))
2680 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2683 Op = IE->getOperand(1);
2686 Op = IE->getOperand(0);
2689 unsigned Reg = getRegForValue(Op);
2693 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2697 updateValueMap(II, ResultReg);
2703 bool X86FastISel::fastLowerArguments() {
2704 if (!FuncInfo.CanLowerReturn)
2707 const Function *F = FuncInfo.Fn;
2711 CallingConv::ID CC = F->getCallingConv();
2712 if (CC != CallingConv::C)
2715 if (Subtarget->isCallingConvWin64(CC))
2718 if (!Subtarget->is64Bit())
2721 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2722 unsigned GPRCnt = 0;
2723 unsigned FPRCnt = 0;
2725 for (auto const &Arg : F->args()) {
2726 // The first argument is at index 1.
2728 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2729 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2730 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2731 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2734 Type *ArgTy = Arg.getType();
2735 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2738 EVT ArgVT = TLI.getValueType(ArgTy);
2739 if (!ArgVT.isSimple()) return false;
2740 switch (ArgVT.getSimpleVT().SimpleTy) {
2741 default: return false;
2748 if (!Subtarget->hasSSE1())
2761 static const MCPhysReg GPR32ArgRegs[] = {
2762 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2764 static const MCPhysReg GPR64ArgRegs[] = {
2765 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2767 static const MCPhysReg XMMArgRegs[] = {
2768 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2769 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2772 unsigned GPRIdx = 0;
2773 unsigned FPRIdx = 0;
2774 for (auto const &Arg : F->args()) {
2775 MVT VT = TLI.getSimpleValueType(Arg.getType());
2776 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2778 switch (VT.SimpleTy) {
2779 default: llvm_unreachable("Unexpected value type.");
2780 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2781 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2782 case MVT::f32: // fall-through
2783 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2785 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2786 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2787 // Without this, EmitLiveInCopies may eliminate the livein if its only
2788 // use is a bitcast (which isn't turned into an instruction).
2789 unsigned ResultReg = createResultReg(RC);
2790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2791 TII.get(TargetOpcode::COPY), ResultReg)
2792 .addReg(DstReg, getKillRegState(true));
2793 updateValueMap(&Arg, ResultReg);
2798 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2800 ImmutableCallSite *CS) {
2801 if (Subtarget->is64Bit())
2803 if (Subtarget->getTargetTriple().isOSMSVCRT())
2805 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2806 CC == CallingConv::HiPE)
2808 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2810 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2815 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2816 auto &OutVals = CLI.OutVals;
2817 auto &OutFlags = CLI.OutFlags;
2818 auto &OutRegs = CLI.OutRegs;
2819 auto &Ins = CLI.Ins;
2820 auto &InRegs = CLI.InRegs;
2821 CallingConv::ID CC = CLI.CallConv;
2822 bool &IsTailCall = CLI.IsTailCall;
2823 bool IsVarArg = CLI.IsVarArg;
2824 const Value *Callee = CLI.Callee;
2825 MCSymbol *Symbol = CLI.Symbol;
2827 bool Is64Bit = Subtarget->is64Bit();
2828 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2830 // Handle only C, fastcc, and webkit_js calling conventions for now.
2832 default: return false;
2833 case CallingConv::C:
2834 case CallingConv::Fast:
2835 case CallingConv::WebKit_JS:
2836 case CallingConv::X86_FastCall:
2837 case CallingConv::X86_64_Win64:
2838 case CallingConv::X86_64_SysV:
2842 // Allow SelectionDAG isel to handle tail calls.
2846 // fastcc with -tailcallopt is intended to provide a guaranteed
2847 // tail call optimization. Fastisel doesn't know how to do that.
2848 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2851 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2852 // x86-32. Special handling for x86-64 is implemented.
2853 if (IsVarArg && IsWin64)
2856 // Don't know about inalloca yet.
2857 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2860 // Fast-isel doesn't know about callee-pop yet.
2861 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2862 TM.Options.GuaranteedTailCallOpt))
2865 SmallVector<MVT, 16> OutVTs;
2866 SmallVector<unsigned, 16> ArgRegs;
2868 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2869 // instruction. This is safe because it is common to all FastISel supported
2870 // calling conventions on x86.
2871 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2872 Value *&Val = OutVals[i];
2873 ISD::ArgFlagsTy Flags = OutFlags[i];
2874 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2875 if (CI->getBitWidth() < 32) {
2877 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2879 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2883 // Passing bools around ends up doing a trunc to i1 and passing it.
2884 // Codegen this as an argument + "and 1".
2886 auto *TI = dyn_cast<TruncInst>(Val);
2888 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2889 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2891 Value *PrevVal = TI->getOperand(0);
2892 ResultReg = getRegForValue(PrevVal);
2897 if (!isTypeLegal(PrevVal->getType(), VT))
2901 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2903 if (!isTypeLegal(Val->getType(), VT))
2905 ResultReg = getRegForValue(Val);
2911 ArgRegs.push_back(ResultReg);
2912 OutVTs.push_back(VT);
2915 // Analyze operands of the call, assigning locations to each operand.
2916 SmallVector<CCValAssign, 16> ArgLocs;
2917 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2919 // Allocate shadow area for Win64
2921 CCInfo.AllocateStack(32, 8);
2923 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2925 // Get a count of how many bytes are to be pushed on the stack.
2926 unsigned NumBytes = CCInfo.getNextStackOffset();
2928 // Issue CALLSEQ_START
2929 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2930 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2931 .addImm(NumBytes).addImm(0);
2933 // Walk the register/memloc assignments, inserting copies/loads.
2934 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2935 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2936 CCValAssign const &VA = ArgLocs[i];
2937 const Value *ArgVal = OutVals[VA.getValNo()];
2938 MVT ArgVT = OutVTs[VA.getValNo()];
2940 if (ArgVT == MVT::x86mmx)
2943 unsigned ArgReg = ArgRegs[VA.getValNo()];
2945 // Promote the value if needed.
2946 switch (VA.getLocInfo()) {
2947 case CCValAssign::Full: break;
2948 case CCValAssign::SExt: {
2949 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2950 "Unexpected extend");
2951 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2953 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2954 ArgVT = VA.getLocVT();
2957 case CCValAssign::ZExt: {
2958 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2959 "Unexpected extend");
2960 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2962 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2963 ArgVT = VA.getLocVT();
2966 case CCValAssign::AExt: {
2967 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2968 "Unexpected extend");
2969 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2972 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2975 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2978 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2979 ArgVT = VA.getLocVT();
2982 case CCValAssign::BCvt: {
2983 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2984 /*TODO: Kill=*/false);
2985 assert(ArgReg && "Failed to emit a bitcast!");
2986 ArgVT = VA.getLocVT();
2989 case CCValAssign::VExt:
2990 // VExt has not been implemented, so this should be impossible to reach
2991 // for now. However, fallback to Selection DAG isel once implemented.
2993 case CCValAssign::AExtUpper:
2994 case CCValAssign::SExtUpper:
2995 case CCValAssign::ZExtUpper:
2996 case CCValAssign::FPExt:
2997 llvm_unreachable("Unexpected loc info!");
2998 case CCValAssign::Indirect:
2999 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3004 if (VA.isRegLoc()) {
3005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3006 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3007 OutRegs.push_back(VA.getLocReg());
3009 assert(VA.isMemLoc());
3011 // Don't emit stores for undef values.
3012 if (isa<UndefValue>(ArgVal))
3015 unsigned LocMemOffset = VA.getLocMemOffset();
3017 AM.Base.Reg = RegInfo->getStackRegister();
3018 AM.Disp = LocMemOffset;
3019 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3020 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3021 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3022 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3023 ArgVT.getStoreSize(), Alignment);
3024 if (Flags.isByVal()) {
3025 X86AddressMode SrcAM;
3026 SrcAM.Base.Reg = ArgReg;
3027 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3029 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3030 // If this is a really simple value, emit this with the Value* version
3031 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3032 // as it can cause us to reevaluate the argument.
3033 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3036 bool ValIsKill = hasTrivialKill(ArgVal);
3037 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3043 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3045 if (Subtarget->isPICStyleGOT()) {
3046 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3048 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3051 if (Is64Bit && IsVarArg && !IsWin64) {
3052 // From AMD64 ABI document:
3053 // For calls that may call functions that use varargs or stdargs
3054 // (prototype-less calls or calls to functions containing ellipsis (...) in
3055 // the declaration) %al is used as hidden argument to specify the number
3056 // of SSE registers used. The contents of %al do not need to match exactly
3057 // the number of registers, but must be an ubound on the number of SSE
3058 // registers used and is in the range 0 - 8 inclusive.
3060 // Count the number of XMM registers allocated.
3061 static const MCPhysReg XMMArgRegs[] = {
3062 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3063 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3065 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3066 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3067 && "SSE registers cannot be used when SSE is disabled");
3068 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3069 X86::AL).addImm(NumXMMRegs);
3072 // Materialize callee address in a register. FIXME: GV address can be
3073 // handled with a CALLpcrel32 instead.
3074 X86AddressMode CalleeAM;
3075 if (!X86SelectCallAddress(Callee, CalleeAM))
3078 unsigned CalleeOp = 0;
3079 const GlobalValue *GV = nullptr;
3080 if (CalleeAM.GV != nullptr) {
3082 } else if (CalleeAM.Base.Reg != 0) {
3083 CalleeOp = CalleeAM.Base.Reg;
3088 MachineInstrBuilder MIB;
3090 // Register-indirect call.
3091 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3092 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3096 assert(GV && "Not a direct call");
3097 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3099 // See if we need any target-specific flags on the GV operand.
3100 unsigned char OpFlags = 0;
3102 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3103 // external symbols most go through the PLT in PIC mode. If the symbol
3104 // has hidden or protected visibility, or if it is static or local, then
3105 // we don't need to use the PLT - we can directly call it.
3106 if (Subtarget->isTargetELF() &&
3107 TM.getRelocationModel() == Reloc::PIC_ &&
3108 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3109 OpFlags = X86II::MO_PLT;
3110 } else if (Subtarget->isPICStyleStubAny() &&
3111 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3112 (!Subtarget->getTargetTriple().isMacOSX() ||
3113 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3114 // PC-relative references to external symbols should go through $stub,
3115 // unless we're building with the leopard linker or later, which
3116 // automatically synthesizes these stubs.
3117 OpFlags = X86II::MO_DARWIN_STUB;
3120 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3122 MIB.addSym(Symbol, OpFlags);
3124 MIB.addGlobalAddress(GV, 0, OpFlags);
3127 // Add a register mask operand representing the call-preserved registers.
3128 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3129 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3131 // Add an implicit use GOT pointer in EBX.
3132 if (Subtarget->isPICStyleGOT())
3133 MIB.addReg(X86::EBX, RegState::Implicit);
3135 if (Is64Bit && IsVarArg && !IsWin64)
3136 MIB.addReg(X86::AL, RegState::Implicit);
3138 // Add implicit physical register uses to the call.
3139 for (auto Reg : OutRegs)
3140 MIB.addReg(Reg, RegState::Implicit);
3142 // Issue CALLSEQ_END
3143 unsigned NumBytesForCalleeToPop =
3144 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3145 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3146 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3147 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3149 // Now handle call return values.
3150 SmallVector<CCValAssign, 16> RVLocs;
3151 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3152 CLI.RetTy->getContext());
3153 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3155 // Copy all of the result registers out of their specified physreg.
3156 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3157 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3158 CCValAssign &VA = RVLocs[i];
3159 EVT CopyVT = VA.getValVT();
3160 unsigned CopyReg = ResultReg + i;
3162 // If this is x86-64, and we disabled SSE, we can't return FP values
3163 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3164 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3165 report_fatal_error("SSE register return with SSE disabled");
3168 // If we prefer to use the value in xmm registers, copy it out as f80 and
3169 // use a truncate to move it from fp stack reg to xmm reg.
3170 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3171 isScalarFPTypeInSSEReg(VA.getValVT())) {
3173 CopyReg = createResultReg(&X86::RFP80RegClass);
3176 // Copy out the result.
3177 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3178 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3179 InRegs.push_back(VA.getLocReg());
3181 // Round the f80 to the right size, which also moves it to the appropriate
3182 // xmm register. This is accomplished by storing the f80 value in memory
3183 // and then loading it back.
3184 if (CopyVT != VA.getValVT()) {
3185 EVT ResVT = VA.getValVT();
3186 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3187 unsigned MemSize = ResVT.getSizeInBits()/8;
3188 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3189 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3192 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3193 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3194 TII.get(Opc), ResultReg + i), FI);
3198 CLI.ResultReg = ResultReg;
3199 CLI.NumResultRegs = RVLocs.size();
3206 X86FastISel::fastSelectInstruction(const Instruction *I) {
3207 switch (I->getOpcode()) {
3209 case Instruction::Load:
3210 return X86SelectLoad(I);
3211 case Instruction::Store:
3212 return X86SelectStore(I);
3213 case Instruction::Ret:
3214 return X86SelectRet(I);
3215 case Instruction::ICmp:
3216 case Instruction::FCmp:
3217 return X86SelectCmp(I);
3218 case Instruction::ZExt:
3219 return X86SelectZExt(I);
3220 case Instruction::Br:
3221 return X86SelectBranch(I);
3222 case Instruction::LShr:
3223 case Instruction::AShr:
3224 case Instruction::Shl:
3225 return X86SelectShift(I);
3226 case Instruction::SDiv:
3227 case Instruction::UDiv:
3228 case Instruction::SRem:
3229 case Instruction::URem:
3230 return X86SelectDivRem(I);
3231 case Instruction::Select:
3232 return X86SelectSelect(I);
3233 case Instruction::Trunc:
3234 return X86SelectTrunc(I);
3235 case Instruction::FPExt:
3236 return X86SelectFPExt(I);
3237 case Instruction::FPTrunc:
3238 return X86SelectFPTrunc(I);
3239 case Instruction::SIToFP:
3240 return X86SelectSIToFP(I);
3241 case Instruction::IntToPtr: // Deliberate fall-through.
3242 case Instruction::PtrToInt: {
3243 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3244 EVT DstVT = TLI.getValueType(I->getType());
3245 if (DstVT.bitsGT(SrcVT))
3246 return X86SelectZExt(I);
3247 if (DstVT.bitsLT(SrcVT))
3248 return X86SelectTrunc(I);
3249 unsigned Reg = getRegForValue(I->getOperand(0));
3250 if (Reg == 0) return false;
3251 updateValueMap(I, Reg);
3259 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3263 uint64_t Imm = CI->getZExtValue();
3265 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3266 switch (VT.SimpleTy) {
3267 default: llvm_unreachable("Unexpected value type");
3270 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3273 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3278 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3280 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3281 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3288 switch (VT.SimpleTy) {
3289 default: llvm_unreachable("Unexpected value type");
3290 case MVT::i1: VT = MVT::i8; // fall-through
3291 case MVT::i8: Opc = X86::MOV8ri; break;
3292 case MVT::i16: Opc = X86::MOV16ri; break;
3293 case MVT::i32: Opc = X86::MOV32ri; break;
3295 if (isUInt<32>(Imm))
3297 else if (isInt<32>(Imm))
3298 Opc = X86::MOV64ri32;
3304 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3305 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3306 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3308 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3309 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3312 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3315 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3316 if (CFP->isNullValue())
3317 return fastMaterializeFloatZero(CFP);
3319 // Can't handle alternate code models yet.
3320 CodeModel::Model CM = TM.getCodeModel();
3321 if (CM != CodeModel::Small && CM != CodeModel::Large)
3324 // Get opcode and regclass of the output for the given load instruction.
3326 const TargetRegisterClass *RC = nullptr;
3327 switch (VT.SimpleTy) {
3330 if (X86ScalarSSEf32) {
3331 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3332 RC = &X86::FR32RegClass;
3334 Opc = X86::LD_Fp32m;
3335 RC = &X86::RFP32RegClass;
3339 if (X86ScalarSSEf64) {
3340 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3341 RC = &X86::FR64RegClass;
3343 Opc = X86::LD_Fp64m;
3344 RC = &X86::RFP64RegClass;
3348 // No f80 support yet.
3352 // MachineConstantPool wants an explicit alignment.
3353 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3355 // Alignment of vector types. FIXME!
3356 Align = DL.getTypeAllocSize(CFP->getType());
3359 // x86-32 PIC requires a PIC base register for constant pools.
3360 unsigned PICBase = 0;
3361 unsigned char OpFlag = 0;
3362 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3363 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3364 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3365 } else if (Subtarget->isPICStyleGOT()) {
3366 OpFlag = X86II::MO_GOTOFF;
3367 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3368 } else if (Subtarget->isPICStyleRIPRel() &&
3369 TM.getCodeModel() == CodeModel::Small) {
3373 // Create the load from the constant pool.
3374 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3375 unsigned ResultReg = createResultReg(RC);
3377 if (CM == CodeModel::Large) {
3378 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3379 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3381 .addConstantPoolIndex(CPI, 0, OpFlag);
3382 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3383 TII.get(Opc), ResultReg);
3384 addDirectMem(MIB, AddrReg);
3385 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3386 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3387 TM.getDataLayout()->getPointerSize(), Align);
3388 MIB->addMemOperand(*FuncInfo.MF, MMO);
3392 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3393 TII.get(Opc), ResultReg),
3394 CPI, PICBase, OpFlag);
3398 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3399 // Can't handle alternate code models yet.
3400 if (TM.getCodeModel() != CodeModel::Small)
3403 // Materialize addresses with LEA/MOV instructions.
3405 if (X86SelectAddress(GV, AM)) {
3406 // If the expression is just a basereg, then we're done, otherwise we need
3408 if (AM.BaseType == X86AddressMode::RegBase &&
3409 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3412 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3413 if (TM.getRelocationModel() == Reloc::Static &&
3414 TLI.getPointerTy() == MVT::i64) {
3415 // The displacement code could be more than 32 bits away so we need to use
3416 // an instruction with a 64 bit immediate
3417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3419 .addGlobalAddress(GV);
3421 unsigned Opc = TLI.getPointerTy() == MVT::i32
3422 ? (Subtarget->isTarget64BitILP32()
3423 ? X86::LEA64_32r : X86::LEA32r)
3425 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3426 TII.get(Opc), ResultReg), AM);
3433 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3434 EVT CEVT = TLI.getValueType(C->getType(), true);
3436 // Only handle simple types.
3437 if (!CEVT.isSimple())
3439 MVT VT = CEVT.getSimpleVT();
3441 if (const auto *CI = dyn_cast<ConstantInt>(C))
3442 return X86MaterializeInt(CI, VT);
3443 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3444 return X86MaterializeFP(CFP, VT);
3445 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3446 return X86MaterializeGV(GV, VT);
3451 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3452 // Fail on dynamic allocas. At this point, getRegForValue has already
3453 // checked its CSE maps, so if we're here trying to handle a dynamic
3454 // alloca, we're not going to succeed. X86SelectAddress has a
3455 // check for dynamic allocas, because it's called directly from
3456 // various places, but targetMaterializeAlloca also needs a check
3457 // in order to avoid recursion between getRegForValue,
3458 // X86SelectAddrss, and targetMaterializeAlloca.
3459 if (!FuncInfo.StaticAllocaMap.count(C))
3461 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3464 if (!X86SelectAddress(C, AM))
3466 unsigned Opc = TLI.getPointerTy() == MVT::i32
3467 ? (Subtarget->isTarget64BitILP32()
3468 ? X86::LEA64_32r : X86::LEA32r)
3470 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3471 unsigned ResultReg = createResultReg(RC);
3472 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3473 TII.get(Opc), ResultReg), AM);
3477 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3479 if (!isTypeLegal(CF->getType(), VT))
3482 // Get opcode and regclass for the given zero.
3484 const TargetRegisterClass *RC = nullptr;
3485 switch (VT.SimpleTy) {
3488 if (X86ScalarSSEf32) {
3489 Opc = X86::FsFLD0SS;
3490 RC = &X86::FR32RegClass;
3492 Opc = X86::LD_Fp032;
3493 RC = &X86::RFP32RegClass;
3497 if (X86ScalarSSEf64) {
3498 Opc = X86::FsFLD0SD;
3499 RC = &X86::FR64RegClass;
3501 Opc = X86::LD_Fp064;
3502 RC = &X86::RFP64RegClass;
3506 // No f80 support yet.
3510 unsigned ResultReg = createResultReg(RC);
3511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3516 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3517 const LoadInst *LI) {
3518 const Value *Ptr = LI->getPointerOperand();
3520 if (!X86SelectAddress(Ptr, AM))
3523 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3525 unsigned Size = DL.getTypeAllocSize(LI->getType());
3526 unsigned Alignment = LI->getAlignment();
3528 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3529 Alignment = DL.getABITypeAlignment(LI->getType());
3531 SmallVector<MachineOperand, 8> AddrOps;
3532 AM.getFullAddress(AddrOps);
3534 MachineInstr *Result = XII.foldMemoryOperandImpl(
3535 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3536 /*AllowCommute=*/true);
3540 // The index register could be in the wrong register class. Unfortunately,
3541 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3542 // to just look at OpNo + the offset to the index reg. We actually need to
3543 // scan the instruction to find the index reg and see if its the correct reg
3545 unsigned OperandNo = 0;
3546 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3547 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3548 MachineOperand &MO = *I;
3549 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3551 // Found the index reg, now try to rewrite it.
3552 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3553 MO.getReg(), OperandNo);
3554 if (IndexReg == MO.getReg())
3556 MO.setReg(IndexReg);
3559 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3560 MI->eraseFromParent();
3566 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3567 const TargetLibraryInfo *libInfo) {
3568 return new X86FastISel(funcInfo, libInfo);