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/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetOptions.h"
46 class X86FastISel final : public FastISel {
47 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
48 /// make the right decision when generating code for different targets.
49 const X86Subtarget *Subtarget;
51 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52 /// floating point ops.
53 /// When SSE is available, use it for f32 operations.
54 /// When SSE2 is available, use it for f64 operations.
59 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
60 const TargetLibraryInfo *libInfo)
61 : FastISel(funcInfo, libInfo) {
62 Subtarget = &TM.getSubtarget<X86Subtarget>();
63 X86ScalarSSEf64 = Subtarget->hasSSE2();
64 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 bool TargetSelectInstruction(const Instruction *I) override;
69 /// \brief The specified machine instr operand is a vreg, and that
70 /// vreg is being provided by the specified load instruction. If possible,
71 /// try to fold the load as an operand to the instruction, returning true if
73 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
74 const LoadInst *LI) override;
76 bool FastLowerArguments() override;
77 bool FastLowerCall(CallLoweringInfo &CLI) override;
78 bool FastLowerIntrinsicCall(const IntrinsicInst *II) override;
80 #include "X86GenFastISel.inc"
83 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
85 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
88 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
89 MachineMemOperand *MMO = nullptr, bool Aligned = false);
90 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
91 const X86AddressMode &AM,
92 MachineMemOperand *MMO = nullptr, bool Aligned = false);
94 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
97 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
98 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
100 bool X86SelectLoad(const Instruction *I);
102 bool X86SelectStore(const Instruction *I);
104 bool X86SelectRet(const Instruction *I);
106 bool X86SelectCmp(const Instruction *I);
108 bool X86SelectZExt(const Instruction *I);
110 bool X86SelectBranch(const Instruction *I);
112 bool X86SelectShift(const Instruction *I);
114 bool X86SelectDivRem(const Instruction *I);
116 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
118 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
120 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
122 bool X86SelectSelect(const Instruction *I);
124 bool X86SelectTrunc(const Instruction *I);
126 bool X86SelectFPExt(const Instruction *I);
127 bool X86SelectFPTrunc(const Instruction *I);
129 const X86InstrInfo *getInstrInfo() const {
130 return getTargetMachine()->getSubtargetImpl()->getInstrInfo();
132 const X86TargetMachine *getTargetMachine() const {
133 return static_cast<const X86TargetMachine *>(&TM);
136 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
138 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
139 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
140 unsigned X86MaterializeGV(const GlobalValue *GV,MVT VT);
141 unsigned TargetMaterializeConstant(const Constant *C) override;
143 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
145 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
147 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
148 /// computed in an SSE register, not on the X87 floating point stack.
149 bool isScalarFPTypeInSSEReg(EVT VT) const {
150 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
151 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
154 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
156 bool IsMemcpySmall(uint64_t Len);
158 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
159 X86AddressMode SrcAM, uint64_t Len);
161 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
165 } // end anonymous namespace.
167 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
168 // If both operands are the same, then try to optimize or fold the cmp.
169 CmpInst::Predicate Predicate = CI->getPredicate();
170 if (CI->getOperand(0) != CI->getOperand(1))
174 default: llvm_unreachable("Invalid predicate!");
175 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
176 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
177 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
178 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
179 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
180 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
181 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
182 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
183 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
184 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
185 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
186 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
187 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
188 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
189 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
190 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
192 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
193 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
194 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
195 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
196 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
197 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
198 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
199 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
200 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
201 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
207 static std::pair<X86::CondCode, bool>
208 getX86ConditionCode(CmpInst::Predicate Predicate) {
209 X86::CondCode CC = X86::COND_INVALID;
210 bool NeedSwap = false;
213 // Floating-point Predicates
214 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
215 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
216 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
217 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
218 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
219 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
220 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
221 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
222 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
223 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
224 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
225 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
226 case CmpInst::FCMP_OEQ: // fall-through
227 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
229 // Integer Predicates
230 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
231 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
232 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
233 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
234 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
235 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
236 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
237 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
238 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
239 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
242 return std::make_pair(CC, NeedSwap);
245 static std::pair<unsigned, bool>
246 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
248 bool NeedSwap = false;
250 // SSE Condition code mapping:
260 default: llvm_unreachable("Unexpected predicate");
261 case CmpInst::FCMP_OEQ: CC = 0; break;
262 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
263 case CmpInst::FCMP_OLT: CC = 1; break;
264 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
265 case CmpInst::FCMP_OLE: CC = 2; break;
266 case CmpInst::FCMP_UNO: CC = 3; break;
267 case CmpInst::FCMP_UNE: CC = 4; break;
268 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
269 case CmpInst::FCMP_UGE: CC = 5; break;
270 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
271 case CmpInst::FCMP_UGT: CC = 6; break;
272 case CmpInst::FCMP_ORD: CC = 7; break;
273 case CmpInst::FCMP_UEQ:
274 case CmpInst::FCMP_ONE: CC = 8; break;
277 return std::make_pair(CC, NeedSwap);
280 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
281 /// into the user. The condition code will only be updated on success.
282 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
284 if (!isa<ExtractValueInst>(Cond))
287 const auto *EV = cast<ExtractValueInst>(Cond);
288 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
291 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
293 const Function *Callee = II->getCalledFunction();
295 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
296 if (!isTypeLegal(RetTy, RetVT))
299 if (RetVT != MVT::i32 && RetVT != MVT::i64)
303 switch (II->getIntrinsicID()) {
304 default: return false;
305 case Intrinsic::sadd_with_overflow:
306 case Intrinsic::ssub_with_overflow:
307 case Intrinsic::smul_with_overflow:
308 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
309 case Intrinsic::uadd_with_overflow:
310 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
313 // Check if both instructions are in the same basic block.
314 if (II->getParent() != I->getParent())
317 // Make sure nothing is in the way
318 BasicBlock::const_iterator Start = I;
319 BasicBlock::const_iterator End = II;
320 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
321 // We only expect extractvalue instructions between the intrinsic and the
322 // instruction to be selected.
323 if (!isa<ExtractValueInst>(Itr))
326 // Check that the extractvalue operand comes from the intrinsic.
327 const auto *EVI = cast<ExtractValueInst>(Itr);
328 if (EVI->getAggregateOperand() != II)
336 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
337 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
338 if (evt == MVT::Other || !evt.isSimple())
339 // Unhandled type. Halt "fast" selection and bail.
342 VT = evt.getSimpleVT();
343 // For now, require SSE/SSE2 for performing floating-point operations,
344 // since x87 requires additional work.
345 if (VT == MVT::f64 && !X86ScalarSSEf64)
347 if (VT == MVT::f32 && !X86ScalarSSEf32)
349 // Similarly, no f80 support yet.
352 // We only handle legal types. For example, on x86-32 the instruction
353 // selector contains all of the 64-bit instructions from x86-64,
354 // under the assumption that i64 won't be used if the target doesn't
356 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
359 #include "X86GenCallingConv.inc"
361 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
362 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
363 /// Return true and the result register by reference if it is possible.
364 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
365 MachineMemOperand *MMO, unsigned &ResultReg) {
366 // Get opcode and regclass of the output for the given load instruction.
368 const TargetRegisterClass *RC = nullptr;
369 switch (VT.getSimpleVT().SimpleTy) {
370 default: return false;
374 RC = &X86::GR8RegClass;
378 RC = &X86::GR16RegClass;
382 RC = &X86::GR32RegClass;
385 // Must be in x86-64 mode.
387 RC = &X86::GR64RegClass;
390 if (X86ScalarSSEf32) {
391 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
392 RC = &X86::FR32RegClass;
395 RC = &X86::RFP32RegClass;
399 if (X86ScalarSSEf64) {
400 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
401 RC = &X86::FR64RegClass;
404 RC = &X86::RFP64RegClass;
408 // No f80 support yet.
412 ResultReg = createResultReg(RC);
413 MachineInstrBuilder MIB =
414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
415 addFullAddress(MIB, AM);
417 MIB->addMemOperand(*FuncInfo.MF, MMO);
421 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
422 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
423 /// and a displacement offset, or a GlobalAddress,
424 /// i.e. V. Return true if it is possible.
425 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
426 const X86AddressMode &AM,
427 MachineMemOperand *MMO, bool Aligned) {
428 // Get opcode and regclass of the output for the given store instruction.
430 switch (VT.getSimpleVT().SimpleTy) {
431 case MVT::f80: // No f80 support yet.
432 default: return false;
434 // Mask out all but lowest bit.
435 unsigned AndResult = createResultReg(&X86::GR8RegClass);
436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
437 TII.get(X86::AND8ri), AndResult)
438 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
441 // FALLTHROUGH, handling i1 as i8.
442 case MVT::i8: Opc = X86::MOV8mr; break;
443 case MVT::i16: Opc = X86::MOV16mr; break;
444 case MVT::i32: Opc = X86::MOV32mr; break;
445 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
447 Opc = X86ScalarSSEf32 ?
448 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
451 Opc = X86ScalarSSEf64 ?
452 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
456 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
458 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
462 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
464 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
471 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
473 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
477 MachineInstrBuilder MIB =
478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
479 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
481 MIB->addMemOperand(*FuncInfo.MF, MMO);
486 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
487 const X86AddressMode &AM,
488 MachineMemOperand *MMO, bool Aligned) {
489 // Handle 'null' like i32/i64 0.
490 if (isa<ConstantPointerNull>(Val))
491 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
493 // If this is a store of a simple constant, fold the constant into the store.
494 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
497 switch (VT.getSimpleVT().SimpleTy) {
499 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
500 case MVT::i8: Opc = X86::MOV8mi; break;
501 case MVT::i16: Opc = X86::MOV16mi; break;
502 case MVT::i32: Opc = X86::MOV32mi; break;
504 // Must be a 32-bit sign extended value.
505 if (isInt<32>(CI->getSExtValue()))
506 Opc = X86::MOV64mi32;
511 MachineInstrBuilder MIB =
512 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
513 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
514 : CI->getZExtValue());
516 MIB->addMemOperand(*FuncInfo.MF, MMO);
521 unsigned ValReg = getRegForValue(Val);
525 bool ValKill = hasTrivialKill(Val);
526 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
529 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
530 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
531 /// ISD::SIGN_EXTEND).
532 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
533 unsigned Src, EVT SrcVT,
534 unsigned &ResultReg) {
535 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
536 Src, /*TODO: Kill=*/false);
544 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
545 // Handle constant address.
546 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
547 // Can't handle alternate code models yet.
548 if (TM.getCodeModel() != CodeModel::Small)
551 // Can't handle TLS yet.
552 if (GV->isThreadLocal())
555 // RIP-relative addresses can't have additional register operands, so if
556 // we've already folded stuff into the addressing mode, just force the
557 // global value into its own register, which we can use as the basereg.
558 if (!Subtarget->isPICStyleRIPRel() ||
559 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
560 // Okay, we've committed to selecting this global. Set up the address.
563 // Allow the subtarget to classify the global.
564 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
566 // If this reference is relative to the pic base, set it now.
567 if (isGlobalRelativeToPICBase(GVFlags)) {
568 // FIXME: How do we know Base.Reg is free??
569 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
572 // Unless the ABI requires an extra load, return a direct reference to
574 if (!isGlobalStubReference(GVFlags)) {
575 if (Subtarget->isPICStyleRIPRel()) {
576 // Use rip-relative addressing if we can. Above we verified that the
577 // base and index registers are unused.
578 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
579 AM.Base.Reg = X86::RIP;
581 AM.GVOpFlags = GVFlags;
585 // Ok, we need to do a load from a stub. If we've already loaded from
586 // this stub, reuse the loaded pointer, otherwise emit the load now.
587 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
589 if (I != LocalValueMap.end() && I->second != 0) {
592 // Issue load from stub.
594 const TargetRegisterClass *RC = nullptr;
595 X86AddressMode StubAM;
596 StubAM.Base.Reg = AM.Base.Reg;
598 StubAM.GVOpFlags = GVFlags;
600 // Prepare for inserting code in the local-value area.
601 SavePoint SaveInsertPt = enterLocalValueArea();
603 if (TLI.getPointerTy() == MVT::i64) {
605 RC = &X86::GR64RegClass;
607 if (Subtarget->isPICStyleRIPRel())
608 StubAM.Base.Reg = X86::RIP;
611 RC = &X86::GR32RegClass;
614 LoadReg = createResultReg(RC);
615 MachineInstrBuilder LoadMI =
616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
617 addFullAddress(LoadMI, StubAM);
619 // Ok, back to normal mode.
620 leaveLocalValueArea(SaveInsertPt);
622 // Prevent loading GV stub multiple times in same MBB.
623 LocalValueMap[V] = LoadReg;
626 // Now construct the final address. Note that the Disp, Scale,
627 // and Index values may already be set here.
628 AM.Base.Reg = LoadReg;
634 // If all else fails, try to materialize the value in a register.
635 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
636 if (AM.Base.Reg == 0) {
637 AM.Base.Reg = getRegForValue(V);
638 return AM.Base.Reg != 0;
640 if (AM.IndexReg == 0) {
641 assert(AM.Scale == 1 && "Scale with no index!");
642 AM.IndexReg = getRegForValue(V);
643 return AM.IndexReg != 0;
650 /// X86SelectAddress - Attempt to fill in an address from the given value.
652 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
653 SmallVector<const Value *, 32> GEPs;
655 const User *U = nullptr;
656 unsigned Opcode = Instruction::UserOp1;
657 if (const Instruction *I = dyn_cast<Instruction>(V)) {
658 // Don't walk into other basic blocks; it's possible we haven't
659 // visited them yet, so the instructions may not yet be assigned
660 // virtual registers.
661 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
662 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
663 Opcode = I->getOpcode();
666 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
667 Opcode = C->getOpcode();
671 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
672 if (Ty->getAddressSpace() > 255)
673 // Fast instruction selection doesn't support the special
679 case Instruction::BitCast:
680 // Look past bitcasts.
681 return X86SelectAddress(U->getOperand(0), AM);
683 case Instruction::IntToPtr:
684 // Look past no-op inttoptrs.
685 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
686 return X86SelectAddress(U->getOperand(0), AM);
689 case Instruction::PtrToInt:
690 // Look past no-op ptrtoints.
691 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
692 return X86SelectAddress(U->getOperand(0), AM);
695 case Instruction::Alloca: {
696 // Do static allocas.
697 const AllocaInst *A = cast<AllocaInst>(V);
698 DenseMap<const AllocaInst*, int>::iterator SI =
699 FuncInfo.StaticAllocaMap.find(A);
700 if (SI != FuncInfo.StaticAllocaMap.end()) {
701 AM.BaseType = X86AddressMode::FrameIndexBase;
702 AM.Base.FrameIndex = SI->second;
708 case Instruction::Add: {
709 // Adds of constants are common and easy enough.
710 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
711 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
712 // They have to fit in the 32-bit signed displacement field though.
713 if (isInt<32>(Disp)) {
714 AM.Disp = (uint32_t)Disp;
715 return X86SelectAddress(U->getOperand(0), AM);
721 case Instruction::GetElementPtr: {
722 X86AddressMode SavedAM = AM;
724 // Pattern-match simple GEPs.
725 uint64_t Disp = (int32_t)AM.Disp;
726 unsigned IndexReg = AM.IndexReg;
727 unsigned Scale = AM.Scale;
728 gep_type_iterator GTI = gep_type_begin(U);
729 // Iterate through the indices, folding what we can. Constants can be
730 // folded, and one dynamic index can be handled, if the scale is supported.
731 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
732 i != e; ++i, ++GTI) {
733 const Value *Op = *i;
734 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
735 const StructLayout *SL = DL.getStructLayout(STy);
736 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
740 // A array/variable index is always of the form i*S where S is the
741 // constant scale size. See if we can push the scale into immediates.
742 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
744 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
745 // Constant-offset addressing.
746 Disp += CI->getSExtValue() * S;
749 if (canFoldAddIntoGEP(U, Op)) {
750 // A compatible add with a constant operand. Fold the constant.
752 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
753 Disp += CI->getSExtValue() * S;
754 // Iterate on the other operand.
755 Op = cast<AddOperator>(Op)->getOperand(0);
759 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
760 (S == 1 || S == 2 || S == 4 || S == 8)) {
761 // Scaled-index addressing.
763 IndexReg = getRegForGEPIndex(Op).first;
769 goto unsupported_gep;
773 // Check for displacement overflow.
774 if (!isInt<32>(Disp))
777 AM.IndexReg = IndexReg;
779 AM.Disp = (uint32_t)Disp;
782 if (const GetElementPtrInst *GEP =
783 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
784 // Ok, the GEP indices were covered by constant-offset and scaled-index
785 // addressing. Update the address state and move on to examining the base.
788 } else if (X86SelectAddress(U->getOperand(0), AM)) {
792 // If we couldn't merge the gep value into this addr mode, revert back to
793 // our address and just match the value instead of completely failing.
796 for (SmallVectorImpl<const Value *>::reverse_iterator
797 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
798 if (handleConstantAddresses(*I, AM))
803 // Ok, the GEP indices weren't all covered.
808 return handleConstantAddresses(V, AM);
811 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
813 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
814 const User *U = nullptr;
815 unsigned Opcode = Instruction::UserOp1;
816 const Instruction *I = dyn_cast<Instruction>(V);
817 // Record if the value is defined in the same basic block.
819 // This information is crucial to know whether or not folding an
821 // Indeed, FastISel generates or reuses a virtual register for all
822 // operands of all instructions it selects. Obviously, the definition and
823 // its uses must use the same virtual register otherwise the produced
824 // code is incorrect.
825 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
826 // registers for values that are alive across basic blocks. This ensures
827 // that the values are consistently set between across basic block, even
828 // if different instruction selection mechanisms are used (e.g., a mix of
829 // SDISel and FastISel).
830 // For values local to a basic block, the instruction selection process
831 // generates these virtual registers with whatever method is appropriate
832 // for its needs. In particular, FastISel and SDISel do not share the way
833 // local virtual registers are set.
834 // Therefore, this is impossible (or at least unsafe) to share values
835 // between basic blocks unless they use the same instruction selection
836 // method, which is not guarantee for X86.
837 // Moreover, things like hasOneUse could not be used accurately, if we
838 // allow to reference values across basic blocks whereas they are not
839 // alive across basic blocks initially.
842 Opcode = I->getOpcode();
844 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
845 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
846 Opcode = C->getOpcode();
852 case Instruction::BitCast:
853 // Look past bitcasts if its operand is in the same BB.
855 return X86SelectCallAddress(U->getOperand(0), AM);
858 case Instruction::IntToPtr:
859 // Look past no-op inttoptrs if its operand is in the same BB.
861 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
862 return X86SelectCallAddress(U->getOperand(0), AM);
865 case Instruction::PtrToInt:
866 // Look past no-op ptrtoints if its operand is in the same BB.
868 TLI.getValueType(U->getType()) == TLI.getPointerTy())
869 return X86SelectCallAddress(U->getOperand(0), AM);
873 // Handle constant address.
874 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
875 // Can't handle alternate code models yet.
876 if (TM.getCodeModel() != CodeModel::Small)
879 // RIP-relative addresses can't have additional register operands.
880 if (Subtarget->isPICStyleRIPRel() &&
881 (AM.Base.Reg != 0 || AM.IndexReg != 0))
884 // Can't handle DLL Import.
885 if (GV->hasDLLImportStorageClass())
889 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
890 if (GVar->isThreadLocal())
893 // Okay, we've committed to selecting this global. Set up the basic address.
896 // No ABI requires an extra load for anything other than DLLImport, which
897 // we rejected above. Return a direct reference to the global.
898 if (Subtarget->isPICStyleRIPRel()) {
899 // Use rip-relative addressing if we can. Above we verified that the
900 // base and index registers are unused.
901 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
902 AM.Base.Reg = X86::RIP;
903 } else if (Subtarget->isPICStyleStubPIC()) {
904 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
905 } else if (Subtarget->isPICStyleGOT()) {
906 AM.GVOpFlags = X86II::MO_GOTOFF;
912 // If all else fails, try to materialize the value in a register.
913 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
914 if (AM.Base.Reg == 0) {
915 AM.Base.Reg = getRegForValue(V);
916 return AM.Base.Reg != 0;
918 if (AM.IndexReg == 0) {
919 assert(AM.Scale == 1 && "Scale with no index!");
920 AM.IndexReg = getRegForValue(V);
921 return AM.IndexReg != 0;
929 /// X86SelectStore - Select and emit code to implement store instructions.
930 bool X86FastISel::X86SelectStore(const Instruction *I) {
931 // Atomic stores need special handling.
932 const StoreInst *S = cast<StoreInst>(I);
937 const Value *Val = S->getValueOperand();
938 const Value *Ptr = S->getPointerOperand();
941 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
944 unsigned Alignment = S->getAlignment();
945 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
946 if (Alignment == 0) // Ensure that codegen never sees alignment 0
947 Alignment = ABIAlignment;
948 bool Aligned = Alignment >= ABIAlignment;
951 if (!X86SelectAddress(Ptr, AM))
954 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
957 /// X86SelectRet - Select and emit code to implement ret instructions.
958 bool X86FastISel::X86SelectRet(const Instruction *I) {
959 const ReturnInst *Ret = cast<ReturnInst>(I);
960 const Function &F = *I->getParent()->getParent();
961 const X86MachineFunctionInfo *X86MFInfo =
962 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
964 if (!FuncInfo.CanLowerReturn)
967 CallingConv::ID CC = F.getCallingConv();
968 if (CC != CallingConv::C &&
969 CC != CallingConv::Fast &&
970 CC != CallingConv::X86_FastCall &&
971 CC != CallingConv::X86_64_SysV)
974 if (Subtarget->isCallingConvWin64(CC))
977 // Don't handle popping bytes on return for now.
978 if (X86MFInfo->getBytesToPopOnReturn() != 0)
981 // fastcc with -tailcallopt is intended to provide a guaranteed
982 // tail call optimization. Fastisel doesn't know how to do that.
983 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
986 // Let SDISel handle vararg functions.
990 // Build a list of return value registers.
991 SmallVector<unsigned, 4> RetRegs;
993 if (Ret->getNumOperands() > 0) {
994 SmallVector<ISD::OutputArg, 4> Outs;
995 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
997 // Analyze operands of the call, assigning locations to each operand.
998 SmallVector<CCValAssign, 16> ValLocs;
999 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1000 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1002 const Value *RV = Ret->getOperand(0);
1003 unsigned Reg = getRegForValue(RV);
1007 // Only handle a single return value for now.
1008 if (ValLocs.size() != 1)
1011 CCValAssign &VA = ValLocs[0];
1013 // Don't bother handling odd stuff for now.
1014 if (VA.getLocInfo() != CCValAssign::Full)
1016 // Only handle register returns for now.
1020 // The calling-convention tables for x87 returns don't tell
1022 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1025 unsigned SrcReg = Reg + VA.getValNo();
1026 EVT SrcVT = TLI.getValueType(RV->getType());
1027 EVT DstVT = VA.getValVT();
1028 // Special handling for extended integers.
1029 if (SrcVT != DstVT) {
1030 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1033 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1036 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1038 if (SrcVT == MVT::i1) {
1039 if (Outs[0].Flags.isSExt())
1041 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1044 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1046 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1047 SrcReg, /*TODO: Kill=*/false);
1051 unsigned DstReg = VA.getLocReg();
1052 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1053 // Avoid a cross-class copy. This is very unlikely.
1054 if (!SrcRC->contains(DstReg))
1056 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1057 DstReg).addReg(SrcReg);
1059 // Add register to return instruction.
1060 RetRegs.push_back(VA.getLocReg());
1063 // The x86-64 ABI for returning structs by value requires that we copy
1064 // the sret argument into %rax for the return. We saved the argument into
1065 // a virtual register in the entry block, so now we copy the value out
1066 // and into %rax. We also do the same with %eax for Win32.
1067 if (F.hasStructRetAttr() &&
1068 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1069 unsigned Reg = X86MFInfo->getSRetReturnReg();
1071 "SRetReturnReg should have been set in LowerFormalArguments()!");
1072 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1073 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1074 RetReg).addReg(Reg);
1075 RetRegs.push_back(RetReg);
1078 // Now emit the RET.
1079 MachineInstrBuilder MIB =
1080 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1081 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1082 MIB.addReg(RetRegs[i], RegState::Implicit);
1086 /// X86SelectLoad - Select and emit code to implement load instructions.
1088 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1089 const LoadInst *LI = cast<LoadInst>(I);
1091 // Atomic loads need special handling.
1096 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1099 const Value *Ptr = LI->getPointerOperand();
1102 if (!X86SelectAddress(Ptr, AM))
1105 unsigned ResultReg = 0;
1106 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1109 UpdateValueMap(I, ResultReg);
1113 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1114 bool HasAVX = Subtarget->hasAVX();
1115 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1116 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1118 switch (VT.getSimpleVT().SimpleTy) {
1120 case MVT::i8: return X86::CMP8rr;
1121 case MVT::i16: return X86::CMP16rr;
1122 case MVT::i32: return X86::CMP32rr;
1123 case MVT::i64: return X86::CMP64rr;
1125 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1127 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1131 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1132 /// of the comparison, return an opcode that works for the compare (e.g.
1133 /// CMP32ri) otherwise return 0.
1134 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1135 switch (VT.getSimpleVT().SimpleTy) {
1136 // Otherwise, we can't fold the immediate into this comparison.
1138 case MVT::i8: return X86::CMP8ri;
1139 case MVT::i16: return X86::CMP16ri;
1140 case MVT::i32: return X86::CMP32ri;
1142 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1144 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1145 return X86::CMP64ri32;
1150 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1152 unsigned Op0Reg = getRegForValue(Op0);
1153 if (Op0Reg == 0) return false;
1155 // Handle 'null' like i32/i64 0.
1156 if (isa<ConstantPointerNull>(Op1))
1157 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1159 // We have two options: compare with register or immediate. If the RHS of
1160 // the compare is an immediate that we can fold into this compare, use
1161 // CMPri, otherwise use CMPrr.
1162 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1163 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1164 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1166 .addImm(Op1C->getSExtValue());
1171 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1172 if (CompareOpc == 0) return false;
1174 unsigned Op1Reg = getRegForValue(Op1);
1175 if (Op1Reg == 0) return false;
1176 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1183 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1184 const CmpInst *CI = cast<CmpInst>(I);
1187 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1190 // Try to optimize or fold the cmp.
1191 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1192 unsigned ResultReg = 0;
1193 switch (Predicate) {
1195 case CmpInst::FCMP_FALSE: {
1196 ResultReg = createResultReg(&X86::GR32RegClass);
1197 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1199 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1205 case CmpInst::FCMP_TRUE: {
1206 ResultReg = createResultReg(&X86::GR8RegClass);
1207 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1208 ResultReg).addImm(1);
1214 UpdateValueMap(I, ResultReg);
1218 const Value *LHS = CI->getOperand(0);
1219 const Value *RHS = CI->getOperand(1);
1221 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1222 // We don't have to materialize a zero constant for this case and can just use
1223 // %x again on the RHS.
1224 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1225 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1226 if (RHSC && RHSC->isNullValue())
1230 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1231 static unsigned SETFOpcTable[2][3] = {
1232 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1233 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1235 unsigned *SETFOpc = nullptr;
1236 switch (Predicate) {
1238 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1239 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1242 ResultReg = createResultReg(&X86::GR8RegClass);
1244 if (!X86FastEmitCompare(LHS, RHS, VT))
1247 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1248 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1254 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1255 UpdateValueMap(I, ResultReg);
1261 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1262 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1263 unsigned Opc = X86::getSETFromCond(CC);
1266 std::swap(LHS, RHS);
1268 // Emit a compare of LHS/RHS.
1269 if (!X86FastEmitCompare(LHS, RHS, VT))
1272 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1273 UpdateValueMap(I, ResultReg);
1277 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1278 EVT DstVT = TLI.getValueType(I->getType());
1279 if (!TLI.isTypeLegal(DstVT))
1282 unsigned ResultReg = getRegForValue(I->getOperand(0));
1286 // Handle zero-extension from i1 to i8, which is common.
1287 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1288 if (SrcVT.SimpleTy == MVT::i1) {
1289 // Set the high bits to zero.
1290 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1297 if (DstVT == MVT::i64) {
1298 // Handle extension to 64-bits via sub-register shenanigans.
1301 switch (SrcVT.SimpleTy) {
1302 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1303 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1304 case MVT::i32: MovInst = X86::MOV32rr; break;
1305 default: llvm_unreachable("Unexpected zext to i64 source type");
1308 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1312 ResultReg = createResultReg(&X86::GR64RegClass);
1313 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1315 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1316 } else if (DstVT != MVT::i8) {
1317 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1318 ResultReg, /*Kill=*/true);
1323 UpdateValueMap(I, ResultReg);
1328 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1329 // Unconditional branches are selected by tablegen-generated code.
1330 // Handle a conditional branch.
1331 const BranchInst *BI = cast<BranchInst>(I);
1332 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1333 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1335 // Fold the common case of a conditional branch with a comparison
1336 // in the same block (values defined on other blocks may not have
1337 // initialized registers).
1339 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1340 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1341 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1343 // Try to optimize or fold the cmp.
1344 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1345 switch (Predicate) {
1347 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1348 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1351 const Value *CmpLHS = CI->getOperand(0);
1352 const Value *CmpRHS = CI->getOperand(1);
1354 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1356 // We don't have to materialize a zero constant for this case and can just
1357 // use %x again on the RHS.
1358 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1359 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1360 if (CmpRHSC && CmpRHSC->isNullValue())
1364 // Try to take advantage of fallthrough opportunities.
1365 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1366 std::swap(TrueMBB, FalseMBB);
1367 Predicate = CmpInst::getInversePredicate(Predicate);
1370 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1371 // code check. Instead two branch instructions are required to check all
1372 // the flags. First we change the predicate to a supported condition code,
1373 // which will be the first branch. Later one we will emit the second
1375 bool NeedExtraBranch = false;
1376 switch (Predicate) {
1378 case CmpInst::FCMP_OEQ:
1379 std::swap(TrueMBB, FalseMBB); // fall-through
1380 case CmpInst::FCMP_UNE:
1381 NeedExtraBranch = true;
1382 Predicate = CmpInst::FCMP_ONE;
1388 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1389 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1391 BranchOpc = X86::GetCondBranchFromCond(CC);
1393 std::swap(CmpLHS, CmpRHS);
1395 // Emit a compare of the LHS and RHS, setting the flags.
1396 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1399 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1402 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1404 if (NeedExtraBranch) {
1405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1409 // Obtain the branch weight and add the TrueBB to the successor list.
1410 uint32_t BranchWeight = 0;
1412 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1413 TrueMBB->getBasicBlock());
1414 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1416 // Emits an unconditional branch to the FalseBB, obtains the branch
1417 // weight, and adds it to the successor list.
1418 FastEmitBranch(FalseMBB, DbgLoc);
1422 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1423 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1424 // typically happen for _Bool and C++ bools.
1426 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1427 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1428 unsigned TestOpc = 0;
1429 switch (SourceVT.SimpleTy) {
1431 case MVT::i8: TestOpc = X86::TEST8ri; break;
1432 case MVT::i16: TestOpc = X86::TEST16ri; break;
1433 case MVT::i32: TestOpc = X86::TEST32ri; break;
1434 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1437 unsigned OpReg = getRegForValue(TI->getOperand(0));
1438 if (OpReg == 0) return false;
1439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1440 .addReg(OpReg).addImm(1);
1442 unsigned JmpOpc = X86::JNE_4;
1443 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1444 std::swap(TrueMBB, FalseMBB);
1448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1450 FastEmitBranch(FalseMBB, DbgLoc);
1451 uint32_t BranchWeight = 0;
1453 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1454 TrueMBB->getBasicBlock());
1455 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1459 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1460 // Fake request the condition, otherwise the intrinsic might be completely
1462 unsigned TmpReg = getRegForValue(BI->getCondition());
1466 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1470 FastEmitBranch(FalseMBB, DbgLoc);
1471 uint32_t BranchWeight = 0;
1473 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1474 TrueMBB->getBasicBlock());
1475 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1479 // Otherwise do a clumsy setcc and re-test it.
1480 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1481 // in an explicit cast, so make sure to handle that correctly.
1482 unsigned OpReg = getRegForValue(BI->getCondition());
1483 if (OpReg == 0) return false;
1485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1486 .addReg(OpReg).addImm(1);
1487 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1489 FastEmitBranch(FalseMBB, DbgLoc);
1490 uint32_t BranchWeight = 0;
1492 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1493 TrueMBB->getBasicBlock());
1494 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1498 bool X86FastISel::X86SelectShift(const Instruction *I) {
1499 unsigned CReg = 0, OpReg = 0;
1500 const TargetRegisterClass *RC = nullptr;
1501 if (I->getType()->isIntegerTy(8)) {
1503 RC = &X86::GR8RegClass;
1504 switch (I->getOpcode()) {
1505 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1506 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1507 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1508 default: return false;
1510 } else if (I->getType()->isIntegerTy(16)) {
1512 RC = &X86::GR16RegClass;
1513 switch (I->getOpcode()) {
1514 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1515 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1516 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1517 default: return false;
1519 } else if (I->getType()->isIntegerTy(32)) {
1521 RC = &X86::GR32RegClass;
1522 switch (I->getOpcode()) {
1523 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1524 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1525 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1526 default: return false;
1528 } else if (I->getType()->isIntegerTy(64)) {
1530 RC = &X86::GR64RegClass;
1531 switch (I->getOpcode()) {
1532 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1533 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1534 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1535 default: return false;
1542 if (!isTypeLegal(I->getType(), VT))
1545 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1546 if (Op0Reg == 0) return false;
1548 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1549 if (Op1Reg == 0) return false;
1550 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1551 CReg).addReg(Op1Reg);
1553 // The shift instruction uses X86::CL. If we defined a super-register
1554 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1555 if (CReg != X86::CL)
1556 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1557 TII.get(TargetOpcode::KILL), X86::CL)
1558 .addReg(CReg, RegState::Kill);
1560 unsigned ResultReg = createResultReg(RC);
1561 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1563 UpdateValueMap(I, ResultReg);
1567 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1568 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1569 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1570 const static bool S = true; // IsSigned
1571 const static bool U = false; // !IsSigned
1572 const static unsigned Copy = TargetOpcode::COPY;
1573 // For the X86 DIV/IDIV instruction, in most cases the dividend
1574 // (numerator) must be in a specific register pair highreg:lowreg,
1575 // producing the quotient in lowreg and the remainder in highreg.
1576 // For most data types, to set up the instruction, the dividend is
1577 // copied into lowreg, and lowreg is sign-extended or zero-extended
1578 // into highreg. The exception is i8, where the dividend is defined
1579 // as a single register rather than a register pair, and we
1580 // therefore directly sign-extend or zero-extend the dividend into
1581 // lowreg, instead of copying, and ignore the highreg.
1582 const static struct DivRemEntry {
1583 // The following portion depends only on the data type.
1584 const TargetRegisterClass *RC;
1585 unsigned LowInReg; // low part of the register pair
1586 unsigned HighInReg; // high part of the register pair
1587 // The following portion depends on both the data type and the operation.
1588 struct DivRemResult {
1589 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1590 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1591 // highreg, or copying a zero into highreg.
1592 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1593 // zero/sign-extending into lowreg for i8.
1594 unsigned DivRemResultReg; // Register containing the desired result.
1595 bool IsOpSigned; // Whether to use signed or unsigned form.
1596 } ResultTable[NumOps];
1597 } OpTable[NumTypes] = {
1598 { &X86::GR8RegClass, X86::AX, 0, {
1599 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1600 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1601 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1602 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1605 { &X86::GR16RegClass, X86::AX, X86::DX, {
1606 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1607 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1608 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1609 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1612 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1613 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1614 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1615 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1616 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1619 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1620 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1621 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1622 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1623 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1629 if (!isTypeLegal(I->getType(), VT))
1632 unsigned TypeIndex, OpIndex;
1633 switch (VT.SimpleTy) {
1634 default: return false;
1635 case MVT::i8: TypeIndex = 0; break;
1636 case MVT::i16: TypeIndex = 1; break;
1637 case MVT::i32: TypeIndex = 2; break;
1638 case MVT::i64: TypeIndex = 3;
1639 if (!Subtarget->is64Bit())
1644 switch (I->getOpcode()) {
1645 default: llvm_unreachable("Unexpected div/rem opcode");
1646 case Instruction::SDiv: OpIndex = 0; break;
1647 case Instruction::SRem: OpIndex = 1; break;
1648 case Instruction::UDiv: OpIndex = 2; break;
1649 case Instruction::URem: OpIndex = 3; break;
1652 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1653 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1654 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1657 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1661 // Move op0 into low-order input register.
1662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1663 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1664 // Zero-extend or sign-extend into high-order input register.
1665 if (OpEntry.OpSignExtend) {
1666 if (OpEntry.IsOpSigned)
1667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1668 TII.get(OpEntry.OpSignExtend));
1670 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1672 TII.get(X86::MOV32r0), Zero32);
1674 // Copy the zero into the appropriate sub/super/identical physical
1675 // register. Unfortunately the operations needed are not uniform enough to
1676 // fit neatly into the table above.
1677 if (VT.SimpleTy == MVT::i16) {
1678 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1679 TII.get(Copy), TypeEntry.HighInReg)
1680 .addReg(Zero32, 0, X86::sub_16bit);
1681 } else if (VT.SimpleTy == MVT::i32) {
1682 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1683 TII.get(Copy), TypeEntry.HighInReg)
1685 } else if (VT.SimpleTy == MVT::i64) {
1686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1687 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1688 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1692 // Generate the DIV/IDIV instruction.
1693 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1694 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1695 // For i8 remainder, we can't reference AH directly, as we'll end
1696 // up with bogus copies like %R9B = COPY %AH. Reference AX
1697 // instead to prevent AH references in a REX instruction.
1699 // The current assumption of the fast register allocator is that isel
1700 // won't generate explicit references to the GPR8_NOREX registers. If
1701 // the allocator and/or the backend get enhanced to be more robust in
1702 // that regard, this can be, and should be, removed.
1703 unsigned ResultReg = 0;
1704 if ((I->getOpcode() == Instruction::SRem ||
1705 I->getOpcode() == Instruction::URem) &&
1706 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1707 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1708 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1709 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1710 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1712 // Shift AX right by 8 bits instead of using AH.
1713 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1714 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1716 // Now reference the 8-bit subreg of the result.
1717 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1718 /*Kill=*/true, X86::sub_8bit);
1720 // Copy the result out of the physreg if we haven't already.
1722 ResultReg = createResultReg(TypeEntry.RC);
1723 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1724 .addReg(OpEntry.DivRemResultReg);
1726 UpdateValueMap(I, ResultReg);
1731 /// \brief Emit a conditional move instruction (if the are supported) to lower
1733 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1734 // Check if the subtarget supports these instructions.
1735 if (!Subtarget->hasCMov())
1738 // FIXME: Add support for i8.
1739 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1742 const Value *Cond = I->getOperand(0);
1743 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1744 bool NeedTest = true;
1745 X86::CondCode CC = X86::COND_NE;
1747 // Optimize conditions coming from a compare if both instructions are in the
1748 // same basic block (values defined in other basic blocks may not have
1749 // initialized registers).
1750 const auto *CI = dyn_cast<CmpInst>(Cond);
1751 if (CI && (CI->getParent() == I->getParent())) {
1752 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1754 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1755 static unsigned SETFOpcTable[2][3] = {
1756 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1757 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1759 unsigned *SETFOpc = nullptr;
1760 switch (Predicate) {
1762 case CmpInst::FCMP_OEQ:
1763 SETFOpc = &SETFOpcTable[0][0];
1764 Predicate = CmpInst::ICMP_NE;
1766 case CmpInst::FCMP_UNE:
1767 SETFOpc = &SETFOpcTable[1][0];
1768 Predicate = CmpInst::ICMP_NE;
1773 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1774 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1776 const Value *CmpLHS = CI->getOperand(0);
1777 const Value *CmpRHS = CI->getOperand(1);
1779 std::swap(CmpLHS, CmpRHS);
1781 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1782 // Emit a compare of the LHS and RHS, setting the flags.
1783 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1787 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1788 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1791 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1793 auto const &II = TII.get(SETFOpc[2]);
1794 if (II.getNumDefs()) {
1795 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1796 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1797 .addReg(FlagReg2).addReg(FlagReg1);
1799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1800 .addReg(FlagReg2).addReg(FlagReg1);
1804 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1805 // Fake request the condition, otherwise the intrinsic might be completely
1807 unsigned TmpReg = getRegForValue(Cond);
1815 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1816 // garbage. Indeed, only the less significant bit is supposed to be
1817 // accurate. If we read more than the lsb, we may see non-zero values
1818 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1819 // the select. This is achieved by performing TEST against 1.
1820 unsigned CondReg = getRegForValue(Cond);
1823 bool CondIsKill = hasTrivialKill(Cond);
1825 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1826 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1829 const Value *LHS = I->getOperand(1);
1830 const Value *RHS = I->getOperand(2);
1832 unsigned RHSReg = getRegForValue(RHS);
1833 bool RHSIsKill = hasTrivialKill(RHS);
1835 unsigned LHSReg = getRegForValue(LHS);
1836 bool LHSIsKill = hasTrivialKill(LHS);
1838 if (!LHSReg || !RHSReg)
1841 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1842 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1844 UpdateValueMap(I, ResultReg);
1848 /// \brief Emit SSE instructions to lower the select.
1850 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1851 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1852 /// SSE instructions are available.
1853 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1854 // Optimize conditions coming from a compare if both instructions are in the
1855 // same basic block (values defined in other basic blocks may not have
1856 // initialized registers).
1857 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1858 if (!CI || (CI->getParent() != I->getParent()))
1861 if (I->getType() != CI->getOperand(0)->getType() ||
1862 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1863 (Subtarget->hasSSE2() && RetVT == MVT::f64) ))
1866 const Value *CmpLHS = CI->getOperand(0);
1867 const Value *CmpRHS = CI->getOperand(1);
1868 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1870 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1871 // We don't have to materialize a zero constant for this case and can just use
1872 // %x again on the RHS.
1873 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1874 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1875 if (CmpRHSC && CmpRHSC->isNullValue())
1881 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1886 std::swap(CmpLHS, CmpRHS);
1888 static unsigned OpcTable[2][2][4] = {
1889 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1890 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1891 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1892 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1895 bool HasAVX = Subtarget->hasAVX();
1896 unsigned *Opc = nullptr;
1897 switch (RetVT.SimpleTy) {
1898 default: return false;
1899 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1900 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1903 const Value *LHS = I->getOperand(1);
1904 const Value *RHS = I->getOperand(2);
1906 unsigned LHSReg = getRegForValue(LHS);
1907 bool LHSIsKill = hasTrivialKill(LHS);
1909 unsigned RHSReg = getRegForValue(RHS);
1910 bool RHSIsKill = hasTrivialKill(RHS);
1912 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1913 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1915 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1916 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1918 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1921 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1922 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1923 CmpRHSReg, CmpRHSIsKill, CC);
1924 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1926 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1928 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1929 AndReg, /*IsKill=*/true);
1930 UpdateValueMap(I, ResultReg);
1934 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1935 // These are pseudo CMOV instructions and will be later expanded into control-
1938 switch (RetVT.SimpleTy) {
1939 default: return false;
1940 case MVT::i8: Opc = X86::CMOV_GR8; break;
1941 case MVT::i16: Opc = X86::CMOV_GR16; break;
1942 case MVT::i32: Opc = X86::CMOV_GR32; break;
1943 case MVT::f32: Opc = X86::CMOV_FR32; break;
1944 case MVT::f64: Opc = X86::CMOV_FR64; break;
1947 const Value *Cond = I->getOperand(0);
1948 X86::CondCode CC = X86::COND_NE;
1950 // Optimize conditions coming from a compare if both instructions are in the
1951 // same basic block (values defined in other basic blocks may not have
1952 // initialized registers).
1953 const auto *CI = dyn_cast<CmpInst>(Cond);
1954 if (CI && (CI->getParent() == I->getParent())) {
1956 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1957 if (CC > X86::LAST_VALID_COND)
1960 const Value *CmpLHS = CI->getOperand(0);
1961 const Value *CmpRHS = CI->getOperand(1);
1964 std::swap(CmpLHS, CmpRHS);
1966 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1967 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1970 unsigned CondReg = getRegForValue(Cond);
1973 bool CondIsKill = hasTrivialKill(Cond);
1974 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1975 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1978 const Value *LHS = I->getOperand(1);
1979 const Value *RHS = I->getOperand(2);
1981 unsigned LHSReg = getRegForValue(LHS);
1982 bool LHSIsKill = hasTrivialKill(LHS);
1984 unsigned RHSReg = getRegForValue(RHS);
1985 bool RHSIsKill = hasTrivialKill(RHS);
1987 if (!LHSReg || !RHSReg)
1990 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1992 unsigned ResultReg =
1993 FastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
1994 UpdateValueMap(I, ResultReg);
1998 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2000 if (!isTypeLegal(I->getType(), RetVT))
2003 // Check if we can fold the select.
2004 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2005 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2006 const Value *Opnd = nullptr;
2007 switch (Predicate) {
2009 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2010 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2012 // No need for a select anymore - this is an unconditional move.
2014 unsigned OpReg = getRegForValue(Opnd);
2017 bool OpIsKill = hasTrivialKill(Opnd);
2018 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2019 unsigned ResultReg = createResultReg(RC);
2020 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2021 TII.get(TargetOpcode::COPY), ResultReg)
2022 .addReg(OpReg, getKillRegState(OpIsKill));
2023 UpdateValueMap(I, ResultReg);
2028 // First try to use real conditional move instructions.
2029 if (X86FastEmitCMoveSelect(RetVT, I))
2032 // Try to use a sequence of SSE instructions to simulate a conditional move.
2033 if (X86FastEmitSSESelect(RetVT, I))
2036 // Fall-back to pseudo conditional move instructions, which will be later
2037 // converted to control-flow.
2038 if (X86FastEmitPseudoSelect(RetVT, I))
2044 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2045 // fpext from float to double.
2046 if (X86ScalarSSEf64 &&
2047 I->getType()->isDoubleTy()) {
2048 const Value *V = I->getOperand(0);
2049 if (V->getType()->isFloatTy()) {
2050 unsigned OpReg = getRegForValue(V);
2051 if (OpReg == 0) return false;
2052 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
2053 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2054 TII.get(X86::CVTSS2SDrr), ResultReg)
2056 UpdateValueMap(I, ResultReg);
2064 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2065 if (X86ScalarSSEf64) {
2066 if (I->getType()->isFloatTy()) {
2067 const Value *V = I->getOperand(0);
2068 if (V->getType()->isDoubleTy()) {
2069 unsigned OpReg = getRegForValue(V);
2070 if (OpReg == 0) return false;
2071 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
2072 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2073 TII.get(X86::CVTSD2SSrr), ResultReg)
2075 UpdateValueMap(I, ResultReg);
2084 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2085 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2086 EVT DstVT = TLI.getValueType(I->getType());
2088 // This code only handles truncation to byte.
2089 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2091 if (!TLI.isTypeLegal(SrcVT))
2094 unsigned InputReg = getRegForValue(I->getOperand(0));
2096 // Unhandled operand. Halt "fast" selection and bail.
2099 if (SrcVT == MVT::i8) {
2100 // Truncate from i8 to i1; no code needed.
2101 UpdateValueMap(I, InputReg);
2105 if (!Subtarget->is64Bit()) {
2106 // If we're on x86-32; we can't extract an i8 from a general register.
2107 // First issue a copy to GR16_ABCD or GR32_ABCD.
2108 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
2109 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
2110 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
2111 unsigned CopyReg = createResultReg(CopyRC);
2112 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
2113 CopyReg).addReg(InputReg);
2117 // Issue an extract_subreg.
2118 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
2119 InputReg, /*Kill=*/true,
2124 UpdateValueMap(I, ResultReg);
2128 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2129 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2132 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2133 X86AddressMode SrcAM, uint64_t Len) {
2135 // Make sure we don't bloat code by inlining very large memcpy's.
2136 if (!IsMemcpySmall(Len))
2139 bool i64Legal = Subtarget->is64Bit();
2141 // We don't care about alignment here since we just emit integer accesses.
2144 if (Len >= 8 && i64Legal)
2155 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2156 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2157 assert(RV && "Failed to emit load or store??");
2159 unsigned Size = VT.getSizeInBits()/8;
2161 DestAM.Disp += Size;
2168 bool X86FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) {
2169 // FIXME: Handle more intrinsics.
2170 switch (II->getIntrinsicID()) {
2171 default: return false;
2172 case Intrinsic::frameaddress: {
2173 Type *RetTy = II->getCalledFunction()->getReturnType();
2176 if (!isTypeLegal(RetTy, VT))
2180 const TargetRegisterClass *RC = nullptr;
2182 switch (VT.SimpleTy) {
2183 default: llvm_unreachable("Invalid result type for frameaddress.");
2184 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2185 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2188 // This needs to be set before we call getFrameRegister, otherwise we get
2189 // the wrong frame register.
2190 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2191 MFI->setFrameAddressIsTaken(true);
2193 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2194 TM.getSubtargetImpl()->getRegisterInfo());
2195 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
2196 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2197 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2198 "Invalid Frame Register!");
2200 // Always make a copy of the frame register to to a vreg first, so that we
2201 // never directly reference the frame register (the TwoAddressInstruction-
2202 // Pass doesn't like that).
2203 unsigned SrcReg = createResultReg(RC);
2204 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2205 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2207 // Now recursively load from the frame address.
2208 // movq (%rbp), %rax
2209 // movq (%rax), %rax
2210 // movq (%rax), %rax
2213 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2215 DestReg = createResultReg(RC);
2216 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2217 TII.get(Opc), DestReg), SrcReg);
2221 UpdateValueMap(II, SrcReg);
2224 case Intrinsic::memcpy: {
2225 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2226 // Don't handle volatile or variable length memcpys.
2227 if (MCI->isVolatile())
2230 if (isa<ConstantInt>(MCI->getLength())) {
2231 // Small memcpy's are common enough that we want to do them
2232 // without a call if possible.
2233 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2234 if (IsMemcpySmall(Len)) {
2235 X86AddressMode DestAM, SrcAM;
2236 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2237 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2239 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2244 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2245 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2248 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2251 return LowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2253 case Intrinsic::memset: {
2254 const MemSetInst *MSI = cast<MemSetInst>(II);
2256 if (MSI->isVolatile())
2259 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2260 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2263 if (MSI->getDestAddressSpace() > 255)
2266 return LowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2268 case Intrinsic::stackprotector: {
2269 // Emit code to store the stack guard onto the stack.
2270 EVT PtrTy = TLI.getPointerTy();
2272 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2273 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2275 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2277 // Grab the frame index.
2279 if (!X86SelectAddress(Slot, AM)) return false;
2280 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2283 case Intrinsic::dbg_declare: {
2284 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2286 assert(DI->getAddress() && "Null address should be checked earlier!");
2287 if (!X86SelectAddress(DI->getAddress(), AM))
2289 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2290 // FIXME may need to add RegState::Debug to any registers produced,
2291 // although ESP/EBP should be the only ones at the moment.
2292 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2293 addImm(0).addMetadata(DI->getVariable());
2296 case Intrinsic::trap: {
2297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2300 case Intrinsic::sqrt: {
2301 if (!Subtarget->hasSSE1())
2304 Type *RetTy = II->getCalledFunction()->getReturnType();
2307 if (!isTypeLegal(RetTy, VT))
2310 // Unfortunately we can't use FastEmit_r, because the AVX version of FSQRT
2311 // is not generated by FastISel yet.
2312 // FIXME: Update this code once tablegen can handle it.
2313 static const unsigned SqrtOpc[2][2] = {
2314 {X86::SQRTSSr, X86::VSQRTSSr},
2315 {X86::SQRTSDr, X86::VSQRTSDr}
2317 bool HasAVX = Subtarget->hasAVX();
2319 const TargetRegisterClass *RC;
2320 switch (VT.SimpleTy) {
2321 default: return false;
2322 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2323 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2326 const Value *SrcVal = II->getArgOperand(0);
2327 unsigned SrcReg = getRegForValue(SrcVal);
2332 unsigned ImplicitDefReg = 0;
2334 ImplicitDefReg = createResultReg(RC);
2335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2336 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2339 unsigned ResultReg = createResultReg(RC);
2340 MachineInstrBuilder MIB;
2341 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2345 MIB.addReg(ImplicitDefReg);
2349 UpdateValueMap(II, ResultReg);
2352 case Intrinsic::sadd_with_overflow:
2353 case Intrinsic::uadd_with_overflow:
2354 case Intrinsic::ssub_with_overflow:
2355 case Intrinsic::usub_with_overflow:
2356 case Intrinsic::smul_with_overflow:
2357 case Intrinsic::umul_with_overflow: {
2358 // This implements the basic lowering of the xalu with overflow intrinsics
2359 // into add/sub/mul followed by either seto or setb.
2360 const Function *Callee = II->getCalledFunction();
2361 auto *Ty = cast<StructType>(Callee->getReturnType());
2362 Type *RetTy = Ty->getTypeAtIndex(0U);
2363 Type *CondTy = Ty->getTypeAtIndex(1);
2366 if (!isTypeLegal(RetTy, VT))
2369 if (VT < MVT::i8 || VT > MVT::i64)
2372 const Value *LHS = II->getArgOperand(0);
2373 const Value *RHS = II->getArgOperand(1);
2375 // Canonicalize immediate to the RHS.
2376 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2377 isCommutativeIntrinsic(II))
2378 std::swap(LHS, RHS);
2380 bool UseIncDec = false;
2381 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2384 unsigned BaseOpc, CondOpc;
2385 switch (II->getIntrinsicID()) {
2386 default: llvm_unreachable("Unexpected intrinsic!");
2387 case Intrinsic::sadd_with_overflow:
2388 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2389 CondOpc = X86::SETOr;
2391 case Intrinsic::uadd_with_overflow:
2392 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2393 case Intrinsic::ssub_with_overflow:
2394 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2395 CondOpc = X86::SETOr;
2397 case Intrinsic::usub_with_overflow:
2398 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2399 case Intrinsic::smul_with_overflow:
2400 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2401 case Intrinsic::umul_with_overflow:
2402 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2405 unsigned LHSReg = getRegForValue(LHS);
2408 bool LHSIsKill = hasTrivialKill(LHS);
2410 unsigned ResultReg = 0;
2411 // Check if we have an immediate version.
2412 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2413 static const unsigned Opc[2][2][4] = {
2414 { { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2415 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r } },
2416 { { X86::INC8r, X86::INC64_16r, X86::INC64_32r, X86::INC64r },
2417 { X86::DEC8r, X86::DEC64_16r, X86::DEC64_32r, X86::DEC64r } }
2420 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2421 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2422 bool Is64Bit = Subtarget->is64Bit();
2423 bool IsDec = BaseOpc == X86ISD::DEC;
2424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2425 TII.get(Opc[Is64Bit][IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2426 .addReg(LHSReg, getKillRegState(LHSIsKill));
2428 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2429 CI->getZExtValue());
2435 RHSReg = getRegForValue(RHS);
2438 RHSIsKill = hasTrivialKill(RHS);
2439 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2443 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2445 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2446 static const unsigned MULOpc[] =
2447 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2448 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2449 // First copy the first operand into RAX, which is an implicit input to
2450 // the X86::MUL*r instruction.
2451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2452 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2453 .addReg(LHSReg, getKillRegState(LHSIsKill));
2454 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2455 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2456 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2457 static const unsigned MULOpc[] =
2458 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2459 if (VT == MVT::i8) {
2460 // Copy the first operand into AL, which is an implicit input to the
2461 // X86::IMUL8r instruction.
2462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2463 TII.get(TargetOpcode::COPY), X86::AL)
2464 .addReg(LHSReg, getKillRegState(LHSIsKill));
2465 ResultReg = FastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2468 ResultReg = FastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2469 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2476 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2477 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2481 UpdateValueMap(II, ResultReg, 2);
2484 case Intrinsic::x86_sse_cvttss2si:
2485 case Intrinsic::x86_sse_cvttss2si64:
2486 case Intrinsic::x86_sse2_cvttsd2si:
2487 case Intrinsic::x86_sse2_cvttsd2si64: {
2489 switch (II->getIntrinsicID()) {
2490 default: llvm_unreachable("Unexpected intrinsic.");
2491 case Intrinsic::x86_sse_cvttss2si:
2492 case Intrinsic::x86_sse_cvttss2si64:
2493 if (!Subtarget->hasSSE1())
2495 IsInputDouble = false;
2497 case Intrinsic::x86_sse2_cvttsd2si:
2498 case Intrinsic::x86_sse2_cvttsd2si64:
2499 if (!Subtarget->hasSSE2())
2501 IsInputDouble = true;
2505 Type *RetTy = II->getCalledFunction()->getReturnType();
2507 if (!isTypeLegal(RetTy, VT))
2510 static const unsigned CvtOpc[2][2][2] = {
2511 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2512 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2513 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2514 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2516 bool HasAVX = Subtarget->hasAVX();
2518 switch (VT.SimpleTy) {
2519 default: llvm_unreachable("Unexpected result type.");
2520 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2521 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2524 // Check if we can fold insertelement instructions into the convert.
2525 const Value *Op = II->getArgOperand(0);
2526 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2527 const Value *Index = IE->getOperand(2);
2528 if (!isa<ConstantInt>(Index))
2530 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2533 Op = IE->getOperand(1);
2536 Op = IE->getOperand(0);
2539 unsigned Reg = getRegForValue(Op);
2543 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2544 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2547 UpdateValueMap(II, ResultReg);
2553 bool X86FastISel::FastLowerArguments() {
2554 if (!FuncInfo.CanLowerReturn)
2557 const Function *F = FuncInfo.Fn;
2561 CallingConv::ID CC = F->getCallingConv();
2562 if (CC != CallingConv::C)
2565 if (Subtarget->isCallingConvWin64(CC))
2568 if (!Subtarget->is64Bit())
2571 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2572 unsigned GPRCnt = 0;
2573 unsigned FPRCnt = 0;
2575 for (auto const &Arg : F->args()) {
2576 // The first argument is at index 1.
2578 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2579 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2580 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2581 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2584 Type *ArgTy = Arg.getType();
2585 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2588 EVT ArgVT = TLI.getValueType(ArgTy);
2589 if (!ArgVT.isSimple()) return false;
2590 switch (ArgVT.getSimpleVT().SimpleTy) {
2591 default: return false;
2598 if (!Subtarget->hasSSE1())
2611 static const MCPhysReg GPR32ArgRegs[] = {
2612 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2614 static const MCPhysReg GPR64ArgRegs[] = {
2615 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2617 static const MCPhysReg XMMArgRegs[] = {
2618 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2619 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2622 unsigned GPRIdx = 0;
2623 unsigned FPRIdx = 0;
2624 for (auto const &Arg : F->args()) {
2625 MVT VT = TLI.getSimpleValueType(Arg.getType());
2626 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2628 switch (VT.SimpleTy) {
2629 default: llvm_unreachable("Unexpected value type.");
2630 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2631 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2632 case MVT::f32: // fall-through
2633 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2635 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2636 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2637 // Without this, EmitLiveInCopies may eliminate the livein if its only
2638 // use is a bitcast (which isn't turned into an instruction).
2639 unsigned ResultReg = createResultReg(RC);
2640 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2641 TII.get(TargetOpcode::COPY), ResultReg)
2642 .addReg(DstReg, getKillRegState(true));
2643 UpdateValueMap(&Arg, ResultReg);
2648 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2650 ImmutableCallSite *CS) {
2651 if (Subtarget->is64Bit())
2653 if (Subtarget->getTargetTriple().isOSMSVCRT())
2655 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2656 CC == CallingConv::HiPE)
2658 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2660 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2665 bool X86FastISel::FastLowerCall(CallLoweringInfo &CLI) {
2666 auto &OutVals = CLI.OutVals;
2667 auto &OutFlags = CLI.OutFlags;
2668 auto &OutRegs = CLI.OutRegs;
2669 auto &Ins = CLI.Ins;
2670 auto &InRegs = CLI.InRegs;
2671 CallingConv::ID CC = CLI.CallConv;
2672 bool &IsTailCall = CLI.IsTailCall;
2673 bool IsVarArg = CLI.IsVarArg;
2674 const Value *Callee = CLI.Callee;
2675 const char *SymName = CLI.SymName;
2677 bool Is64Bit = Subtarget->is64Bit();
2678 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2680 // Handle only C, fastcc, and webkit_js calling conventions for now.
2682 default: return false;
2683 case CallingConv::C:
2684 case CallingConv::Fast:
2685 case CallingConv::WebKit_JS:
2686 case CallingConv::X86_FastCall:
2687 case CallingConv::X86_64_Win64:
2688 case CallingConv::X86_64_SysV:
2692 // Allow SelectionDAG isel to handle tail calls.
2696 // fastcc with -tailcallopt is intended to provide a guaranteed
2697 // tail call optimization. Fastisel doesn't know how to do that.
2698 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2701 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2702 // x86-32. Special handling for x86-64 is implemented.
2703 if (IsVarArg && IsWin64)
2706 // Don't know about inalloca yet.
2707 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2710 // Fast-isel doesn't know about callee-pop yet.
2711 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2712 TM.Options.GuaranteedTailCallOpt))
2715 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2716 // instruction. This is safe because it is common to all FastISel supported
2717 // calling conventions on x86.
2718 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2719 Value *&Val = OutVals[i];
2720 ISD::ArgFlagsTy Flags = OutFlags[i];
2721 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2722 if (CI->getBitWidth() < 32) {
2724 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2726 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2730 // Passing bools around ends up doing a trunc to i1 and passing it.
2731 // Codegen this as an argument + "and 1".
2732 if (auto *TI = dyn_cast<TruncInst>(Val)) {
2733 if (TI->getType()->isIntegerTy(1) && CLI.CS &&
2734 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2736 Val = cast<TruncInst>(Val)->getOperand(0);
2737 unsigned ResultReg = getRegForValue(Val);
2743 if (!isTypeLegal(Val->getType(), ArgVT))
2747 FastEmit_ri(ArgVT, ArgVT, ISD::AND, ResultReg, Val->hasOneUse(), 1);
2751 UpdateValueMap(Val, ResultReg);
2756 // Analyze operands of the call, assigning locations to each operand.
2757 SmallVector<CCValAssign, 16> ArgLocs;
2758 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2760 // Allocate shadow area for Win64
2762 CCInfo.AllocateStack(32, 8);
2764 SmallVector<MVT, 16> OutVTs;
2765 for (auto *Val : OutVals) {
2767 if (!isTypeLegal(Val->getType(), VT))
2769 OutVTs.push_back(VT);
2771 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2773 // Get a count of how many bytes are to be pushed on the stack.
2774 unsigned NumBytes = CCInfo.getNextStackOffset();
2776 // Issue CALLSEQ_START
2777 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2778 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2781 // Walk the register/memloc assignments, inserting copies/loads.
2782 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2783 TM.getSubtargetImpl()->getRegisterInfo());
2784 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2785 CCValAssign const &VA = ArgLocs[i];
2786 const Value *ArgVal = OutVals[VA.getValNo()];
2787 MVT ArgVT = OutVTs[VA.getValNo()];
2789 if (ArgVT == MVT::x86mmx)
2792 unsigned ArgReg = getRegForValue(ArgVal);
2796 // Promote the value if needed.
2797 switch (VA.getLocInfo()) {
2798 case CCValAssign::Full: break;
2799 case CCValAssign::SExt: {
2800 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2801 "Unexpected extend");
2802 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2804 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2805 ArgVT = VA.getLocVT();
2808 case CCValAssign::ZExt: {
2809 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2810 "Unexpected extend");
2811 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2813 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2814 ArgVT = VA.getLocVT();
2817 case CCValAssign::AExt: {
2818 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2819 "Unexpected extend");
2820 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2823 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2826 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2829 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2830 ArgVT = VA.getLocVT();
2833 case CCValAssign::BCvt: {
2834 ArgReg = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2835 /*TODO: Kill=*/false);
2836 assert(ArgReg && "Failed to emit a bitcast!");
2837 ArgVT = VA.getLocVT();
2840 case CCValAssign::VExt:
2841 // VExt has not been implemented, so this should be impossible to reach
2842 // for now. However, fallback to Selection DAG isel once implemented.
2844 case CCValAssign::FPExt:
2845 llvm_unreachable("Unexpected loc info!");
2846 case CCValAssign::Indirect:
2847 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2852 if (VA.isRegLoc()) {
2853 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2854 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2855 OutRegs.push_back(VA.getLocReg());
2857 assert(VA.isMemLoc());
2859 // Don't emit stores for undef values.
2860 if (isa<UndefValue>(ArgVal))
2863 unsigned LocMemOffset = VA.getLocMemOffset();
2865 AM.Base.Reg = RegInfo->getStackRegister();
2866 AM.Disp = LocMemOffset;
2867 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
2868 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2869 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2870 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
2871 ArgVT.getStoreSize(), Alignment);
2872 if (Flags.isByVal()) {
2873 X86AddressMode SrcAM;
2874 SrcAM.Base.Reg = ArgReg;
2875 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
2877 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2878 // If this is a really simple value, emit this with the Value* version
2879 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2880 // as it can cause us to reevaluate the argument.
2881 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
2884 bool ValIsKill = hasTrivialKill(ArgVal);
2885 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
2891 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2893 if (Subtarget->isPICStyleGOT()) {
2894 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2895 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2896 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2899 if (Is64Bit && IsVarArg && !IsWin64) {
2900 // From AMD64 ABI document:
2901 // For calls that may call functions that use varargs or stdargs
2902 // (prototype-less calls or calls to functions containing ellipsis (...) in
2903 // the declaration) %al is used as hidden argument to specify the number
2904 // of SSE registers used. The contents of %al do not need to match exactly
2905 // the number of registers, but must be an ubound on the number of SSE
2906 // registers used and is in the range 0 - 8 inclusive.
2908 // Count the number of XMM registers allocated.
2909 static const MCPhysReg XMMArgRegs[] = {
2910 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2911 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2913 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2914 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2915 && "SSE registers cannot be used when SSE is disabled");
2916 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2917 X86::AL).addImm(NumXMMRegs);
2920 // Materialize callee address in a register. FIXME: GV address can be
2921 // handled with a CALLpcrel32 instead.
2922 X86AddressMode CalleeAM;
2923 if (!X86SelectCallAddress(Callee, CalleeAM))
2926 unsigned CalleeOp = 0;
2927 const GlobalValue *GV = nullptr;
2928 if (CalleeAM.GV != nullptr) {
2930 } else if (CalleeAM.Base.Reg != 0) {
2931 CalleeOp = CalleeAM.Base.Reg;
2936 MachineInstrBuilder MIB;
2938 // Register-indirect call.
2939 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
2940 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2944 assert(GV && "Not a direct call");
2945 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
2947 // See if we need any target-specific flags on the GV operand.
2948 unsigned char OpFlags = 0;
2950 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2951 // external symbols most go through the PLT in PIC mode. If the symbol
2952 // has hidden or protected visibility, or if it is static or local, then
2953 // we don't need to use the PLT - we can directly call it.
2954 if (Subtarget->isTargetELF() &&
2955 TM.getRelocationModel() == Reloc::PIC_ &&
2956 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2957 OpFlags = X86II::MO_PLT;
2958 } else if (Subtarget->isPICStyleStubAny() &&
2959 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2960 (!Subtarget->getTargetTriple().isMacOSX() ||
2961 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2962 // PC-relative references to external symbols should go through $stub,
2963 // unless we're building with the leopard linker or later, which
2964 // automatically synthesizes these stubs.
2965 OpFlags = X86II::MO_DARWIN_STUB;
2968 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2970 MIB.addExternalSymbol(SymName, OpFlags);
2972 MIB.addGlobalAddress(GV, 0, OpFlags);
2975 // Add a register mask operand representing the call-preserved registers.
2976 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2977 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2979 // Add an implicit use GOT pointer in EBX.
2980 if (Subtarget->isPICStyleGOT())
2981 MIB.addReg(X86::EBX, RegState::Implicit);
2983 if (Is64Bit && IsVarArg && !IsWin64)
2984 MIB.addReg(X86::AL, RegState::Implicit);
2986 // Add implicit physical register uses to the call.
2987 for (auto Reg : OutRegs)
2988 MIB.addReg(Reg, RegState::Implicit);
2990 // Issue CALLSEQ_END
2991 unsigned NumBytesForCalleeToPop =
2992 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
2993 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2994 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2995 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
2997 // Now handle call return values.
2998 SmallVector<CCValAssign, 16> RVLocs;
2999 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3000 CLI.RetTy->getContext());
3001 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3003 // Copy all of the result registers out of their specified physreg.
3004 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3005 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3006 CCValAssign &VA = RVLocs[i];
3007 EVT CopyVT = VA.getValVT();
3008 unsigned CopyReg = ResultReg + i;
3010 // If this is x86-64, and we disabled SSE, we can't return FP values
3011 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3012 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3013 report_fatal_error("SSE register return with SSE disabled");
3016 // If we prefer to use the value in xmm registers, copy it out as f80 and
3017 // use a truncate to move it from fp stack reg to xmm reg.
3018 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3019 isScalarFPTypeInSSEReg(VA.getValVT())) {
3021 CopyReg = createResultReg(&X86::RFP80RegClass);
3024 // Copy out the result.
3025 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3026 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3027 InRegs.push_back(VA.getLocReg());
3029 // Round the f80 to the right size, which also moves it to the appropriate
3030 // xmm register. This is accomplished by storing the f80 value in memory
3031 // and then loading it back.
3032 if (CopyVT != VA.getValVT()) {
3033 EVT ResVT = VA.getValVT();
3034 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3035 unsigned MemSize = ResVT.getSizeInBits()/8;
3036 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3037 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3040 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3041 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3042 TII.get(Opc), ResultReg + i), FI);
3046 CLI.ResultReg = ResultReg;
3047 CLI.NumResultRegs = RVLocs.size();
3054 X86FastISel::TargetSelectInstruction(const Instruction *I) {
3055 switch (I->getOpcode()) {
3057 case Instruction::Load:
3058 return X86SelectLoad(I);
3059 case Instruction::Store:
3060 return X86SelectStore(I);
3061 case Instruction::Ret:
3062 return X86SelectRet(I);
3063 case Instruction::ICmp:
3064 case Instruction::FCmp:
3065 return X86SelectCmp(I);
3066 case Instruction::ZExt:
3067 return X86SelectZExt(I);
3068 case Instruction::Br:
3069 return X86SelectBranch(I);
3070 case Instruction::LShr:
3071 case Instruction::AShr:
3072 case Instruction::Shl:
3073 return X86SelectShift(I);
3074 case Instruction::SDiv:
3075 case Instruction::UDiv:
3076 case Instruction::SRem:
3077 case Instruction::URem:
3078 return X86SelectDivRem(I);
3079 case Instruction::Select:
3080 return X86SelectSelect(I);
3081 case Instruction::Trunc:
3082 return X86SelectTrunc(I);
3083 case Instruction::FPExt:
3084 return X86SelectFPExt(I);
3085 case Instruction::FPTrunc:
3086 return X86SelectFPTrunc(I);
3087 case Instruction::IntToPtr: // Deliberate fall-through.
3088 case Instruction::PtrToInt: {
3089 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3090 EVT DstVT = TLI.getValueType(I->getType());
3091 if (DstVT.bitsGT(SrcVT))
3092 return X86SelectZExt(I);
3093 if (DstVT.bitsLT(SrcVT))
3094 return X86SelectTrunc(I);
3095 unsigned Reg = getRegForValue(I->getOperand(0));
3096 if (Reg == 0) return false;
3097 UpdateValueMap(I, Reg);
3105 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3109 uint64_t Imm = CI->getZExtValue();
3111 unsigned SrcReg = FastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3112 switch (VT.SimpleTy) {
3113 default: llvm_unreachable("Unexpected value type");
3116 return FastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3119 return FastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3124 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3125 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3126 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3127 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3134 switch (VT.SimpleTy) {
3135 default: llvm_unreachable("Unexpected value type");
3136 case MVT::i1: VT = MVT::i8; // fall-through
3137 case MVT::i8: Opc = X86::MOV8ri; break;
3138 case MVT::i16: Opc = X86::MOV16ri; break;
3139 case MVT::i32: Opc = X86::MOV32ri; break;
3141 if (isUInt<32>(Imm))
3143 else if (isInt<32>(Imm))
3144 Opc = X86::MOV64ri32;
3150 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3151 unsigned SrcReg = FastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3152 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3154 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3155 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3158 return FastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3161 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3162 if (CFP->isNullValue())
3163 return TargetMaterializeFloatZero(CFP);
3165 // Can't handle alternate code models yet.
3166 CodeModel::Model CM = TM.getCodeModel();
3167 if (CM != CodeModel::Small && CM != CodeModel::Large)
3170 // Get opcode and regclass of the output for the given load instruction.
3172 const TargetRegisterClass *RC = nullptr;
3173 switch (VT.SimpleTy) {
3176 if (X86ScalarSSEf32) {
3177 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3178 RC = &X86::FR32RegClass;
3180 Opc = X86::LD_Fp32m;
3181 RC = &X86::RFP32RegClass;
3185 if (X86ScalarSSEf64) {
3186 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3187 RC = &X86::FR64RegClass;
3189 Opc = X86::LD_Fp64m;
3190 RC = &X86::RFP64RegClass;
3194 // No f80 support yet.
3198 // MachineConstantPool wants an explicit alignment.
3199 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3201 // Alignment of vector types. FIXME!
3202 Align = DL.getTypeAllocSize(CFP->getType());
3205 // x86-32 PIC requires a PIC base register for constant pools.
3206 unsigned PICBase = 0;
3207 unsigned char OpFlag = 0;
3208 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3209 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3210 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3211 } else if (Subtarget->isPICStyleGOT()) {
3212 OpFlag = X86II::MO_GOTOFF;
3213 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3214 } else if (Subtarget->isPICStyleRIPRel() &&
3215 TM.getCodeModel() == CodeModel::Small) {
3219 // Create the load from the constant pool.
3220 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3221 unsigned ResultReg = createResultReg(RC);
3223 if (CM == CodeModel::Large) {
3224 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3227 .addConstantPoolIndex(CPI, 0, OpFlag);
3228 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3229 TII.get(Opc), ResultReg);
3230 addDirectMem(MIB, AddrReg);
3231 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3232 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3233 TM.getSubtargetImpl()->getDataLayout()->getPointerSize(), Align);
3234 MIB->addMemOperand(*FuncInfo.MF, MMO);
3238 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3239 TII.get(Opc), ResultReg),
3240 CPI, PICBase, OpFlag);
3244 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3245 // Can't handle alternate code models yet.
3246 if (TM.getCodeModel() != CodeModel::Small)
3249 // Materialize addresses with LEA/MOV instructions.
3251 if (X86SelectAddress(GV, AM)) {
3252 // If the expression is just a basereg, then we're done, otherwise we need
3254 if (AM.BaseType == X86AddressMode::RegBase &&
3255 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3258 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3259 if (TM.getRelocationModel() == Reloc::Static &&
3260 TLI.getPointerTy() == MVT::i64) {
3261 // The displacement code could be more than 32 bits away so we need to use
3262 // an instruction with a 64 bit immediate
3263 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3265 .addGlobalAddress(GV);
3267 unsigned Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
3268 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3269 TII.get(Opc), ResultReg), AM);
3276 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
3277 EVT CEVT = TLI.getValueType(C->getType(), true);
3279 // Only handle simple types.
3280 if (!CEVT.isSimple())
3282 MVT VT = CEVT.getSimpleVT();
3284 if (const auto *CI = dyn_cast<ConstantInt>(C))
3285 return X86MaterializeInt(CI, VT);
3286 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3287 return X86MaterializeFP(CFP, VT);
3288 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3289 return X86MaterializeGV(GV, VT);
3294 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
3295 // Fail on dynamic allocas. At this point, getRegForValue has already
3296 // checked its CSE maps, so if we're here trying to handle a dynamic
3297 // alloca, we're not going to succeed. X86SelectAddress has a
3298 // check for dynamic allocas, because it's called directly from
3299 // various places, but TargetMaterializeAlloca also needs a check
3300 // in order to avoid recursion between getRegForValue,
3301 // X86SelectAddrss, and TargetMaterializeAlloca.
3302 if (!FuncInfo.StaticAllocaMap.count(C))
3304 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3307 if (!X86SelectAddress(C, AM))
3309 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3310 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3311 unsigned ResultReg = createResultReg(RC);
3312 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3313 TII.get(Opc), ResultReg), AM);
3317 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3319 if (!isTypeLegal(CF->getType(), VT))
3322 // Get opcode and regclass for the given zero.
3324 const TargetRegisterClass *RC = nullptr;
3325 switch (VT.SimpleTy) {
3328 if (X86ScalarSSEf32) {
3329 Opc = X86::FsFLD0SS;
3330 RC = &X86::FR32RegClass;
3332 Opc = X86::LD_Fp032;
3333 RC = &X86::RFP32RegClass;
3337 if (X86ScalarSSEf64) {
3338 Opc = X86::FsFLD0SD;
3339 RC = &X86::FR64RegClass;
3341 Opc = X86::LD_Fp064;
3342 RC = &X86::RFP64RegClass;
3346 // No f80 support yet.
3350 unsigned ResultReg = createResultReg(RC);
3351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3356 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3357 const LoadInst *LI) {
3358 const Value *Ptr = LI->getPointerOperand();
3360 if (!X86SelectAddress(Ptr, AM))
3363 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3365 unsigned Size = DL.getTypeAllocSize(LI->getType());
3366 unsigned Alignment = LI->getAlignment();
3368 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3369 Alignment = DL.getABITypeAlignment(LI->getType());
3371 SmallVector<MachineOperand, 8> AddrOps;
3372 AM.getFullAddress(AddrOps);
3374 MachineInstr *Result =
3375 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3379 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3380 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3381 MI->eraseFromParent();
3387 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3388 const TargetLibraryInfo *libInfo) {
3389 return new X86FastISel(funcInfo, libInfo);