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/Support/ErrorHandling.h"
42 #include "llvm/Target/TargetOptions.h"
47 class X86FastISel final : public FastISel {
48 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
49 /// make the right decision when generating code for different targets.
50 const X86Subtarget *Subtarget;
52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
53 /// floating point ops.
54 /// When SSE is available, use it for f32 operations.
55 /// When SSE2 is available, use it for f64 operations.
60 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
61 const TargetLibraryInfo *libInfo)
62 : FastISel(funcInfo, libInfo) {
63 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
64 X86ScalarSSEf64 = Subtarget->hasSSE2();
65 X86ScalarSSEf32 = Subtarget->hasSSE1();
68 bool fastSelectInstruction(const Instruction *I) override;
70 /// \brief The specified machine instr operand is a vreg, and that
71 /// vreg is being provided by the specified load instruction. If possible,
72 /// try to fold the load as an operand to the instruction, returning true if
74 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
75 const LoadInst *LI) override;
77 bool fastLowerArguments() override;
78 bool fastLowerCall(CallLoweringInfo &CLI) override;
79 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81 #include "X86GenFastISel.inc"
84 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, DebugLoc DL);
86 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
89 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
91 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
92 const X86AddressMode &AM,
93 MachineMemOperand *MMO = nullptr, bool Aligned = false);
95 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
99 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectLoad(const Instruction *I);
103 bool X86SelectStore(const Instruction *I);
105 bool X86SelectRet(const Instruction *I);
107 bool X86SelectCmp(const Instruction *I);
109 bool X86SelectZExt(const Instruction *I);
111 bool X86SelectBranch(const Instruction *I);
113 bool X86SelectShift(const Instruction *I);
115 bool X86SelectDivRem(const Instruction *I);
117 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
119 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
121 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
123 bool X86SelectSelect(const Instruction *I);
125 bool X86SelectTrunc(const Instruction *I);
127 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
128 const TargetRegisterClass *RC);
130 bool X86SelectFPExt(const Instruction *I);
131 bool X86SelectFPTrunc(const Instruction *I);
132 bool X86SelectSIToFP(const Instruction *I);
134 const X86InstrInfo *getInstrInfo() const {
135 return Subtarget->getInstrInfo();
137 const X86TargetMachine *getTargetMachine() const {
138 return static_cast<const X86TargetMachine *>(&TM);
141 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
143 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
144 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
145 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
146 unsigned fastMaterializeConstant(const Constant *C) override;
148 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
150 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
152 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
153 /// computed in an SSE register, not on the X87 floating point stack.
154 bool isScalarFPTypeInSSEReg(EVT VT) const {
155 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
156 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
159 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
161 bool IsMemcpySmall(uint64_t Len);
163 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
164 X86AddressMode SrcAM, uint64_t Len);
166 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
170 } // end anonymous namespace.
172 static std::pair<X86::CondCode, bool>
173 getX86ConditionCode(CmpInst::Predicate Predicate) {
174 X86::CondCode CC = X86::COND_INVALID;
175 bool NeedSwap = false;
178 // Floating-point Predicates
179 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
180 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
181 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
182 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
183 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
184 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
185 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
186 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
187 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
188 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
189 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
190 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
191 case CmpInst::FCMP_OEQ: // fall-through
192 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
194 // Integer Predicates
195 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
196 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
197 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
198 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
199 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
200 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
201 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
202 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
203 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
204 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
207 return std::make_pair(CC, NeedSwap);
210 static std::pair<unsigned, bool>
211 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
213 bool NeedSwap = false;
215 // SSE Condition code mapping:
225 default: llvm_unreachable("Unexpected predicate");
226 case CmpInst::FCMP_OEQ: CC = 0; break;
227 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
228 case CmpInst::FCMP_OLT: CC = 1; break;
229 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
230 case CmpInst::FCMP_OLE: CC = 2; break;
231 case CmpInst::FCMP_UNO: CC = 3; break;
232 case CmpInst::FCMP_UNE: CC = 4; break;
233 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
234 case CmpInst::FCMP_UGE: CC = 5; break;
235 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
236 case CmpInst::FCMP_UGT: CC = 6; break;
237 case CmpInst::FCMP_ORD: CC = 7; break;
238 case CmpInst::FCMP_UEQ:
239 case CmpInst::FCMP_ONE: CC = 8; break;
242 return std::make_pair(CC, NeedSwap);
245 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
246 /// into the user. The condition code will only be updated on success.
247 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
249 if (!isa<ExtractValueInst>(Cond))
252 const auto *EV = cast<ExtractValueInst>(Cond);
253 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
256 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
258 const Function *Callee = II->getCalledFunction();
260 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
261 if (!isTypeLegal(RetTy, RetVT))
264 if (RetVT != MVT::i32 && RetVT != MVT::i64)
268 switch (II->getIntrinsicID()) {
269 default: return false;
270 case Intrinsic::sadd_with_overflow:
271 case Intrinsic::ssub_with_overflow:
272 case Intrinsic::smul_with_overflow:
273 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
274 case Intrinsic::uadd_with_overflow:
275 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
278 // Check if both instructions are in the same basic block.
279 if (II->getParent() != I->getParent())
282 // Make sure nothing is in the way
283 BasicBlock::const_iterator Start = I;
284 BasicBlock::const_iterator End = II;
285 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
286 // We only expect extractvalue instructions between the intrinsic and the
287 // instruction to be selected.
288 if (!isa<ExtractValueInst>(Itr))
291 // Check that the extractvalue operand comes from the intrinsic.
292 const auto *EVI = cast<ExtractValueInst>(Itr);
293 if (EVI->getAggregateOperand() != II)
301 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
302 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
303 if (evt == MVT::Other || !evt.isSimple())
304 // Unhandled type. Halt "fast" selection and bail.
307 VT = evt.getSimpleVT();
308 // For now, require SSE/SSE2 for performing floating-point operations,
309 // since x87 requires additional work.
310 if (VT == MVT::f64 && !X86ScalarSSEf64)
312 if (VT == MVT::f32 && !X86ScalarSSEf32)
314 // Similarly, no f80 support yet.
317 // We only handle legal types. For example, on x86-32 the instruction
318 // selector contains all of the 64-bit instructions from x86-64,
319 // under the assumption that i64 won't be used if the target doesn't
321 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
324 #include "X86GenCallingConv.inc"
326 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
327 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
328 /// Return true and the result register by reference if it is possible.
329 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
330 MachineMemOperand *MMO, unsigned &ResultReg) {
331 // Get opcode and regclass of the output for the given load instruction.
333 const TargetRegisterClass *RC = nullptr;
334 switch (VT.getSimpleVT().SimpleTy) {
335 default: return false;
339 RC = &X86::GR8RegClass;
343 RC = &X86::GR16RegClass;
347 RC = &X86::GR32RegClass;
350 // Must be in x86-64 mode.
352 RC = &X86::GR64RegClass;
355 if (X86ScalarSSEf32) {
356 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
357 RC = &X86::FR32RegClass;
360 RC = &X86::RFP32RegClass;
364 if (X86ScalarSSEf64) {
365 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
366 RC = &X86::FR64RegClass;
369 RC = &X86::RFP64RegClass;
373 // No f80 support yet.
377 ResultReg = createResultReg(RC);
378 MachineInstrBuilder MIB =
379 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
380 addFullAddress(MIB, AM);
382 MIB->addMemOperand(*FuncInfo.MF, MMO);
386 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
387 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
388 /// and a displacement offset, or a GlobalAddress,
389 /// i.e. V. Return true if it is possible.
390 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
391 const X86AddressMode &AM,
392 MachineMemOperand *MMO, bool Aligned) {
393 // Get opcode and regclass of the output for the given store instruction.
395 switch (VT.getSimpleVT().SimpleTy) {
396 case MVT::f80: // No f80 support yet.
397 default: return false;
399 // Mask out all but lowest bit.
400 unsigned AndResult = createResultReg(&X86::GR8RegClass);
401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
402 TII.get(X86::AND8ri), AndResult)
403 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
406 // FALLTHROUGH, handling i1 as i8.
407 case MVT::i8: Opc = X86::MOV8mr; break;
408 case MVT::i16: Opc = X86::MOV16mr; break;
409 case MVT::i32: Opc = X86::MOV32mr; break;
410 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
412 Opc = X86ScalarSSEf32 ?
413 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
416 Opc = X86ScalarSSEf64 ?
417 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
421 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
423 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
427 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
429 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
436 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
438 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
442 MachineInstrBuilder MIB =
443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
444 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
446 MIB->addMemOperand(*FuncInfo.MF, MMO);
451 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
452 const X86AddressMode &AM,
453 MachineMemOperand *MMO, bool Aligned) {
454 // Handle 'null' like i32/i64 0.
455 if (isa<ConstantPointerNull>(Val))
456 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
458 // If this is a store of a simple constant, fold the constant into the store.
459 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
462 switch (VT.getSimpleVT().SimpleTy) {
464 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
465 case MVT::i8: Opc = X86::MOV8mi; break;
466 case MVT::i16: Opc = X86::MOV16mi; break;
467 case MVT::i32: Opc = X86::MOV32mi; break;
469 // Must be a 32-bit sign extended value.
470 if (isInt<32>(CI->getSExtValue()))
471 Opc = X86::MOV64mi32;
476 MachineInstrBuilder MIB =
477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
478 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
479 : CI->getZExtValue());
481 MIB->addMemOperand(*FuncInfo.MF, MMO);
486 unsigned ValReg = getRegForValue(Val);
490 bool ValKill = hasTrivialKill(Val);
491 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
494 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
495 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
496 /// ISD::SIGN_EXTEND).
497 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
498 unsigned Src, EVT SrcVT,
499 unsigned &ResultReg) {
500 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
501 Src, /*TODO: Kill=*/false);
509 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
510 // Handle constant address.
511 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
512 // Can't handle alternate code models yet.
513 if (TM.getCodeModel() != CodeModel::Small)
516 // Can't handle TLS yet.
517 if (GV->isThreadLocal())
520 // RIP-relative addresses can't have additional register operands, so if
521 // we've already folded stuff into the addressing mode, just force the
522 // global value into its own register, which we can use as the basereg.
523 if (!Subtarget->isPICStyleRIPRel() ||
524 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
525 // Okay, we've committed to selecting this global. Set up the address.
528 // Allow the subtarget to classify the global.
529 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
531 // If this reference is relative to the pic base, set it now.
532 if (isGlobalRelativeToPICBase(GVFlags)) {
533 // FIXME: How do we know Base.Reg is free??
534 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
537 // Unless the ABI requires an extra load, return a direct reference to
539 if (!isGlobalStubReference(GVFlags)) {
540 if (Subtarget->isPICStyleRIPRel()) {
541 // Use rip-relative addressing if we can. Above we verified that the
542 // base and index registers are unused.
543 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
544 AM.Base.Reg = X86::RIP;
546 AM.GVOpFlags = GVFlags;
550 // Ok, we need to do a load from a stub. If we've already loaded from
551 // this stub, reuse the loaded pointer, otherwise emit the load now.
552 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
554 if (I != LocalValueMap.end() && I->second != 0) {
557 // Issue load from stub.
559 const TargetRegisterClass *RC = nullptr;
560 X86AddressMode StubAM;
561 StubAM.Base.Reg = AM.Base.Reg;
563 StubAM.GVOpFlags = GVFlags;
565 // Prepare for inserting code in the local-value area.
566 SavePoint SaveInsertPt = enterLocalValueArea();
568 if (TLI.getPointerTy() == MVT::i64) {
570 RC = &X86::GR64RegClass;
572 if (Subtarget->isPICStyleRIPRel())
573 StubAM.Base.Reg = X86::RIP;
576 RC = &X86::GR32RegClass;
579 LoadReg = createResultReg(RC);
580 MachineInstrBuilder LoadMI =
581 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
582 addFullAddress(LoadMI, StubAM);
584 // Ok, back to normal mode.
585 leaveLocalValueArea(SaveInsertPt);
587 // Prevent loading GV stub multiple times in same MBB.
588 LocalValueMap[V] = LoadReg;
591 // Now construct the final address. Note that the Disp, Scale,
592 // and Index values may already be set here.
593 AM.Base.Reg = LoadReg;
599 // If all else fails, try to materialize the value in a register.
600 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
601 if (AM.Base.Reg == 0) {
602 AM.Base.Reg = getRegForValue(V);
603 return AM.Base.Reg != 0;
605 if (AM.IndexReg == 0) {
606 assert(AM.Scale == 1 && "Scale with no index!");
607 AM.IndexReg = getRegForValue(V);
608 return AM.IndexReg != 0;
615 /// X86SelectAddress - Attempt to fill in an address from the given value.
617 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
618 SmallVector<const Value *, 32> GEPs;
620 const User *U = nullptr;
621 unsigned Opcode = Instruction::UserOp1;
622 if (const Instruction *I = dyn_cast<Instruction>(V)) {
623 // Don't walk into other basic blocks; it's possible we haven't
624 // visited them yet, so the instructions may not yet be assigned
625 // virtual registers.
626 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
627 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
628 Opcode = I->getOpcode();
631 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
632 Opcode = C->getOpcode();
636 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
637 if (Ty->getAddressSpace() > 255)
638 // Fast instruction selection doesn't support the special
644 case Instruction::BitCast:
645 // Look past bitcasts.
646 return X86SelectAddress(U->getOperand(0), AM);
648 case Instruction::IntToPtr:
649 // Look past no-op inttoptrs.
650 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
651 return X86SelectAddress(U->getOperand(0), AM);
654 case Instruction::PtrToInt:
655 // Look past no-op ptrtoints.
656 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
657 return X86SelectAddress(U->getOperand(0), AM);
660 case Instruction::Alloca: {
661 // Do static allocas.
662 const AllocaInst *A = cast<AllocaInst>(V);
663 DenseMap<const AllocaInst *, int>::iterator SI =
664 FuncInfo.StaticAllocaMap.find(A);
665 if (SI != FuncInfo.StaticAllocaMap.end()) {
666 AM.BaseType = X86AddressMode::FrameIndexBase;
667 AM.Base.FrameIndex = SI->second;
673 case Instruction::Add: {
674 // Adds of constants are common and easy enough.
675 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
676 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
677 // They have to fit in the 32-bit signed displacement field though.
678 if (isInt<32>(Disp)) {
679 AM.Disp = (uint32_t)Disp;
680 return X86SelectAddress(U->getOperand(0), AM);
686 case Instruction::GetElementPtr: {
687 X86AddressMode SavedAM = AM;
689 // Pattern-match simple GEPs.
690 uint64_t Disp = (int32_t)AM.Disp;
691 unsigned IndexReg = AM.IndexReg;
692 unsigned Scale = AM.Scale;
693 gep_type_iterator GTI = gep_type_begin(U);
694 // Iterate through the indices, folding what we can. Constants can be
695 // folded, and one dynamic index can be handled, if the scale is supported.
696 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
697 i != e; ++i, ++GTI) {
698 const Value *Op = *i;
699 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
700 const StructLayout *SL = DL.getStructLayout(STy);
701 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
705 // A array/variable index is always of the form i*S where S is the
706 // constant scale size. See if we can push the scale into immediates.
707 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
709 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
710 // Constant-offset addressing.
711 Disp += CI->getSExtValue() * S;
714 if (canFoldAddIntoGEP(U, Op)) {
715 // A compatible add with a constant operand. Fold the constant.
717 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
718 Disp += CI->getSExtValue() * S;
719 // Iterate on the other operand.
720 Op = cast<AddOperator>(Op)->getOperand(0);
724 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
725 (S == 1 || S == 2 || S == 4 || S == 8)) {
726 // Scaled-index addressing.
728 IndexReg = getRegForGEPIndex(Op).first;
734 goto unsupported_gep;
738 // Check for displacement overflow.
739 if (!isInt<32>(Disp))
742 AM.IndexReg = IndexReg;
744 AM.Disp = (uint32_t)Disp;
747 if (const GetElementPtrInst *GEP =
748 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
749 // Ok, the GEP indices were covered by constant-offset and scaled-index
750 // addressing. Update the address state and move on to examining the base.
753 } else if (X86SelectAddress(U->getOperand(0), AM)) {
757 // If we couldn't merge the gep value into this addr mode, revert back to
758 // our address and just match the value instead of completely failing.
761 for (SmallVectorImpl<const Value *>::reverse_iterator
762 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
763 if (handleConstantAddresses(*I, AM))
768 // Ok, the GEP indices weren't all covered.
773 return handleConstantAddresses(V, AM);
776 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
778 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
779 const User *U = nullptr;
780 unsigned Opcode = Instruction::UserOp1;
781 const Instruction *I = dyn_cast<Instruction>(V);
782 // Record if the value is defined in the same basic block.
784 // This information is crucial to know whether or not folding an
786 // Indeed, FastISel generates or reuses a virtual register for all
787 // operands of all instructions it selects. Obviously, the definition and
788 // its uses must use the same virtual register otherwise the produced
789 // code is incorrect.
790 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
791 // registers for values that are alive across basic blocks. This ensures
792 // that the values are consistently set between across basic block, even
793 // if different instruction selection mechanisms are used (e.g., a mix of
794 // SDISel and FastISel).
795 // For values local to a basic block, the instruction selection process
796 // generates these virtual registers with whatever method is appropriate
797 // for its needs. In particular, FastISel and SDISel do not share the way
798 // local virtual registers are set.
799 // Therefore, this is impossible (or at least unsafe) to share values
800 // between basic blocks unless they use the same instruction selection
801 // method, which is not guarantee for X86.
802 // Moreover, things like hasOneUse could not be used accurately, if we
803 // allow to reference values across basic blocks whereas they are not
804 // alive across basic blocks initially.
807 Opcode = I->getOpcode();
809 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
810 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
811 Opcode = C->getOpcode();
817 case Instruction::BitCast:
818 // Look past bitcasts if its operand is in the same BB.
820 return X86SelectCallAddress(U->getOperand(0), AM);
823 case Instruction::IntToPtr:
824 // Look past no-op inttoptrs if its operand is in the same BB.
826 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
827 return X86SelectCallAddress(U->getOperand(0), AM);
830 case Instruction::PtrToInt:
831 // Look past no-op ptrtoints if its operand is in the same BB.
833 TLI.getValueType(U->getType()) == TLI.getPointerTy())
834 return X86SelectCallAddress(U->getOperand(0), AM);
838 // Handle constant address.
839 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
840 // Can't handle alternate code models yet.
841 if (TM.getCodeModel() != CodeModel::Small)
844 // RIP-relative addresses can't have additional register operands.
845 if (Subtarget->isPICStyleRIPRel() &&
846 (AM.Base.Reg != 0 || AM.IndexReg != 0))
849 // Can't handle DLL Import.
850 if (GV->hasDLLImportStorageClass())
854 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
855 if (GVar->isThreadLocal())
858 // Okay, we've committed to selecting this global. Set up the basic address.
861 // No ABI requires an extra load for anything other than DLLImport, which
862 // we rejected above. Return a direct reference to the global.
863 if (Subtarget->isPICStyleRIPRel()) {
864 // Use rip-relative addressing if we can. Above we verified that the
865 // base and index registers are unused.
866 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
867 AM.Base.Reg = X86::RIP;
868 } else if (Subtarget->isPICStyleStubPIC()) {
869 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
870 } else if (Subtarget->isPICStyleGOT()) {
871 AM.GVOpFlags = X86II::MO_GOTOFF;
877 // If all else fails, try to materialize the value in a register.
878 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
879 if (AM.Base.Reg == 0) {
880 AM.Base.Reg = getRegForValue(V);
881 return AM.Base.Reg != 0;
883 if (AM.IndexReg == 0) {
884 assert(AM.Scale == 1 && "Scale with no index!");
885 AM.IndexReg = getRegForValue(V);
886 return AM.IndexReg != 0;
894 /// X86SelectStore - Select and emit code to implement store instructions.
895 bool X86FastISel::X86SelectStore(const Instruction *I) {
896 // Atomic stores need special handling.
897 const StoreInst *S = cast<StoreInst>(I);
902 const Value *Val = S->getValueOperand();
903 const Value *Ptr = S->getPointerOperand();
906 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
909 unsigned Alignment = S->getAlignment();
910 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
911 if (Alignment == 0) // Ensure that codegen never sees alignment 0
912 Alignment = ABIAlignment;
913 bool Aligned = Alignment >= ABIAlignment;
916 if (!X86SelectAddress(Ptr, AM))
919 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
922 /// X86SelectRet - Select and emit code to implement ret instructions.
923 bool X86FastISel::X86SelectRet(const Instruction *I) {
924 const ReturnInst *Ret = cast<ReturnInst>(I);
925 const Function &F = *I->getParent()->getParent();
926 const X86MachineFunctionInfo *X86MFInfo =
927 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
929 if (!FuncInfo.CanLowerReturn)
932 CallingConv::ID CC = F.getCallingConv();
933 if (CC != CallingConv::C &&
934 CC != CallingConv::Fast &&
935 CC != CallingConv::X86_FastCall &&
936 CC != CallingConv::X86_64_SysV)
939 if (Subtarget->isCallingConvWin64(CC))
942 // Don't handle popping bytes on return for now.
943 if (X86MFInfo->getBytesToPopOnReturn() != 0)
946 // fastcc with -tailcallopt is intended to provide a guaranteed
947 // tail call optimization. Fastisel doesn't know how to do that.
948 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
951 // Let SDISel handle vararg functions.
955 // Build a list of return value registers.
956 SmallVector<unsigned, 4> RetRegs;
958 if (Ret->getNumOperands() > 0) {
959 SmallVector<ISD::OutputArg, 4> Outs;
960 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
962 // Analyze operands of the call, assigning locations to each operand.
963 SmallVector<CCValAssign, 16> ValLocs;
964 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
965 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
967 const Value *RV = Ret->getOperand(0);
968 unsigned Reg = getRegForValue(RV);
972 // Only handle a single return value for now.
973 if (ValLocs.size() != 1)
976 CCValAssign &VA = ValLocs[0];
978 // Don't bother handling odd stuff for now.
979 if (VA.getLocInfo() != CCValAssign::Full)
981 // Only handle register returns for now.
985 // The calling-convention tables for x87 returns don't tell
987 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
990 unsigned SrcReg = Reg + VA.getValNo();
991 EVT SrcVT = TLI.getValueType(RV->getType());
992 EVT DstVT = VA.getValVT();
993 // Special handling for extended integers.
994 if (SrcVT != DstVT) {
995 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
998 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1001 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1003 if (SrcVT == MVT::i1) {
1004 if (Outs[0].Flags.isSExt())
1006 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1009 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1011 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1012 SrcReg, /*TODO: Kill=*/false);
1016 unsigned DstReg = VA.getLocReg();
1017 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1018 // Avoid a cross-class copy. This is very unlikely.
1019 if (!SrcRC->contains(DstReg))
1021 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1022 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1024 // Add register to return instruction.
1025 RetRegs.push_back(VA.getLocReg());
1028 // The x86-64 ABI for returning structs by value requires that we copy
1029 // the sret argument into %rax for the return. We saved the argument into
1030 // a virtual register in the entry block, so now we copy the value out
1031 // and into %rax. We also do the same with %eax for Win32.
1032 if (F.hasStructRetAttr() &&
1033 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1034 unsigned Reg = X86MFInfo->getSRetReturnReg();
1036 "SRetReturnReg should have been set in LowerFormalArguments()!");
1037 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1039 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1040 RetRegs.push_back(RetReg);
1043 // Now emit the RET.
1044 MachineInstrBuilder MIB =
1045 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1046 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1047 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1048 MIB.addReg(RetRegs[i], RegState::Implicit);
1052 /// X86SelectLoad - Select and emit code to implement load instructions.
1054 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1055 const LoadInst *LI = cast<LoadInst>(I);
1057 // Atomic loads need special handling.
1062 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1065 const Value *Ptr = LI->getPointerOperand();
1068 if (!X86SelectAddress(Ptr, AM))
1071 unsigned ResultReg = 0;
1072 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1075 updateValueMap(I, ResultReg);
1079 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1080 bool HasAVX = Subtarget->hasAVX();
1081 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1082 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1084 switch (VT.getSimpleVT().SimpleTy) {
1086 case MVT::i8: return X86::CMP8rr;
1087 case MVT::i16: return X86::CMP16rr;
1088 case MVT::i32: return X86::CMP32rr;
1089 case MVT::i64: return X86::CMP64rr;
1091 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1093 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1097 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1098 /// of the comparison, return an opcode that works for the compare (e.g.
1099 /// CMP32ri) otherwise return 0.
1100 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1101 switch (VT.getSimpleVT().SimpleTy) {
1102 // Otherwise, we can't fold the immediate into this comparison.
1104 case MVT::i8: return X86::CMP8ri;
1105 case MVT::i16: return X86::CMP16ri;
1106 case MVT::i32: return X86::CMP32ri;
1108 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1110 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1111 return X86::CMP64ri32;
1116 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1117 EVT VT, DebugLoc CurDbgLoc) {
1118 unsigned Op0Reg = getRegForValue(Op0);
1119 if (Op0Reg == 0) return false;
1121 // Handle 'null' like i32/i64 0.
1122 if (isa<ConstantPointerNull>(Op1))
1123 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1125 // We have two options: compare with register or immediate. If the RHS of
1126 // the compare is an immediate that we can fold into this compare, use
1127 // CMPri, otherwise use CMPrr.
1128 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1129 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1130 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1132 .addImm(Op1C->getSExtValue());
1137 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1138 if (CompareOpc == 0) return false;
1140 unsigned Op1Reg = getRegForValue(Op1);
1141 if (Op1Reg == 0) return false;
1142 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1149 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1150 const CmpInst *CI = cast<CmpInst>(I);
1153 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1156 // Try to optimize or fold the cmp.
1157 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1158 unsigned ResultReg = 0;
1159 switch (Predicate) {
1161 case CmpInst::FCMP_FALSE: {
1162 ResultReg = createResultReg(&X86::GR32RegClass);
1163 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1165 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1171 case CmpInst::FCMP_TRUE: {
1172 ResultReg = createResultReg(&X86::GR8RegClass);
1173 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1174 ResultReg).addImm(1);
1180 updateValueMap(I, ResultReg);
1184 const Value *LHS = CI->getOperand(0);
1185 const Value *RHS = CI->getOperand(1);
1187 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1188 // We don't have to materialize a zero constant for this case and can just use
1189 // %x again on the RHS.
1190 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1191 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1192 if (RHSC && RHSC->isNullValue())
1196 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1197 static unsigned SETFOpcTable[2][3] = {
1198 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1199 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1201 unsigned *SETFOpc = nullptr;
1202 switch (Predicate) {
1204 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1205 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1208 ResultReg = createResultReg(&X86::GR8RegClass);
1210 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1213 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1214 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1217 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1220 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1221 updateValueMap(I, ResultReg);
1227 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1228 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1229 unsigned Opc = X86::getSETFromCond(CC);
1232 std::swap(LHS, RHS);
1234 // Emit a compare of LHS/RHS.
1235 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1239 updateValueMap(I, ResultReg);
1243 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1244 EVT DstVT = TLI.getValueType(I->getType());
1245 if (!TLI.isTypeLegal(DstVT))
1248 unsigned ResultReg = getRegForValue(I->getOperand(0));
1252 // Handle zero-extension from i1 to i8, which is common.
1253 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1254 if (SrcVT.SimpleTy == MVT::i1) {
1255 // Set the high bits to zero.
1256 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1263 if (DstVT == MVT::i64) {
1264 // Handle extension to 64-bits via sub-register shenanigans.
1267 switch (SrcVT.SimpleTy) {
1268 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1269 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1270 case MVT::i32: MovInst = X86::MOV32rr; break;
1271 default: llvm_unreachable("Unexpected zext to i64 source type");
1274 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1278 ResultReg = createResultReg(&X86::GR64RegClass);
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1281 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1282 } else if (DstVT != MVT::i8) {
1283 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1284 ResultReg, /*Kill=*/true);
1289 updateValueMap(I, ResultReg);
1293 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1294 // Unconditional branches are selected by tablegen-generated code.
1295 // Handle a conditional branch.
1296 const BranchInst *BI = cast<BranchInst>(I);
1297 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1298 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1300 // Fold the common case of a conditional branch with a comparison
1301 // in the same block (values defined on other blocks may not have
1302 // initialized registers).
1304 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1305 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1306 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1308 // Try to optimize or fold the cmp.
1309 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1310 switch (Predicate) {
1312 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1313 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1316 const Value *CmpLHS = CI->getOperand(0);
1317 const Value *CmpRHS = CI->getOperand(1);
1319 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1321 // We don't have to materialize a zero constant for this case and can just
1322 // use %x again on the RHS.
1323 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1324 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1325 if (CmpRHSC && CmpRHSC->isNullValue())
1329 // Try to take advantage of fallthrough opportunities.
1330 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1331 std::swap(TrueMBB, FalseMBB);
1332 Predicate = CmpInst::getInversePredicate(Predicate);
1335 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1336 // code check. Instead two branch instructions are required to check all
1337 // the flags. First we change the predicate to a supported condition code,
1338 // which will be the first branch. Later one we will emit the second
1340 bool NeedExtraBranch = false;
1341 switch (Predicate) {
1343 case CmpInst::FCMP_OEQ:
1344 std::swap(TrueMBB, FalseMBB); // fall-through
1345 case CmpInst::FCMP_UNE:
1346 NeedExtraBranch = true;
1347 Predicate = CmpInst::FCMP_ONE;
1353 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1354 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1356 BranchOpc = X86::GetCondBranchFromCond(CC);
1358 std::swap(CmpLHS, CmpRHS);
1360 // Emit a compare of the LHS and RHS, setting the flags.
1361 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1367 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1369 if (NeedExtraBranch) {
1370 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1374 // Obtain the branch weight and add the TrueBB to the successor list.
1375 uint32_t BranchWeight = 0;
1377 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1378 TrueMBB->getBasicBlock());
1379 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1381 // Emits an unconditional branch to the FalseBB, obtains the branch
1382 // weight, and adds it to the successor list.
1383 fastEmitBranch(FalseMBB, DbgLoc);
1387 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1388 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1389 // typically happen for _Bool and C++ bools.
1391 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1392 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1393 unsigned TestOpc = 0;
1394 switch (SourceVT.SimpleTy) {
1396 case MVT::i8: TestOpc = X86::TEST8ri; break;
1397 case MVT::i16: TestOpc = X86::TEST16ri; break;
1398 case MVT::i32: TestOpc = X86::TEST32ri; break;
1399 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1402 unsigned OpReg = getRegForValue(TI->getOperand(0));
1403 if (OpReg == 0) return false;
1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1405 .addReg(OpReg).addImm(1);
1407 unsigned JmpOpc = X86::JNE_1;
1408 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1409 std::swap(TrueMBB, FalseMBB);
1413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1415 fastEmitBranch(FalseMBB, DbgLoc);
1416 uint32_t BranchWeight = 0;
1418 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1419 TrueMBB->getBasicBlock());
1420 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1424 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1425 // Fake request the condition, otherwise the intrinsic might be completely
1427 unsigned TmpReg = getRegForValue(BI->getCondition());
1431 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1435 fastEmitBranch(FalseMBB, DbgLoc);
1436 uint32_t BranchWeight = 0;
1438 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1439 TrueMBB->getBasicBlock());
1440 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1444 // Otherwise do a clumsy setcc and re-test it.
1445 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1446 // in an explicit cast, so make sure to handle that correctly.
1447 unsigned OpReg = getRegForValue(BI->getCondition());
1448 if (OpReg == 0) return false;
1450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1451 .addReg(OpReg).addImm(1);
1452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1454 fastEmitBranch(FalseMBB, DbgLoc);
1455 uint32_t BranchWeight = 0;
1457 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1458 TrueMBB->getBasicBlock());
1459 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1463 bool X86FastISel::X86SelectShift(const Instruction *I) {
1464 unsigned CReg = 0, OpReg = 0;
1465 const TargetRegisterClass *RC = nullptr;
1466 if (I->getType()->isIntegerTy(8)) {
1468 RC = &X86::GR8RegClass;
1469 switch (I->getOpcode()) {
1470 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1471 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1472 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1473 default: return false;
1475 } else if (I->getType()->isIntegerTy(16)) {
1477 RC = &X86::GR16RegClass;
1478 switch (I->getOpcode()) {
1479 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1480 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1481 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1482 default: return false;
1484 } else if (I->getType()->isIntegerTy(32)) {
1486 RC = &X86::GR32RegClass;
1487 switch (I->getOpcode()) {
1488 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1489 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1490 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1491 default: return false;
1493 } else if (I->getType()->isIntegerTy(64)) {
1495 RC = &X86::GR64RegClass;
1496 switch (I->getOpcode()) {
1497 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1498 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1499 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1500 default: return false;
1507 if (!isTypeLegal(I->getType(), VT))
1510 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1511 if (Op0Reg == 0) return false;
1513 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1514 if (Op1Reg == 0) return false;
1515 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1516 CReg).addReg(Op1Reg);
1518 // The shift instruction uses X86::CL. If we defined a super-register
1519 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1520 if (CReg != X86::CL)
1521 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1522 TII.get(TargetOpcode::KILL), X86::CL)
1523 .addReg(CReg, RegState::Kill);
1525 unsigned ResultReg = createResultReg(RC);
1526 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1528 updateValueMap(I, ResultReg);
1532 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1533 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1534 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1535 const static bool S = true; // IsSigned
1536 const static bool U = false; // !IsSigned
1537 const static unsigned Copy = TargetOpcode::COPY;
1538 // For the X86 DIV/IDIV instruction, in most cases the dividend
1539 // (numerator) must be in a specific register pair highreg:lowreg,
1540 // producing the quotient in lowreg and the remainder in highreg.
1541 // For most data types, to set up the instruction, the dividend is
1542 // copied into lowreg, and lowreg is sign-extended or zero-extended
1543 // into highreg. The exception is i8, where the dividend is defined
1544 // as a single register rather than a register pair, and we
1545 // therefore directly sign-extend or zero-extend the dividend into
1546 // lowreg, instead of copying, and ignore the highreg.
1547 const static struct DivRemEntry {
1548 // The following portion depends only on the data type.
1549 const TargetRegisterClass *RC;
1550 unsigned LowInReg; // low part of the register pair
1551 unsigned HighInReg; // high part of the register pair
1552 // The following portion depends on both the data type and the operation.
1553 struct DivRemResult {
1554 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1555 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1556 // highreg, or copying a zero into highreg.
1557 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1558 // zero/sign-extending into lowreg for i8.
1559 unsigned DivRemResultReg; // Register containing the desired result.
1560 bool IsOpSigned; // Whether to use signed or unsigned form.
1561 } ResultTable[NumOps];
1562 } OpTable[NumTypes] = {
1563 { &X86::GR8RegClass, X86::AX, 0, {
1564 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1565 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1566 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1567 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1570 { &X86::GR16RegClass, X86::AX, X86::DX, {
1571 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1572 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1573 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1574 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1577 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1578 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1579 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1580 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1581 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1584 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1585 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1586 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1587 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1588 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1594 if (!isTypeLegal(I->getType(), VT))
1597 unsigned TypeIndex, OpIndex;
1598 switch (VT.SimpleTy) {
1599 default: return false;
1600 case MVT::i8: TypeIndex = 0; break;
1601 case MVT::i16: TypeIndex = 1; break;
1602 case MVT::i32: TypeIndex = 2; break;
1603 case MVT::i64: TypeIndex = 3;
1604 if (!Subtarget->is64Bit())
1609 switch (I->getOpcode()) {
1610 default: llvm_unreachable("Unexpected div/rem opcode");
1611 case Instruction::SDiv: OpIndex = 0; break;
1612 case Instruction::SRem: OpIndex = 1; break;
1613 case Instruction::UDiv: OpIndex = 2; break;
1614 case Instruction::URem: OpIndex = 3; break;
1617 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1618 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1619 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1622 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1626 // Move op0 into low-order input register.
1627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1628 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1629 // Zero-extend or sign-extend into high-order input register.
1630 if (OpEntry.OpSignExtend) {
1631 if (OpEntry.IsOpSigned)
1632 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1633 TII.get(OpEntry.OpSignExtend));
1635 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1636 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1637 TII.get(X86::MOV32r0), Zero32);
1639 // Copy the zero into the appropriate sub/super/identical physical
1640 // register. Unfortunately the operations needed are not uniform enough
1641 // to fit neatly into the table above.
1642 if (VT.SimpleTy == MVT::i16) {
1643 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1644 TII.get(Copy), TypeEntry.HighInReg)
1645 .addReg(Zero32, 0, X86::sub_16bit);
1646 } else if (VT.SimpleTy == MVT::i32) {
1647 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1648 TII.get(Copy), TypeEntry.HighInReg)
1650 } else if (VT.SimpleTy == MVT::i64) {
1651 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1652 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1653 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1657 // Generate the DIV/IDIV instruction.
1658 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1659 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1660 // For i8 remainder, we can't reference AH directly, as we'll end
1661 // up with bogus copies like %R9B = COPY %AH. Reference AX
1662 // instead to prevent AH references in a REX instruction.
1664 // The current assumption of the fast register allocator is that isel
1665 // won't generate explicit references to the GPR8_NOREX registers. If
1666 // the allocator and/or the backend get enhanced to be more robust in
1667 // that regard, this can be, and should be, removed.
1668 unsigned ResultReg = 0;
1669 if ((I->getOpcode() == Instruction::SRem ||
1670 I->getOpcode() == Instruction::URem) &&
1671 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1672 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1673 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1674 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1675 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1677 // Shift AX right by 8 bits instead of using AH.
1678 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1679 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1681 // Now reference the 8-bit subreg of the result.
1682 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1683 /*Kill=*/true, X86::sub_8bit);
1685 // Copy the result out of the physreg if we haven't already.
1687 ResultReg = createResultReg(TypeEntry.RC);
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1689 .addReg(OpEntry.DivRemResultReg);
1691 updateValueMap(I, ResultReg);
1696 /// \brief Emit a conditional move instruction (if the are supported) to lower
1698 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1699 // Check if the subtarget supports these instructions.
1700 if (!Subtarget->hasCMov())
1703 // FIXME: Add support for i8.
1704 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1707 const Value *Cond = I->getOperand(0);
1708 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1709 bool NeedTest = true;
1710 X86::CondCode CC = X86::COND_NE;
1712 // Optimize conditions coming from a compare if both instructions are in the
1713 // same basic block (values defined in other basic blocks may not have
1714 // initialized registers).
1715 const auto *CI = dyn_cast<CmpInst>(Cond);
1716 if (CI && (CI->getParent() == I->getParent())) {
1717 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1719 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1720 static unsigned SETFOpcTable[2][3] = {
1721 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1722 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1724 unsigned *SETFOpc = nullptr;
1725 switch (Predicate) {
1727 case CmpInst::FCMP_OEQ:
1728 SETFOpc = &SETFOpcTable[0][0];
1729 Predicate = CmpInst::ICMP_NE;
1731 case CmpInst::FCMP_UNE:
1732 SETFOpc = &SETFOpcTable[1][0];
1733 Predicate = CmpInst::ICMP_NE;
1738 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1739 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1741 const Value *CmpLHS = CI->getOperand(0);
1742 const Value *CmpRHS = CI->getOperand(1);
1744 std::swap(CmpLHS, CmpRHS);
1746 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1747 // Emit a compare of the LHS and RHS, setting the flags.
1748 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1752 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1753 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1754 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1756 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1758 auto const &II = TII.get(SETFOpc[2]);
1759 if (II.getNumDefs()) {
1760 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1761 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1762 .addReg(FlagReg2).addReg(FlagReg1);
1764 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1765 .addReg(FlagReg2).addReg(FlagReg1);
1769 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1770 // Fake request the condition, otherwise the intrinsic might be completely
1772 unsigned TmpReg = getRegForValue(Cond);
1780 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1781 // garbage. Indeed, only the less significant bit is supposed to be
1782 // accurate. If we read more than the lsb, we may see non-zero values
1783 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1784 // the select. This is achieved by performing TEST against 1.
1785 unsigned CondReg = getRegForValue(Cond);
1788 bool CondIsKill = hasTrivialKill(Cond);
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1791 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1794 const Value *LHS = I->getOperand(1);
1795 const Value *RHS = I->getOperand(2);
1797 unsigned RHSReg = getRegForValue(RHS);
1798 bool RHSIsKill = hasTrivialKill(RHS);
1800 unsigned LHSReg = getRegForValue(LHS);
1801 bool LHSIsKill = hasTrivialKill(LHS);
1803 if (!LHSReg || !RHSReg)
1806 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1807 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1809 updateValueMap(I, ResultReg);
1813 /// \brief Emit SSE or AVX instructions to lower the select.
1815 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1816 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1817 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
1818 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1819 // Optimize conditions coming from a compare if both instructions are in the
1820 // same basic block (values defined in other basic blocks may not have
1821 // initialized registers).
1822 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1823 if (!CI || (CI->getParent() != I->getParent()))
1826 if (I->getType() != CI->getOperand(0)->getType() ||
1827 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1828 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1831 const Value *CmpLHS = CI->getOperand(0);
1832 const Value *CmpRHS = CI->getOperand(1);
1833 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1835 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1836 // We don't have to materialize a zero constant for this case and can just use
1837 // %x again on the RHS.
1838 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1839 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1840 if (CmpRHSC && CmpRHSC->isNullValue())
1846 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1851 std::swap(CmpLHS, CmpRHS);
1853 // Choose the SSE instruction sequence based on data type (float or double).
1854 static unsigned OpcTable[2][4] = {
1855 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1856 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
1859 unsigned *Opc = nullptr;
1860 switch (RetVT.SimpleTy) {
1861 default: return false;
1862 case MVT::f32: Opc = &OpcTable[0][0]; break;
1863 case MVT::f64: Opc = &OpcTable[1][0]; break;
1866 const Value *LHS = I->getOperand(1);
1867 const Value *RHS = I->getOperand(2);
1869 unsigned LHSReg = getRegForValue(LHS);
1870 bool LHSIsKill = hasTrivialKill(LHS);
1872 unsigned RHSReg = getRegForValue(RHS);
1873 bool RHSIsKill = hasTrivialKill(RHS);
1875 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1876 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1878 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1879 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1881 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1884 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1887 if (Subtarget->hasAVX()) {
1888 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1889 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1890 // uses XMM0 as the selection register. That may need just as many
1891 // instructions as the AND/ANDN/OR sequence due to register moves, so
1893 unsigned CmpOpcode =
1894 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1895 unsigned BlendOpcode =
1896 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1898 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
1899 CmpRHSReg, CmpRHSIsKill, CC);
1900 ResultReg = fastEmitInst_rrr(BlendOpcode, RC, RHSReg, RHSIsKill,
1901 LHSReg, LHSIsKill, CmpReg, true);
1903 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1904 CmpRHSReg, CmpRHSIsKill, CC);
1905 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1907 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1909 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1910 AndReg, /*IsKill=*/true);
1912 updateValueMap(I, ResultReg);
1916 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1917 // These are pseudo CMOV instructions and will be later expanded into control-
1920 switch (RetVT.SimpleTy) {
1921 default: return false;
1922 case MVT::i8: Opc = X86::CMOV_GR8; break;
1923 case MVT::i16: Opc = X86::CMOV_GR16; break;
1924 case MVT::i32: Opc = X86::CMOV_GR32; break;
1925 case MVT::f32: Opc = X86::CMOV_FR32; break;
1926 case MVT::f64: Opc = X86::CMOV_FR64; break;
1929 const Value *Cond = I->getOperand(0);
1930 X86::CondCode CC = X86::COND_NE;
1932 // Optimize conditions coming from a compare if both instructions are in the
1933 // same basic block (values defined in other basic blocks may not have
1934 // initialized registers).
1935 const auto *CI = dyn_cast<CmpInst>(Cond);
1936 if (CI && (CI->getParent() == I->getParent())) {
1938 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1939 if (CC > X86::LAST_VALID_COND)
1942 const Value *CmpLHS = CI->getOperand(0);
1943 const Value *CmpRHS = CI->getOperand(1);
1946 std::swap(CmpLHS, CmpRHS);
1948 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1949 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1952 unsigned CondReg = getRegForValue(Cond);
1955 bool CondIsKill = hasTrivialKill(Cond);
1956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1957 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1960 const Value *LHS = I->getOperand(1);
1961 const Value *RHS = I->getOperand(2);
1963 unsigned LHSReg = getRegForValue(LHS);
1964 bool LHSIsKill = hasTrivialKill(LHS);
1966 unsigned RHSReg = getRegForValue(RHS);
1967 bool RHSIsKill = hasTrivialKill(RHS);
1969 if (!LHSReg || !RHSReg)
1972 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1974 unsigned ResultReg =
1975 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
1976 updateValueMap(I, ResultReg);
1980 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1982 if (!isTypeLegal(I->getType(), RetVT))
1985 // Check if we can fold the select.
1986 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
1987 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1988 const Value *Opnd = nullptr;
1989 switch (Predicate) {
1991 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
1992 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
1994 // No need for a select anymore - this is an unconditional move.
1996 unsigned OpReg = getRegForValue(Opnd);
1999 bool OpIsKill = hasTrivialKill(Opnd);
2000 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2001 unsigned ResultReg = createResultReg(RC);
2002 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2003 TII.get(TargetOpcode::COPY), ResultReg)
2004 .addReg(OpReg, getKillRegState(OpIsKill));
2005 updateValueMap(I, ResultReg);
2010 // First try to use real conditional move instructions.
2011 if (X86FastEmitCMoveSelect(RetVT, I))
2014 // Try to use a sequence of SSE instructions to simulate a conditional move.
2015 if (X86FastEmitSSESelect(RetVT, I))
2018 // Fall-back to pseudo conditional move instructions, which will be later
2019 // converted to control-flow.
2020 if (X86FastEmitPseudoSelect(RetVT, I))
2026 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2027 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2030 // Select integer to float/double conversion.
2031 unsigned OpReg = getRegForValue(I->getOperand(0));
2035 const TargetRegisterClass *RC = nullptr;
2038 if (I->getType()->isDoubleTy()) {
2039 // sitofp int -> double
2040 Opcode = X86::VCVTSI2SDrr;
2041 RC = &X86::FR64RegClass;
2042 } else if (I->getType()->isFloatTy()) {
2043 // sitofp int -> float
2044 Opcode = X86::VCVTSI2SSrr;
2045 RC = &X86::FR32RegClass;
2049 // The target-independent selection algorithm in FastISel already knows how
2050 // to select a SINT_TO_FP if the target is SSE but not AVX. This code is only
2051 // reachable if the subtarget has AVX.
2052 assert(Subtarget->hasAVX() && "Expected a subtarget with AVX!");
2054 unsigned ImplicitDefReg = createResultReg(RC);
2055 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2056 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2057 unsigned ResultReg =
2058 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2059 updateValueMap(I, ResultReg);
2063 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2064 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2066 const TargetRegisterClass *RC) {
2067 assert((I->getOpcode() == Instruction::FPExt ||
2068 I->getOpcode() == Instruction::FPTrunc) &&
2069 "Instruction must be an FPExt or FPTrunc!");
2071 unsigned OpReg = getRegForValue(I->getOperand(0));
2075 unsigned ResultReg = createResultReg(RC);
2076 MachineInstrBuilder MIB;
2077 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2079 if (Subtarget->hasAVX())
2082 updateValueMap(I, ResultReg);
2086 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2087 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2088 I->getOperand(0)->getType()->isFloatTy()) {
2089 // fpext from float to double.
2090 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2091 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2097 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2098 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2099 I->getOperand(0)->getType()->isDoubleTy()) {
2100 // fptrunc from double to float.
2101 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2102 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2108 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2109 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2110 EVT DstVT = TLI.getValueType(I->getType());
2112 // This code only handles truncation to byte.
2113 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2115 if (!TLI.isTypeLegal(SrcVT))
2118 unsigned InputReg = getRegForValue(I->getOperand(0));
2120 // Unhandled operand. Halt "fast" selection and bail.
2123 if (SrcVT == MVT::i8) {
2124 // Truncate from i8 to i1; no code needed.
2125 updateValueMap(I, InputReg);
2129 if (!Subtarget->is64Bit()) {
2130 // If we're on x86-32; we can't extract an i8 from a general register.
2131 // First issue a copy to GR16_ABCD or GR32_ABCD.
2132 const TargetRegisterClass *CopyRC =
2133 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2134 unsigned CopyReg = createResultReg(CopyRC);
2135 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2136 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2140 // Issue an extract_subreg.
2141 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2142 InputReg, /*Kill=*/true,
2147 updateValueMap(I, ResultReg);
2151 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2152 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2155 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2156 X86AddressMode SrcAM, uint64_t Len) {
2158 // Make sure we don't bloat code by inlining very large memcpy's.
2159 if (!IsMemcpySmall(Len))
2162 bool i64Legal = Subtarget->is64Bit();
2164 // We don't care about alignment here since we just emit integer accesses.
2167 if (Len >= 8 && i64Legal)
2177 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2178 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2179 assert(RV && "Failed to emit load or store??");
2181 unsigned Size = VT.getSizeInBits()/8;
2183 DestAM.Disp += Size;
2190 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2191 // FIXME: Handle more intrinsics.
2192 switch (II->getIntrinsicID()) {
2193 default: return false;
2194 case Intrinsic::convert_from_fp16:
2195 case Intrinsic::convert_to_fp16: {
2196 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C())
2199 const Value *Op = II->getArgOperand(0);
2200 unsigned InputReg = getRegForValue(Op);
2204 // F16C only allows converting from float to half and from half to float.
2205 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2206 if (IsFloatToHalf) {
2207 if (!Op->getType()->isFloatTy())
2210 if (!II->getType()->isFloatTy())
2214 unsigned ResultReg = 0;
2215 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2216 if (IsFloatToHalf) {
2217 // 'InputReg' is implicitly promoted from register class FR32 to
2218 // register class VR128 by method 'constrainOperandRegClass' which is
2219 // directly called by 'fastEmitInst_ri'.
2220 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2221 // used to provide rounding control.
2222 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2224 // Move the lower 32-bits of ResultReg to another register of class GR32.
2225 ResultReg = createResultReg(&X86::GR32RegClass);
2226 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2227 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2228 .addReg(InputReg, RegState::Kill);
2230 // The result value is in the lower 16-bits of ResultReg.
2231 unsigned RegIdx = X86::sub_16bit;
2232 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2234 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2235 // Explicitly sign-extend the input to 32-bit.
2236 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2239 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2240 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2241 InputReg, /*Kill=*/true);
2243 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2245 // The result value is in the lower 32-bits of ResultReg.
2246 // Emit an explicit copy from register class VR128 to register class FR32.
2247 ResultReg = createResultReg(&X86::FR32RegClass);
2248 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2249 TII.get(TargetOpcode::COPY), ResultReg)
2250 .addReg(InputReg, RegState::Kill);
2253 updateValueMap(II, ResultReg);
2256 case Intrinsic::frameaddress: {
2257 MachineFunction *MF = FuncInfo.MF;
2258 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2261 Type *RetTy = II->getCalledFunction()->getReturnType();
2264 if (!isTypeLegal(RetTy, VT))
2268 const TargetRegisterClass *RC = nullptr;
2270 switch (VT.SimpleTy) {
2271 default: llvm_unreachable("Invalid result type for frameaddress.");
2272 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2273 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2276 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2277 // we get the wrong frame register.
2278 MachineFrameInfo *MFI = MF->getFrameInfo();
2279 MFI->setFrameAddressIsTaken(true);
2281 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2282 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2283 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2284 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2285 "Invalid Frame Register!");
2287 // Always make a copy of the frame register to to a vreg first, so that we
2288 // never directly reference the frame register (the TwoAddressInstruction-
2289 // Pass doesn't like that).
2290 unsigned SrcReg = createResultReg(RC);
2291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2292 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2294 // Now recursively load from the frame address.
2295 // movq (%rbp), %rax
2296 // movq (%rax), %rax
2297 // movq (%rax), %rax
2300 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2302 DestReg = createResultReg(RC);
2303 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2304 TII.get(Opc), DestReg), SrcReg);
2308 updateValueMap(II, SrcReg);
2311 case Intrinsic::memcpy: {
2312 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2313 // Don't handle volatile or variable length memcpys.
2314 if (MCI->isVolatile())
2317 if (isa<ConstantInt>(MCI->getLength())) {
2318 // Small memcpy's are common enough that we want to do them
2319 // without a call if possible.
2320 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2321 if (IsMemcpySmall(Len)) {
2322 X86AddressMode DestAM, SrcAM;
2323 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2324 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2326 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2331 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2332 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2335 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2338 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2340 case Intrinsic::memset: {
2341 const MemSetInst *MSI = cast<MemSetInst>(II);
2343 if (MSI->isVolatile())
2346 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2347 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2350 if (MSI->getDestAddressSpace() > 255)
2353 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2355 case Intrinsic::stackprotector: {
2356 // Emit code to store the stack guard onto the stack.
2357 EVT PtrTy = TLI.getPointerTy();
2359 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2360 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2362 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2364 // Grab the frame index.
2366 if (!X86SelectAddress(Slot, AM)) return false;
2367 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2370 case Intrinsic::dbg_declare: {
2371 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2373 assert(DI->getAddress() && "Null address should be checked earlier!");
2374 if (!X86SelectAddress(DI->getAddress(), AM))
2376 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2377 // FIXME may need to add RegState::Debug to any registers produced,
2378 // although ESP/EBP should be the only ones at the moment.
2379 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2381 .addMetadata(DI->getVariable())
2382 .addMetadata(DI->getExpression());
2385 case Intrinsic::trap: {
2386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2389 case Intrinsic::sqrt: {
2390 if (!Subtarget->hasSSE1())
2393 Type *RetTy = II->getCalledFunction()->getReturnType();
2396 if (!isTypeLegal(RetTy, VT))
2399 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2400 // is not generated by FastISel yet.
2401 // FIXME: Update this code once tablegen can handle it.
2402 static const unsigned SqrtOpc[2][2] = {
2403 {X86::SQRTSSr, X86::VSQRTSSr},
2404 {X86::SQRTSDr, X86::VSQRTSDr}
2406 bool HasAVX = Subtarget->hasAVX();
2408 const TargetRegisterClass *RC;
2409 switch (VT.SimpleTy) {
2410 default: return false;
2411 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2412 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2415 const Value *SrcVal = II->getArgOperand(0);
2416 unsigned SrcReg = getRegForValue(SrcVal);
2421 unsigned ImplicitDefReg = 0;
2423 ImplicitDefReg = createResultReg(RC);
2424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2425 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2428 unsigned ResultReg = createResultReg(RC);
2429 MachineInstrBuilder MIB;
2430 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2434 MIB.addReg(ImplicitDefReg);
2438 updateValueMap(II, ResultReg);
2441 case Intrinsic::sadd_with_overflow:
2442 case Intrinsic::uadd_with_overflow:
2443 case Intrinsic::ssub_with_overflow:
2444 case Intrinsic::usub_with_overflow:
2445 case Intrinsic::smul_with_overflow:
2446 case Intrinsic::umul_with_overflow: {
2447 // This implements the basic lowering of the xalu with overflow intrinsics
2448 // into add/sub/mul followed by either seto or setb.
2449 const Function *Callee = II->getCalledFunction();
2450 auto *Ty = cast<StructType>(Callee->getReturnType());
2451 Type *RetTy = Ty->getTypeAtIndex(0U);
2452 Type *CondTy = Ty->getTypeAtIndex(1);
2455 if (!isTypeLegal(RetTy, VT))
2458 if (VT < MVT::i8 || VT > MVT::i64)
2461 const Value *LHS = II->getArgOperand(0);
2462 const Value *RHS = II->getArgOperand(1);
2464 // Canonicalize immediate to the RHS.
2465 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2466 isCommutativeIntrinsic(II))
2467 std::swap(LHS, RHS);
2469 bool UseIncDec = false;
2470 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2473 unsigned BaseOpc, CondOpc;
2474 switch (II->getIntrinsicID()) {
2475 default: llvm_unreachable("Unexpected intrinsic!");
2476 case Intrinsic::sadd_with_overflow:
2477 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2478 CondOpc = X86::SETOr;
2480 case Intrinsic::uadd_with_overflow:
2481 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2482 case Intrinsic::ssub_with_overflow:
2483 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2484 CondOpc = X86::SETOr;
2486 case Intrinsic::usub_with_overflow:
2487 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2488 case Intrinsic::smul_with_overflow:
2489 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2490 case Intrinsic::umul_with_overflow:
2491 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2494 unsigned LHSReg = getRegForValue(LHS);
2497 bool LHSIsKill = hasTrivialKill(LHS);
2499 unsigned ResultReg = 0;
2500 // Check if we have an immediate version.
2501 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2502 static const unsigned Opc[2][4] = {
2503 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2504 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2507 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2508 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2509 bool IsDec = BaseOpc == X86ISD::DEC;
2510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2511 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2512 .addReg(LHSReg, getKillRegState(LHSIsKill));
2514 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2515 CI->getZExtValue());
2521 RHSReg = getRegForValue(RHS);
2524 RHSIsKill = hasTrivialKill(RHS);
2525 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2529 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2531 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2532 static const unsigned MULOpc[] =
2533 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2534 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2535 // First copy the first operand into RAX, which is an implicit input to
2536 // the X86::MUL*r instruction.
2537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2538 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2539 .addReg(LHSReg, getKillRegState(LHSIsKill));
2540 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2541 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2542 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2543 static const unsigned MULOpc[] =
2544 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2545 if (VT == MVT::i8) {
2546 // Copy the first operand into AL, which is an implicit input to the
2547 // X86::IMUL8r instruction.
2548 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2549 TII.get(TargetOpcode::COPY), X86::AL)
2550 .addReg(LHSReg, getKillRegState(LHSIsKill));
2551 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2554 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2555 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2562 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2563 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2564 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2567 updateValueMap(II, ResultReg, 2);
2570 case Intrinsic::x86_sse_cvttss2si:
2571 case Intrinsic::x86_sse_cvttss2si64:
2572 case Intrinsic::x86_sse2_cvttsd2si:
2573 case Intrinsic::x86_sse2_cvttsd2si64: {
2575 switch (II->getIntrinsicID()) {
2576 default: llvm_unreachable("Unexpected intrinsic.");
2577 case Intrinsic::x86_sse_cvttss2si:
2578 case Intrinsic::x86_sse_cvttss2si64:
2579 if (!Subtarget->hasSSE1())
2581 IsInputDouble = false;
2583 case Intrinsic::x86_sse2_cvttsd2si:
2584 case Intrinsic::x86_sse2_cvttsd2si64:
2585 if (!Subtarget->hasSSE2())
2587 IsInputDouble = true;
2591 Type *RetTy = II->getCalledFunction()->getReturnType();
2593 if (!isTypeLegal(RetTy, VT))
2596 static const unsigned CvtOpc[2][2][2] = {
2597 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2598 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2599 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2600 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2602 bool HasAVX = Subtarget->hasAVX();
2604 switch (VT.SimpleTy) {
2605 default: llvm_unreachable("Unexpected result type.");
2606 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2607 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2610 // Check if we can fold insertelement instructions into the convert.
2611 const Value *Op = II->getArgOperand(0);
2612 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2613 const Value *Index = IE->getOperand(2);
2614 if (!isa<ConstantInt>(Index))
2616 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2619 Op = IE->getOperand(1);
2622 Op = IE->getOperand(0);
2625 unsigned Reg = getRegForValue(Op);
2629 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2630 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2633 updateValueMap(II, ResultReg);
2639 bool X86FastISel::fastLowerArguments() {
2640 if (!FuncInfo.CanLowerReturn)
2643 const Function *F = FuncInfo.Fn;
2647 CallingConv::ID CC = F->getCallingConv();
2648 if (CC != CallingConv::C)
2651 if (Subtarget->isCallingConvWin64(CC))
2654 if (!Subtarget->is64Bit())
2657 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2658 unsigned GPRCnt = 0;
2659 unsigned FPRCnt = 0;
2661 for (auto const &Arg : F->args()) {
2662 // The first argument is at index 1.
2664 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2665 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2666 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2667 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2670 Type *ArgTy = Arg.getType();
2671 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2674 EVT ArgVT = TLI.getValueType(ArgTy);
2675 if (!ArgVT.isSimple()) return false;
2676 switch (ArgVT.getSimpleVT().SimpleTy) {
2677 default: return false;
2684 if (!Subtarget->hasSSE1())
2697 static const MCPhysReg GPR32ArgRegs[] = {
2698 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2700 static const MCPhysReg GPR64ArgRegs[] = {
2701 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2703 static const MCPhysReg XMMArgRegs[] = {
2704 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2705 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2708 unsigned GPRIdx = 0;
2709 unsigned FPRIdx = 0;
2710 for (auto const &Arg : F->args()) {
2711 MVT VT = TLI.getSimpleValueType(Arg.getType());
2712 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2714 switch (VT.SimpleTy) {
2715 default: llvm_unreachable("Unexpected value type.");
2716 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2717 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2718 case MVT::f32: // fall-through
2719 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2721 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2722 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2723 // Without this, EmitLiveInCopies may eliminate the livein if its only
2724 // use is a bitcast (which isn't turned into an instruction).
2725 unsigned ResultReg = createResultReg(RC);
2726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2727 TII.get(TargetOpcode::COPY), ResultReg)
2728 .addReg(DstReg, getKillRegState(true));
2729 updateValueMap(&Arg, ResultReg);
2734 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2736 ImmutableCallSite *CS) {
2737 if (Subtarget->is64Bit())
2739 if (Subtarget->getTargetTriple().isOSMSVCRT())
2741 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2742 CC == CallingConv::HiPE)
2744 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2746 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2751 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2752 auto &OutVals = CLI.OutVals;
2753 auto &OutFlags = CLI.OutFlags;
2754 auto &OutRegs = CLI.OutRegs;
2755 auto &Ins = CLI.Ins;
2756 auto &InRegs = CLI.InRegs;
2757 CallingConv::ID CC = CLI.CallConv;
2758 bool &IsTailCall = CLI.IsTailCall;
2759 bool IsVarArg = CLI.IsVarArg;
2760 const Value *Callee = CLI.Callee;
2761 const char *SymName = CLI.SymName;
2763 bool Is64Bit = Subtarget->is64Bit();
2764 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2766 // Handle only C, fastcc, and webkit_js calling conventions for now.
2768 default: return false;
2769 case CallingConv::C:
2770 case CallingConv::Fast:
2771 case CallingConv::WebKit_JS:
2772 case CallingConv::X86_FastCall:
2773 case CallingConv::X86_64_Win64:
2774 case CallingConv::X86_64_SysV:
2778 // Allow SelectionDAG isel to handle tail calls.
2782 // fastcc with -tailcallopt is intended to provide a guaranteed
2783 // tail call optimization. Fastisel doesn't know how to do that.
2784 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2787 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2788 // x86-32. Special handling for x86-64 is implemented.
2789 if (IsVarArg && IsWin64)
2792 // Don't know about inalloca yet.
2793 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2796 // Fast-isel doesn't know about callee-pop yet.
2797 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2798 TM.Options.GuaranteedTailCallOpt))
2801 SmallVector<MVT, 16> OutVTs;
2802 SmallVector<unsigned, 16> ArgRegs;
2804 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2805 // instruction. This is safe because it is common to all FastISel supported
2806 // calling conventions on x86.
2807 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2808 Value *&Val = OutVals[i];
2809 ISD::ArgFlagsTy Flags = OutFlags[i];
2810 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2811 if (CI->getBitWidth() < 32) {
2813 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2815 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2819 // Passing bools around ends up doing a trunc to i1 and passing it.
2820 // Codegen this as an argument + "and 1".
2822 auto *TI = dyn_cast<TruncInst>(Val);
2824 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2825 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2827 Value *PrevVal = TI->getOperand(0);
2828 ResultReg = getRegForValue(PrevVal);
2833 if (!isTypeLegal(PrevVal->getType(), VT))
2837 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2839 if (!isTypeLegal(Val->getType(), VT))
2841 ResultReg = getRegForValue(Val);
2847 ArgRegs.push_back(ResultReg);
2848 OutVTs.push_back(VT);
2851 // Analyze operands of the call, assigning locations to each operand.
2852 SmallVector<CCValAssign, 16> ArgLocs;
2853 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2855 // Allocate shadow area for Win64
2857 CCInfo.AllocateStack(32, 8);
2859 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2861 // Get a count of how many bytes are to be pushed on the stack.
2862 unsigned NumBytes = CCInfo.getNextStackOffset();
2864 // Issue CALLSEQ_START
2865 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2867 .addImm(NumBytes).addImm(0);
2869 // Walk the register/memloc assignments, inserting copies/loads.
2870 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2871 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2872 CCValAssign const &VA = ArgLocs[i];
2873 const Value *ArgVal = OutVals[VA.getValNo()];
2874 MVT ArgVT = OutVTs[VA.getValNo()];
2876 if (ArgVT == MVT::x86mmx)
2879 unsigned ArgReg = ArgRegs[VA.getValNo()];
2881 // Promote the value if needed.
2882 switch (VA.getLocInfo()) {
2883 case CCValAssign::Full: break;
2884 case CCValAssign::SExt: {
2885 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2886 "Unexpected extend");
2887 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2889 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2890 ArgVT = VA.getLocVT();
2893 case CCValAssign::ZExt: {
2894 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2895 "Unexpected extend");
2896 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2898 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2899 ArgVT = VA.getLocVT();
2902 case CCValAssign::AExt: {
2903 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2904 "Unexpected extend");
2905 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2908 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2911 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2914 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2915 ArgVT = VA.getLocVT();
2918 case CCValAssign::BCvt: {
2919 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2920 /*TODO: Kill=*/false);
2921 assert(ArgReg && "Failed to emit a bitcast!");
2922 ArgVT = VA.getLocVT();
2925 case CCValAssign::VExt:
2926 // VExt has not been implemented, so this should be impossible to reach
2927 // for now. However, fallback to Selection DAG isel once implemented.
2929 case CCValAssign::AExtUpper:
2930 case CCValAssign::SExtUpper:
2931 case CCValAssign::ZExtUpper:
2932 case CCValAssign::FPExt:
2933 llvm_unreachable("Unexpected loc info!");
2934 case CCValAssign::Indirect:
2935 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2940 if (VA.isRegLoc()) {
2941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2942 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2943 OutRegs.push_back(VA.getLocReg());
2945 assert(VA.isMemLoc());
2947 // Don't emit stores for undef values.
2948 if (isa<UndefValue>(ArgVal))
2951 unsigned LocMemOffset = VA.getLocMemOffset();
2953 AM.Base.Reg = RegInfo->getStackRegister();
2954 AM.Disp = LocMemOffset;
2955 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
2956 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2957 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2958 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
2959 ArgVT.getStoreSize(), Alignment);
2960 if (Flags.isByVal()) {
2961 X86AddressMode SrcAM;
2962 SrcAM.Base.Reg = ArgReg;
2963 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
2965 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2966 // If this is a really simple value, emit this with the Value* version
2967 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2968 // as it can cause us to reevaluate the argument.
2969 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
2972 bool ValIsKill = hasTrivialKill(ArgVal);
2973 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
2979 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2981 if (Subtarget->isPICStyleGOT()) {
2982 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2984 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2987 if (Is64Bit && IsVarArg && !IsWin64) {
2988 // From AMD64 ABI document:
2989 // For calls that may call functions that use varargs or stdargs
2990 // (prototype-less calls or calls to functions containing ellipsis (...) in
2991 // the declaration) %al is used as hidden argument to specify the number
2992 // of SSE registers used. The contents of %al do not need to match exactly
2993 // the number of registers, but must be an ubound on the number of SSE
2994 // registers used and is in the range 0 - 8 inclusive.
2996 // Count the number of XMM registers allocated.
2997 static const MCPhysReg XMMArgRegs[] = {
2998 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2999 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3001 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3002 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3003 && "SSE registers cannot be used when SSE is disabled");
3004 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3005 X86::AL).addImm(NumXMMRegs);
3008 // Materialize callee address in a register. FIXME: GV address can be
3009 // handled with a CALLpcrel32 instead.
3010 X86AddressMode CalleeAM;
3011 if (!X86SelectCallAddress(Callee, CalleeAM))
3014 unsigned CalleeOp = 0;
3015 const GlobalValue *GV = nullptr;
3016 if (CalleeAM.GV != nullptr) {
3018 } else if (CalleeAM.Base.Reg != 0) {
3019 CalleeOp = CalleeAM.Base.Reg;
3024 MachineInstrBuilder MIB;
3026 // Register-indirect call.
3027 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3028 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3032 assert(GV && "Not a direct call");
3033 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3035 // See if we need any target-specific flags on the GV operand.
3036 unsigned char OpFlags = 0;
3038 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3039 // external symbols most go through the PLT in PIC mode. If the symbol
3040 // has hidden or protected visibility, or if it is static or local, then
3041 // we don't need to use the PLT - we can directly call it.
3042 if (Subtarget->isTargetELF() &&
3043 TM.getRelocationModel() == Reloc::PIC_ &&
3044 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3045 OpFlags = X86II::MO_PLT;
3046 } else if (Subtarget->isPICStyleStubAny() &&
3047 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3048 (!Subtarget->getTargetTriple().isMacOSX() ||
3049 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3050 // PC-relative references to external symbols should go through $stub,
3051 // unless we're building with the leopard linker or later, which
3052 // automatically synthesizes these stubs.
3053 OpFlags = X86II::MO_DARWIN_STUB;
3056 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3058 MIB.addExternalSymbol(SymName, OpFlags);
3060 MIB.addGlobalAddress(GV, 0, OpFlags);
3063 // Add a register mask operand representing the call-preserved registers.
3064 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3065 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3067 // Add an implicit use GOT pointer in EBX.
3068 if (Subtarget->isPICStyleGOT())
3069 MIB.addReg(X86::EBX, RegState::Implicit);
3071 if (Is64Bit && IsVarArg && !IsWin64)
3072 MIB.addReg(X86::AL, RegState::Implicit);
3074 // Add implicit physical register uses to the call.
3075 for (auto Reg : OutRegs)
3076 MIB.addReg(Reg, RegState::Implicit);
3078 // Issue CALLSEQ_END
3079 unsigned NumBytesForCalleeToPop =
3080 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3081 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3083 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3085 // Now handle call return values.
3086 SmallVector<CCValAssign, 16> RVLocs;
3087 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3088 CLI.RetTy->getContext());
3089 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3091 // Copy all of the result registers out of their specified physreg.
3092 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3093 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3094 CCValAssign &VA = RVLocs[i];
3095 EVT CopyVT = VA.getValVT();
3096 unsigned CopyReg = ResultReg + i;
3098 // If this is x86-64, and we disabled SSE, we can't return FP values
3099 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3100 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3101 report_fatal_error("SSE register return with SSE disabled");
3104 // If we prefer to use the value in xmm registers, copy it out as f80 and
3105 // use a truncate to move it from fp stack reg to xmm reg.
3106 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3107 isScalarFPTypeInSSEReg(VA.getValVT())) {
3109 CopyReg = createResultReg(&X86::RFP80RegClass);
3112 // Copy out the result.
3113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3114 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3115 InRegs.push_back(VA.getLocReg());
3117 // Round the f80 to the right size, which also moves it to the appropriate
3118 // xmm register. This is accomplished by storing the f80 value in memory
3119 // and then loading it back.
3120 if (CopyVT != VA.getValVT()) {
3121 EVT ResVT = VA.getValVT();
3122 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3123 unsigned MemSize = ResVT.getSizeInBits()/8;
3124 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3125 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3128 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3129 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3130 TII.get(Opc), ResultReg + i), FI);
3134 CLI.ResultReg = ResultReg;
3135 CLI.NumResultRegs = RVLocs.size();
3142 X86FastISel::fastSelectInstruction(const Instruction *I) {
3143 switch (I->getOpcode()) {
3145 case Instruction::Load:
3146 return X86SelectLoad(I);
3147 case Instruction::Store:
3148 return X86SelectStore(I);
3149 case Instruction::Ret:
3150 return X86SelectRet(I);
3151 case Instruction::ICmp:
3152 case Instruction::FCmp:
3153 return X86SelectCmp(I);
3154 case Instruction::ZExt:
3155 return X86SelectZExt(I);
3156 case Instruction::Br:
3157 return X86SelectBranch(I);
3158 case Instruction::LShr:
3159 case Instruction::AShr:
3160 case Instruction::Shl:
3161 return X86SelectShift(I);
3162 case Instruction::SDiv:
3163 case Instruction::UDiv:
3164 case Instruction::SRem:
3165 case Instruction::URem:
3166 return X86SelectDivRem(I);
3167 case Instruction::Select:
3168 return X86SelectSelect(I);
3169 case Instruction::Trunc:
3170 return X86SelectTrunc(I);
3171 case Instruction::FPExt:
3172 return X86SelectFPExt(I);
3173 case Instruction::FPTrunc:
3174 return X86SelectFPTrunc(I);
3175 case Instruction::SIToFP:
3176 return X86SelectSIToFP(I);
3177 case Instruction::IntToPtr: // Deliberate fall-through.
3178 case Instruction::PtrToInt: {
3179 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3180 EVT DstVT = TLI.getValueType(I->getType());
3181 if (DstVT.bitsGT(SrcVT))
3182 return X86SelectZExt(I);
3183 if (DstVT.bitsLT(SrcVT))
3184 return X86SelectTrunc(I);
3185 unsigned Reg = getRegForValue(I->getOperand(0));
3186 if (Reg == 0) return false;
3187 updateValueMap(I, Reg);
3195 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3199 uint64_t Imm = CI->getZExtValue();
3201 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3202 switch (VT.SimpleTy) {
3203 default: llvm_unreachable("Unexpected value type");
3206 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3209 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3214 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3216 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3217 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3224 switch (VT.SimpleTy) {
3225 default: llvm_unreachable("Unexpected value type");
3226 case MVT::i1: VT = MVT::i8; // fall-through
3227 case MVT::i8: Opc = X86::MOV8ri; break;
3228 case MVT::i16: Opc = X86::MOV16ri; break;
3229 case MVT::i32: Opc = X86::MOV32ri; break;
3231 if (isUInt<32>(Imm))
3233 else if (isInt<32>(Imm))
3234 Opc = X86::MOV64ri32;
3240 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3241 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3242 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3244 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3245 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3248 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3251 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3252 if (CFP->isNullValue())
3253 return fastMaterializeFloatZero(CFP);
3255 // Can't handle alternate code models yet.
3256 CodeModel::Model CM = TM.getCodeModel();
3257 if (CM != CodeModel::Small && CM != CodeModel::Large)
3260 // Get opcode and regclass of the output for the given load instruction.
3262 const TargetRegisterClass *RC = nullptr;
3263 switch (VT.SimpleTy) {
3266 if (X86ScalarSSEf32) {
3267 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3268 RC = &X86::FR32RegClass;
3270 Opc = X86::LD_Fp32m;
3271 RC = &X86::RFP32RegClass;
3275 if (X86ScalarSSEf64) {
3276 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3277 RC = &X86::FR64RegClass;
3279 Opc = X86::LD_Fp64m;
3280 RC = &X86::RFP64RegClass;
3284 // No f80 support yet.
3288 // MachineConstantPool wants an explicit alignment.
3289 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3291 // Alignment of vector types. FIXME!
3292 Align = DL.getTypeAllocSize(CFP->getType());
3295 // x86-32 PIC requires a PIC base register for constant pools.
3296 unsigned PICBase = 0;
3297 unsigned char OpFlag = 0;
3298 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3299 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3300 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3301 } else if (Subtarget->isPICStyleGOT()) {
3302 OpFlag = X86II::MO_GOTOFF;
3303 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3304 } else if (Subtarget->isPICStyleRIPRel() &&
3305 TM.getCodeModel() == CodeModel::Small) {
3309 // Create the load from the constant pool.
3310 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3311 unsigned ResultReg = createResultReg(RC);
3313 if (CM == CodeModel::Large) {
3314 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3317 .addConstantPoolIndex(CPI, 0, OpFlag);
3318 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3319 TII.get(Opc), ResultReg);
3320 addDirectMem(MIB, AddrReg);
3321 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3322 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3323 TM.getDataLayout()->getPointerSize(), Align);
3324 MIB->addMemOperand(*FuncInfo.MF, MMO);
3328 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3329 TII.get(Opc), ResultReg),
3330 CPI, PICBase, OpFlag);
3334 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3335 // Can't handle alternate code models yet.
3336 if (TM.getCodeModel() != CodeModel::Small)
3339 // Materialize addresses with LEA/MOV instructions.
3341 if (X86SelectAddress(GV, AM)) {
3342 // If the expression is just a basereg, then we're done, otherwise we need
3344 if (AM.BaseType == X86AddressMode::RegBase &&
3345 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3348 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3349 if (TM.getRelocationModel() == Reloc::Static &&
3350 TLI.getPointerTy() == MVT::i64) {
3351 // The displacement code could be more than 32 bits away so we need to use
3352 // an instruction with a 64 bit immediate
3353 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3355 .addGlobalAddress(GV);
3357 unsigned Opc = TLI.getPointerTy() == MVT::i32
3358 ? (Subtarget->isTarget64BitILP32()
3359 ? X86::LEA64_32r : X86::LEA32r)
3361 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3362 TII.get(Opc), ResultReg), AM);
3369 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3370 EVT CEVT = TLI.getValueType(C->getType(), true);
3372 // Only handle simple types.
3373 if (!CEVT.isSimple())
3375 MVT VT = CEVT.getSimpleVT();
3377 if (const auto *CI = dyn_cast<ConstantInt>(C))
3378 return X86MaterializeInt(CI, VT);
3379 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3380 return X86MaterializeFP(CFP, VT);
3381 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3382 return X86MaterializeGV(GV, VT);
3387 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3388 // Fail on dynamic allocas. At this point, getRegForValue has already
3389 // checked its CSE maps, so if we're here trying to handle a dynamic
3390 // alloca, we're not going to succeed. X86SelectAddress has a
3391 // check for dynamic allocas, because it's called directly from
3392 // various places, but targetMaterializeAlloca also needs a check
3393 // in order to avoid recursion between getRegForValue,
3394 // X86SelectAddrss, and targetMaterializeAlloca.
3395 if (!FuncInfo.StaticAllocaMap.count(C))
3397 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3400 if (!X86SelectAddress(C, AM))
3402 unsigned Opc = TLI.getPointerTy() == MVT::i32
3403 ? (Subtarget->isTarget64BitILP32()
3404 ? X86::LEA64_32r : X86::LEA32r)
3406 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3407 unsigned ResultReg = createResultReg(RC);
3408 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3409 TII.get(Opc), ResultReg), AM);
3413 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3415 if (!isTypeLegal(CF->getType(), VT))
3418 // Get opcode and regclass for the given zero.
3420 const TargetRegisterClass *RC = nullptr;
3421 switch (VT.SimpleTy) {
3424 if (X86ScalarSSEf32) {
3425 Opc = X86::FsFLD0SS;
3426 RC = &X86::FR32RegClass;
3428 Opc = X86::LD_Fp032;
3429 RC = &X86::RFP32RegClass;
3433 if (X86ScalarSSEf64) {
3434 Opc = X86::FsFLD0SD;
3435 RC = &X86::FR64RegClass;
3437 Opc = X86::LD_Fp064;
3438 RC = &X86::RFP64RegClass;
3442 // No f80 support yet.
3446 unsigned ResultReg = createResultReg(RC);
3447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3452 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3453 const LoadInst *LI) {
3454 const Value *Ptr = LI->getPointerOperand();
3456 if (!X86SelectAddress(Ptr, AM))
3459 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3461 unsigned Size = DL.getTypeAllocSize(LI->getType());
3462 unsigned Alignment = LI->getAlignment();
3464 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3465 Alignment = DL.getABITypeAlignment(LI->getType());
3467 SmallVector<MachineOperand, 8> AddrOps;
3468 AM.getFullAddress(AddrOps);
3470 MachineInstr *Result =
3471 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps,
3472 Size, Alignment, /*AllowCommute=*/true);
3476 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3477 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3478 MI->eraseFromParent();
3484 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3485 const TargetLibraryInfo *libInfo) {
3486 return new X86FastISel(funcInfo, libInfo);