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;
78 #include "X86GenFastISel.inc"
81 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
83 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
86 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
87 MachineMemOperand *MMO = nullptr, bool Aligned = false);
88 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
89 const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
92 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
95 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
96 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
98 bool X86SelectLoad(const Instruction *I);
100 bool X86SelectStore(const Instruction *I);
102 bool X86SelectRet(const Instruction *I);
104 bool X86SelectCmp(const Instruction *I);
106 bool X86SelectZExt(const Instruction *I);
108 bool X86SelectBranch(const Instruction *I);
110 bool X86SelectShift(const Instruction *I);
112 bool X86SelectDivRem(const Instruction *I);
114 bool X86FastEmitCMoveSelect(const Instruction *I);
116 bool X86FastEmitSSESelect(const Instruction *I);
118 bool X86FastEmitPseudoSelect(const Instruction *I);
120 bool X86SelectSelect(const Instruction *I);
122 bool X86SelectTrunc(const Instruction *I);
124 bool X86SelectFPExt(const Instruction *I);
125 bool X86SelectFPTrunc(const Instruction *I);
127 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
128 bool X86SelectCall(const Instruction *I);
130 bool DoSelectCall(const Instruction *I, const char *MemIntName);
132 const X86InstrInfo *getInstrInfo() const {
133 return getTargetMachine()->getInstrInfo();
135 const X86TargetMachine *getTargetMachine() const {
136 return static_cast<const X86TargetMachine *>(&TM);
139 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
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 std::pair<bool, X86::CondCode>
162 foldX86XALUIntrinsic(const Instruction *I, const Value *Cond);
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 getX86ConditonCode(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 getX86SSECondtionCode(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
282 std::pair<bool, X86::CondCode>
283 X86FastISel::foldX86XALUIntrinsic(const Instruction *I, const Value *Cond) {
284 if (!isa<ExtractValueInst>(Cond))
285 return std::make_pair(false, X86::COND_INVALID);
287 const auto *EV = cast<ExtractValueInst>(Cond);
288 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
289 return std::make_pair(false, X86::COND_INVALID);
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))
297 return std::make_pair(false, X86::COND_INVALID);
299 if (RetVT != MVT::i32 && RetVT != MVT::i64)
300 return std::make_pair(false, X86::COND_INVALID);
303 switch (II->getIntrinsicID()) {
304 default: return std::make_pair(false, X86::COND_INVALID);
305 case Intrinsic::sadd_with_overflow:
306 case Intrinsic::ssub_with_overflow:
307 case Intrinsic::smul_with_overflow:
308 case Intrinsic::umul_with_overflow: CC = X86::COND_O; break;
309 case Intrinsic::uadd_with_overflow:
310 case Intrinsic::usub_with_overflow: CC = X86::COND_B; break;
313 // Check if both instructions are in the same basic block.
314 if (II->getParent() != I->getParent())
315 return std::make_pair(false, X86::COND_INVALID);
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))
324 return std::make_pair(false, X86::COND_INVALID);
326 // Check that the extractvalue operand comes from the intrinsic.
327 const auto *EVI = cast<ExtractValueInst>(Itr);
328 if (EVI->getAggregateOperand() != II)
329 return std::make_pair(false, X86::COND_INVALID);
332 return std::make_pair(true, CC);
335 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
336 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
337 if (evt == MVT::Other || !evt.isSimple())
338 // Unhandled type. Halt "fast" selection and bail.
341 VT = evt.getSimpleVT();
342 // For now, require SSE/SSE2 for performing floating-point operations,
343 // since x87 requires additional work.
344 if (VT == MVT::f64 && !X86ScalarSSEf64)
346 if (VT == MVT::f32 && !X86ScalarSSEf32)
348 // Similarly, no f80 support yet.
351 // We only handle legal types. For example, on x86-32 the instruction
352 // selector contains all of the 64-bit instructions from x86-64,
353 // under the assumption that i64 won't be used if the target doesn't
355 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
358 #include "X86GenCallingConv.inc"
360 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
361 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
362 /// Return true and the result register by reference if it is possible.
363 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
364 MachineMemOperand *MMO, unsigned &ResultReg) {
365 // Get opcode and regclass of the output for the given load instruction.
367 const TargetRegisterClass *RC = nullptr;
368 switch (VT.getSimpleVT().SimpleTy) {
369 default: return false;
373 RC = &X86::GR8RegClass;
377 RC = &X86::GR16RegClass;
381 RC = &X86::GR32RegClass;
384 // Must be in x86-64 mode.
386 RC = &X86::GR64RegClass;
389 if (X86ScalarSSEf32) {
390 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
391 RC = &X86::FR32RegClass;
394 RC = &X86::RFP32RegClass;
398 if (X86ScalarSSEf64) {
399 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
400 RC = &X86::FR64RegClass;
403 RC = &X86::RFP64RegClass;
407 // No f80 support yet.
411 ResultReg = createResultReg(RC);
412 MachineInstrBuilder MIB =
413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
414 addFullAddress(MIB, AM);
416 MIB->addMemOperand(*FuncInfo.MF, MMO);
420 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
421 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
422 /// and a displacement offset, or a GlobalAddress,
423 /// i.e. V. Return true if it is possible.
424 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
425 const X86AddressMode &AM,
426 MachineMemOperand *MMO, bool Aligned) {
427 // Get opcode and regclass of the output for the given store instruction.
429 switch (VT.getSimpleVT().SimpleTy) {
430 case MVT::f80: // No f80 support yet.
431 default: return false;
433 // Mask out all but lowest bit.
434 unsigned AndResult = createResultReg(&X86::GR8RegClass);
435 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
436 TII.get(X86::AND8ri), AndResult)
437 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
440 // FALLTHROUGH, handling i1 as i8.
441 case MVT::i8: Opc = X86::MOV8mr; break;
442 case MVT::i16: Opc = X86::MOV16mr; break;
443 case MVT::i32: Opc = X86::MOV32mr; break;
444 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
446 Opc = X86ScalarSSEf32 ?
447 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
450 Opc = X86ScalarSSEf64 ?
451 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
455 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
457 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
461 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
463 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
470 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
472 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
476 MachineInstrBuilder MIB =
477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
478 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
480 MIB->addMemOperand(*FuncInfo.MF, MMO);
485 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
486 const X86AddressMode &AM,
487 MachineMemOperand *MMO, bool Aligned) {
488 // Handle 'null' like i32/i64 0.
489 if (isa<ConstantPointerNull>(Val))
490 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
492 // If this is a store of a simple constant, fold the constant into the store.
493 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
496 switch (VT.getSimpleVT().SimpleTy) {
498 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
499 case MVT::i8: Opc = X86::MOV8mi; break;
500 case MVT::i16: Opc = X86::MOV16mi; break;
501 case MVT::i32: Opc = X86::MOV32mi; break;
503 // Must be a 32-bit sign extended value.
504 if (isInt<32>(CI->getSExtValue()))
505 Opc = X86::MOV64mi32;
510 MachineInstrBuilder MIB =
511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
512 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
513 : CI->getZExtValue());
515 MIB->addMemOperand(*FuncInfo.MF, MMO);
520 unsigned ValReg = getRegForValue(Val);
524 bool ValKill = hasTrivialKill(Val);
525 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
528 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
529 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
530 /// ISD::SIGN_EXTEND).
531 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
532 unsigned Src, EVT SrcVT,
533 unsigned &ResultReg) {
534 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
535 Src, /*TODO: Kill=*/false);
543 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
544 // Handle constant address.
545 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
546 // Can't handle alternate code models yet.
547 if (TM.getCodeModel() != CodeModel::Small)
550 // Can't handle TLS yet.
551 if (GV->isThreadLocal())
554 // RIP-relative addresses can't have additional register operands, so if
555 // we've already folded stuff into the addressing mode, just force the
556 // global value into its own register, which we can use as the basereg.
557 if (!Subtarget->isPICStyleRIPRel() ||
558 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
559 // Okay, we've committed to selecting this global. Set up the address.
562 // Allow the subtarget to classify the global.
563 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
565 // If this reference is relative to the pic base, set it now.
566 if (isGlobalRelativeToPICBase(GVFlags)) {
567 // FIXME: How do we know Base.Reg is free??
568 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
571 // Unless the ABI requires an extra load, return a direct reference to
573 if (!isGlobalStubReference(GVFlags)) {
574 if (Subtarget->isPICStyleRIPRel()) {
575 // Use rip-relative addressing if we can. Above we verified that the
576 // base and index registers are unused.
577 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
578 AM.Base.Reg = X86::RIP;
580 AM.GVOpFlags = GVFlags;
584 // Ok, we need to do a load from a stub. If we've already loaded from
585 // this stub, reuse the loaded pointer, otherwise emit the load now.
586 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
588 if (I != LocalValueMap.end() && I->second != 0) {
591 // Issue load from stub.
593 const TargetRegisterClass *RC = nullptr;
594 X86AddressMode StubAM;
595 StubAM.Base.Reg = AM.Base.Reg;
597 StubAM.GVOpFlags = GVFlags;
599 // Prepare for inserting code in the local-value area.
600 SavePoint SaveInsertPt = enterLocalValueArea();
602 if (TLI.getPointerTy() == MVT::i64) {
604 RC = &X86::GR64RegClass;
606 if (Subtarget->isPICStyleRIPRel())
607 StubAM.Base.Reg = X86::RIP;
610 RC = &X86::GR32RegClass;
613 LoadReg = createResultReg(RC);
614 MachineInstrBuilder LoadMI =
615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
616 addFullAddress(LoadMI, StubAM);
618 // Ok, back to normal mode.
619 leaveLocalValueArea(SaveInsertPt);
621 // Prevent loading GV stub multiple times in same MBB.
622 LocalValueMap[V] = LoadReg;
625 // Now construct the final address. Note that the Disp, Scale,
626 // and Index values may already be set here.
627 AM.Base.Reg = LoadReg;
633 // If all else fails, try to materialize the value in a register.
634 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
635 if (AM.Base.Reg == 0) {
636 AM.Base.Reg = getRegForValue(V);
637 return AM.Base.Reg != 0;
639 if (AM.IndexReg == 0) {
640 assert(AM.Scale == 1 && "Scale with no index!");
641 AM.IndexReg = getRegForValue(V);
642 return AM.IndexReg != 0;
649 /// X86SelectAddress - Attempt to fill in an address from the given value.
651 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
652 SmallVector<const Value *, 32> GEPs;
654 const User *U = nullptr;
655 unsigned Opcode = Instruction::UserOp1;
656 if (const Instruction *I = dyn_cast<Instruction>(V)) {
657 // Don't walk into other basic blocks; it's possible we haven't
658 // visited them yet, so the instructions may not yet be assigned
659 // virtual registers.
660 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
661 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
662 Opcode = I->getOpcode();
665 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
666 Opcode = C->getOpcode();
670 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
671 if (Ty->getAddressSpace() > 255)
672 // Fast instruction selection doesn't support the special
678 case Instruction::BitCast:
679 // Look past bitcasts.
680 return X86SelectAddress(U->getOperand(0), AM);
682 case Instruction::IntToPtr:
683 // Look past no-op inttoptrs.
684 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
685 return X86SelectAddress(U->getOperand(0), AM);
688 case Instruction::PtrToInt:
689 // Look past no-op ptrtoints.
690 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
691 return X86SelectAddress(U->getOperand(0), AM);
694 case Instruction::Alloca: {
695 // Do static allocas.
696 const AllocaInst *A = cast<AllocaInst>(V);
697 DenseMap<const AllocaInst*, int>::iterator SI =
698 FuncInfo.StaticAllocaMap.find(A);
699 if (SI != FuncInfo.StaticAllocaMap.end()) {
700 AM.BaseType = X86AddressMode::FrameIndexBase;
701 AM.Base.FrameIndex = SI->second;
707 case Instruction::Add: {
708 // Adds of constants are common and easy enough.
709 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
710 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
711 // They have to fit in the 32-bit signed displacement field though.
712 if (isInt<32>(Disp)) {
713 AM.Disp = (uint32_t)Disp;
714 return X86SelectAddress(U->getOperand(0), AM);
720 case Instruction::GetElementPtr: {
721 X86AddressMode SavedAM = AM;
723 // Pattern-match simple GEPs.
724 uint64_t Disp = (int32_t)AM.Disp;
725 unsigned IndexReg = AM.IndexReg;
726 unsigned Scale = AM.Scale;
727 gep_type_iterator GTI = gep_type_begin(U);
728 // Iterate through the indices, folding what we can. Constants can be
729 // folded, and one dynamic index can be handled, if the scale is supported.
730 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
731 i != e; ++i, ++GTI) {
732 const Value *Op = *i;
733 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
734 const StructLayout *SL = DL.getStructLayout(STy);
735 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
739 // A array/variable index is always of the form i*S where S is the
740 // constant scale size. See if we can push the scale into immediates.
741 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
743 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
744 // Constant-offset addressing.
745 Disp += CI->getSExtValue() * S;
748 if (canFoldAddIntoGEP(U, Op)) {
749 // A compatible add with a constant operand. Fold the constant.
751 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
752 Disp += CI->getSExtValue() * S;
753 // Iterate on the other operand.
754 Op = cast<AddOperator>(Op)->getOperand(0);
758 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
759 (S == 1 || S == 2 || S == 4 || S == 8)) {
760 // Scaled-index addressing.
762 IndexReg = getRegForGEPIndex(Op).first;
768 goto unsupported_gep;
772 // Check for displacement overflow.
773 if (!isInt<32>(Disp))
776 AM.IndexReg = IndexReg;
778 AM.Disp = (uint32_t)Disp;
781 if (const GetElementPtrInst *GEP =
782 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
783 // Ok, the GEP indices were covered by constant-offset and scaled-index
784 // addressing. Update the address state and move on to examining the base.
787 } else if (X86SelectAddress(U->getOperand(0), AM)) {
791 // If we couldn't merge the gep value into this addr mode, revert back to
792 // our address and just match the value instead of completely failing.
795 for (SmallVectorImpl<const Value *>::reverse_iterator
796 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
797 if (handleConstantAddresses(*I, AM))
802 // Ok, the GEP indices weren't all covered.
807 return handleConstantAddresses(V, AM);
810 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
812 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
813 const User *U = nullptr;
814 unsigned Opcode = Instruction::UserOp1;
815 const Instruction *I = dyn_cast<Instruction>(V);
816 // Record if the value is defined in the same basic block.
818 // This information is crucial to know whether or not folding an
820 // Indeed, FastISel generates or reuses a virtual register for all
821 // operands of all instructions it selects. Obviously, the definition and
822 // its uses must use the same virtual register otherwise the produced
823 // code is incorrect.
824 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
825 // registers for values that are alive across basic blocks. This ensures
826 // that the values are consistently set between across basic block, even
827 // if different instruction selection mechanisms are used (e.g., a mix of
828 // SDISel and FastISel).
829 // For values local to a basic block, the instruction selection process
830 // generates these virtual registers with whatever method is appropriate
831 // for its needs. In particular, FastISel and SDISel do not share the way
832 // local virtual registers are set.
833 // Therefore, this is impossible (or at least unsafe) to share values
834 // between basic blocks unless they use the same instruction selection
835 // method, which is not guarantee for X86.
836 // Moreover, things like hasOneUse could not be used accurately, if we
837 // allow to reference values across basic blocks whereas they are not
838 // alive across basic blocks initially.
841 Opcode = I->getOpcode();
843 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
844 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
845 Opcode = C->getOpcode();
851 case Instruction::BitCast:
852 // Look past bitcasts if its operand is in the same BB.
854 return X86SelectCallAddress(U->getOperand(0), AM);
857 case Instruction::IntToPtr:
858 // Look past no-op inttoptrs if its operand is in the same BB.
860 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
861 return X86SelectCallAddress(U->getOperand(0), AM);
864 case Instruction::PtrToInt:
865 // Look past no-op ptrtoints if its operand is in the same BB.
867 TLI.getValueType(U->getType()) == TLI.getPointerTy())
868 return X86SelectCallAddress(U->getOperand(0), AM);
872 // Handle constant address.
873 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
874 // Can't handle alternate code models yet.
875 if (TM.getCodeModel() != CodeModel::Small)
878 // RIP-relative addresses can't have additional register operands.
879 if (Subtarget->isPICStyleRIPRel() &&
880 (AM.Base.Reg != 0 || AM.IndexReg != 0))
883 // Can't handle DbgLocLImport.
884 if (GV->hasDLLImportStorageClass())
888 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
889 if (GVar->isThreadLocal())
892 // Okay, we've committed to selecting this global. Set up the basic address.
895 // No ABI requires an extra load for anything other than DLLImport, which
896 // we rejected above. Return a direct reference to the global.
897 if (Subtarget->isPICStyleRIPRel()) {
898 // Use rip-relative addressing if we can. Above we verified that the
899 // base and index registers are unused.
900 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
901 AM.Base.Reg = X86::RIP;
902 } else if (Subtarget->isPICStyleStubPIC()) {
903 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
904 } else if (Subtarget->isPICStyleGOT()) {
905 AM.GVOpFlags = X86II::MO_GOTOFF;
911 // If all else fails, try to materialize the value in a register.
912 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
913 if (AM.Base.Reg == 0) {
914 AM.Base.Reg = getRegForValue(V);
915 return AM.Base.Reg != 0;
917 if (AM.IndexReg == 0) {
918 assert(AM.Scale == 1 && "Scale with no index!");
919 AM.IndexReg = getRegForValue(V);
920 return AM.IndexReg != 0;
928 /// X86SelectStore - Select and emit code to implement store instructions.
929 bool X86FastISel::X86SelectStore(const Instruction *I) {
930 // Atomic stores need special handling.
931 const StoreInst *S = cast<StoreInst>(I);
936 const Value *Val = S->getValueOperand();
937 const Value *Ptr = S->getPointerOperand();
940 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
943 unsigned Alignment = S->getAlignment();
944 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
945 if (Alignment == 0) // Ensure that codegen never sees alignment 0
946 Alignment = ABIAlignment;
947 bool Aligned = Alignment >= ABIAlignment;
950 if (!X86SelectAddress(Ptr, AM))
953 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
956 /// X86SelectRet - Select and emit code to implement ret instructions.
957 bool X86FastISel::X86SelectRet(const Instruction *I) {
958 const ReturnInst *Ret = cast<ReturnInst>(I);
959 const Function &F = *I->getParent()->getParent();
960 const X86MachineFunctionInfo *X86MFInfo =
961 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
963 if (!FuncInfo.CanLowerReturn)
966 CallingConv::ID CC = F.getCallingConv();
967 if (CC != CallingConv::C &&
968 CC != CallingConv::Fast &&
969 CC != CallingConv::X86_FastCall &&
970 CC != CallingConv::X86_64_SysV)
973 if (Subtarget->isCallingConvWin64(CC))
976 // Don't handle popping bytes on return for now.
977 if (X86MFInfo->getBytesToPopOnReturn() != 0)
980 // fastcc with -tailcallopt is intended to provide a guaranteed
981 // tail call optimization. Fastisel doesn't know how to do that.
982 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
985 // Let SDISel handle vararg functions.
989 // Build a list of return value registers.
990 SmallVector<unsigned, 4> RetRegs;
992 if (Ret->getNumOperands() > 0) {
993 SmallVector<ISD::OutputArg, 4> Outs;
994 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
996 // Analyze operands of the call, assigning locations to each operand.
997 SmallVector<CCValAssign, 16> ValLocs;
998 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
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::ST0 || VA.getLocReg() == X86::ST1)
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) = getX86ConditonCode(Predicate);
1262 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon 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).
1338 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1339 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1340 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1342 // Try to optimize or fold the cmp.
1343 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1344 switch (Predicate) {
1346 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1347 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1350 const Value *CmpLHS = CI->getOperand(0);
1351 const Value *CmpRHS = CI->getOperand(1);
1353 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1355 // We don't have to materialize a zero constant for this case and can just
1356 // use %x again on the RHS.
1357 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1358 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1359 if (CmpRHSC && CmpRHSC->isNullValue())
1363 // Try to take advantage of fallthrough opportunities.
1364 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1365 std::swap(TrueMBB, FalseMBB);
1366 Predicate = CmpInst::getInversePredicate(Predicate);
1369 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1370 // code check. Instead two branch instructions are required to check all
1371 // the flags. First we change the predicate to a supported conditon code,
1372 // which will be the first branch. Later one we will emit the second
1374 bool NeedExtraBranch = false;
1375 switch (Predicate) {
1377 case CmpInst::FCMP_OEQ:
1378 std::swap(TrueMBB, FalseMBB); // fall-through
1379 case CmpInst::FCMP_UNE:
1380 NeedExtraBranch = true;
1381 Predicate = CmpInst::FCMP_ONE;
1388 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1389 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon 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);
1462 std::tie(FoldIntrinsic, CC) = foldX86XALUIntrinsic(BI, BI->getCondition());
1463 if (FoldIntrinsic) {
1464 // Fake request the condition, otherwise the intrinsic might be completely
1466 unsigned TmpReg = getRegForValue(BI->getCondition());
1470 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1474 FastEmitBranch(FalseMBB, DbgLoc);
1475 uint32_t BranchWeight = 0;
1477 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1478 TrueMBB->getBasicBlock());
1479 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1484 // Otherwise do a clumsy setcc and re-test it.
1485 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1486 // in an explicit cast, so make sure to handle that correctly.
1487 unsigned OpReg = getRegForValue(BI->getCondition());
1488 if (OpReg == 0) return false;
1490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1491 .addReg(OpReg).addImm(1);
1492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1494 FastEmitBranch(FalseMBB, DbgLoc);
1495 uint32_t BranchWeight = 0;
1497 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1498 TrueMBB->getBasicBlock());
1499 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1503 bool X86FastISel::X86SelectShift(const Instruction *I) {
1504 unsigned CReg = 0, OpReg = 0;
1505 const TargetRegisterClass *RC = nullptr;
1506 if (I->getType()->isIntegerTy(8)) {
1508 RC = &X86::GR8RegClass;
1509 switch (I->getOpcode()) {
1510 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1511 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1512 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1513 default: return false;
1515 } else if (I->getType()->isIntegerTy(16)) {
1517 RC = &X86::GR16RegClass;
1518 switch (I->getOpcode()) {
1519 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1520 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1521 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1522 default: return false;
1524 } else if (I->getType()->isIntegerTy(32)) {
1526 RC = &X86::GR32RegClass;
1527 switch (I->getOpcode()) {
1528 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1529 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1530 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1531 default: return false;
1533 } else if (I->getType()->isIntegerTy(64)) {
1535 RC = &X86::GR64RegClass;
1536 switch (I->getOpcode()) {
1537 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1538 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1539 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1540 default: return false;
1547 if (!isTypeLegal(I->getType(), VT))
1550 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1551 if (Op0Reg == 0) return false;
1553 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1554 if (Op1Reg == 0) return false;
1555 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1556 CReg).addReg(Op1Reg);
1558 // The shift instruction uses X86::CL. If we defined a super-register
1559 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1560 if (CReg != X86::CL)
1561 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1562 TII.get(TargetOpcode::KILL), X86::CL)
1563 .addReg(CReg, RegState::Kill);
1565 unsigned ResultReg = createResultReg(RC);
1566 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1568 UpdateValueMap(I, ResultReg);
1572 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1573 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1574 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1575 const static bool S = true; // IsSigned
1576 const static bool U = false; // !IsSigned
1577 const static unsigned Copy = TargetOpcode::COPY;
1578 // For the X86 DIV/IDIV instruction, in most cases the dividend
1579 // (numerator) must be in a specific register pair highreg:lowreg,
1580 // producing the quotient in lowreg and the remainder in highreg.
1581 // For most data types, to set up the instruction, the dividend is
1582 // copied into lowreg, and lowreg is sign-extended or zero-extended
1583 // into highreg. The exception is i8, where the dividend is defined
1584 // as a single register rather than a register pair, and we
1585 // therefore directly sign-extend or zero-extend the dividend into
1586 // lowreg, instead of copying, and ignore the highreg.
1587 const static struct DivRemEntry {
1588 // The following portion depends only on the data type.
1589 const TargetRegisterClass *RC;
1590 unsigned LowInReg; // low part of the register pair
1591 unsigned HighInReg; // high part of the register pair
1592 // The following portion depends on both the data type and the operation.
1593 struct DivRemResult {
1594 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1595 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1596 // highreg, or copying a zero into highreg.
1597 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1598 // zero/sign-extending into lowreg for i8.
1599 unsigned DivRemResultReg; // Register containing the desired result.
1600 bool IsOpSigned; // Whether to use signed or unsigned form.
1601 } ResultTable[NumOps];
1602 } OpTable[NumTypes] = {
1603 { &X86::GR8RegClass, X86::AX, 0, {
1604 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1605 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1606 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1607 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1610 { &X86::GR16RegClass, X86::AX, X86::DX, {
1611 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1612 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1613 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1614 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1617 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1618 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1619 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1620 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1621 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1624 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1625 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1626 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1627 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1628 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1634 if (!isTypeLegal(I->getType(), VT))
1637 unsigned TypeIndex, OpIndex;
1638 switch (VT.SimpleTy) {
1639 default: return false;
1640 case MVT::i8: TypeIndex = 0; break;
1641 case MVT::i16: TypeIndex = 1; break;
1642 case MVT::i32: TypeIndex = 2; break;
1643 case MVT::i64: TypeIndex = 3;
1644 if (!Subtarget->is64Bit())
1649 switch (I->getOpcode()) {
1650 default: llvm_unreachable("Unexpected div/rem opcode");
1651 case Instruction::SDiv: OpIndex = 0; break;
1652 case Instruction::SRem: OpIndex = 1; break;
1653 case Instruction::UDiv: OpIndex = 2; break;
1654 case Instruction::URem: OpIndex = 3; break;
1657 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1658 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1659 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1662 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1666 // Move op0 into low-order input register.
1667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1668 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1669 // Zero-extend or sign-extend into high-order input register.
1670 if (OpEntry.OpSignExtend) {
1671 if (OpEntry.IsOpSigned)
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1673 TII.get(OpEntry.OpSignExtend));
1675 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1677 TII.get(X86::MOV32r0), Zero32);
1679 // Copy the zero into the appropriate sub/super/identical physical
1680 // register. Unfortunately the operations needed are not uniform enough to
1681 // fit neatly into the table above.
1682 if (VT.SimpleTy == MVT::i16) {
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1684 TII.get(Copy), TypeEntry.HighInReg)
1685 .addReg(Zero32, 0, X86::sub_16bit);
1686 } else if (VT.SimpleTy == MVT::i32) {
1687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1688 TII.get(Copy), TypeEntry.HighInReg)
1690 } else if (VT.SimpleTy == MVT::i64) {
1691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1692 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1693 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1697 // Generate the DIV/IDIV instruction.
1698 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1699 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1700 // For i8 remainder, we can't reference AH directly, as we'll end
1701 // up with bogus copies like %R9B = COPY %AH. Reference AX
1702 // instead to prevent AH references in a REX instruction.
1704 // The current assumption of the fast register allocator is that isel
1705 // won't generate explicit references to the GPR8_NOREX registers. If
1706 // the allocator and/or the backend get enhanced to be more robust in
1707 // that regard, this can be, and should be, removed.
1708 unsigned ResultReg = 0;
1709 if ((I->getOpcode() == Instruction::SRem ||
1710 I->getOpcode() == Instruction::URem) &&
1711 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1712 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1713 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1715 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1717 // Shift AX right by 8 bits instead of using AH.
1718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1719 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1721 // Now reference the 8-bit subreg of the result.
1722 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1723 /*Kill=*/true, X86::sub_8bit);
1725 // Copy the result out of the physreg if we haven't already.
1727 ResultReg = createResultReg(TypeEntry.RC);
1728 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1729 .addReg(OpEntry.DivRemResultReg);
1731 UpdateValueMap(I, ResultReg);
1736 /// \brief Emit a conditional move instruction (if the are supported) to lower
1738 bool X86FastISel::X86FastEmitCMoveSelect(const Instruction *I) {
1740 if (!isTypeLegal(I->getType(), RetVT))
1743 // Check if the subtarget supports these instructions.
1744 if (!Subtarget->hasCMov())
1747 // FIXME: Add support for i8.
1749 switch (RetVT.SimpleTy) {
1750 default: return false;
1751 case MVT::i16: Opc = X86::CMOVNE16rr; break;
1752 case MVT::i32: Opc = X86::CMOVNE32rr; break;
1753 case MVT::i64: Opc = X86::CMOVNE64rr; break;
1756 const Value *Cond = I->getOperand(0);
1757 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1758 bool NeedTest = true;
1760 // Optimize conditons coming from a compare if both instructions are in the
1761 // same basic block (values defined in other basic blocks may not have
1762 // initialized registers).
1763 const auto *CI = dyn_cast<CmpInst>(Cond);
1764 if (CI && (CI->getParent() == I->getParent())) {
1765 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1767 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1768 static unsigned SETFOpcTable[2][3] = {
1769 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1770 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1772 unsigned *SETFOpc = nullptr;
1773 switch (Predicate) {
1775 case CmpInst::FCMP_OEQ:
1776 SETFOpc = &SETFOpcTable[0][0];
1777 Predicate = CmpInst::ICMP_NE;
1779 case CmpInst::FCMP_UNE:
1780 SETFOpc = &SETFOpcTable[1][0];
1781 Predicate = CmpInst::ICMP_NE;
1787 std::tie(CC, NeedSwap) = getX86ConditonCode(Predicate);
1788 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1789 Opc = X86::getCMovFromCond(CC, RC->getSize());
1791 const Value *CmpLHS = CI->getOperand(0);
1792 const Value *CmpRHS = CI->getOperand(1);
1794 std::swap(CmpLHS, CmpRHS);
1796 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1797 // Emit a compare of the LHS and RHS, setting the flags.
1798 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1802 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1803 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1804 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1806 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1808 auto const &II = TII.get(SETFOpc[2]);
1809 if (II.getNumDefs()) {
1810 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1811 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1812 .addReg(FlagReg2).addReg(FlagReg1);
1814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1815 .addReg(FlagReg2).addReg(FlagReg1);
1822 std::tie(FoldIntrinsic, CC) = foldX86XALUIntrinsic(I, Cond);
1824 if (FoldIntrinsic) {
1825 // Fake request the condition, otherwise the intrinsic might be completely
1827 unsigned TmpReg = getRegForValue(Cond);
1831 Opc = X86::getCMovFromCond(CC, RC->getSize());
1837 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1838 // garbage. Indeed, only the less significant bit is supposed to be
1839 // accurate. If we read more than the lsb, we may see non-zero values
1840 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1841 // the select. This is achieved by performing TEST against 1.
1842 unsigned CondReg = getRegForValue(Cond);
1845 bool CondIsKill = hasTrivialKill(Cond);
1847 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1848 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1851 const Value *LHS = I->getOperand(1);
1852 const Value *RHS = I->getOperand(2);
1854 unsigned RHSReg = getRegForValue(RHS);
1855 bool RHSIsKill = hasTrivialKill(RHS);
1857 unsigned LHSReg = getRegForValue(LHS);
1858 bool LHSIsKill = hasTrivialKill(LHS);
1860 if (!LHSReg || !RHSReg)
1863 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1865 UpdateValueMap(I, ResultReg);
1869 /// \brief Emit SSE instructions to lower the select.
1871 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1872 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1873 /// SSE instructions are available.
1874 bool X86FastISel::X86FastEmitSSESelect(const Instruction *I) {
1876 if (!isTypeLegal(I->getType(), RetVT))
1879 // Optimize conditons coming from a compare if both instructions are in the
1880 // same basic block (values defined in other basic blocks may not have
1881 // initialized registers).
1882 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1883 if (!CI || (CI->getParent() != I->getParent()))
1886 if (I->getType() != CI->getOperand(0)->getType() ||
1887 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1888 (Subtarget->hasSSE2() && RetVT == MVT::f64) ))
1891 const Value *CmpLHS = CI->getOperand(0);
1892 const Value *CmpRHS = CI->getOperand(1);
1893 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1895 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1896 // We don't have to materialize a zero constant for this case and can just use
1897 // %x again on the RHS.
1898 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1899 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1900 if (CmpRHSC && CmpRHSC->isNullValue())
1906 std::tie(CC, NeedSwap) = getX86SSECondtionCode(Predicate);
1911 std::swap(CmpLHS, CmpRHS);
1913 static unsigned OpcTable[2][2][4] = {
1914 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1915 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1916 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1917 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1920 bool HasAVX = Subtarget->hasAVX();
1921 unsigned *Opc = nullptr;
1922 switch (RetVT.SimpleTy) {
1923 default: return false;
1924 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1925 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1928 const Value *LHS = I->getOperand(1);
1929 const Value *RHS = I->getOperand(2);
1931 unsigned LHSReg = getRegForValue(LHS);
1932 bool LHSIsKill = hasTrivialKill(LHS);
1934 unsigned RHSReg = getRegForValue(RHS);
1935 bool RHSIsKill = hasTrivialKill(RHS);
1937 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1938 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1940 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1941 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1943 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1946 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1947 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1948 CmpRHSReg, CmpRHSIsKill, CC);
1949 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1951 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1953 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1954 AndReg, /*IsKill=*/true);
1955 UpdateValueMap(I, ResultReg);
1959 bool X86FastISel::X86FastEmitPseudoSelect(const Instruction *I) {
1961 if (!isTypeLegal(I->getType(), RetVT))
1964 // These are pseudo CMOV instructions and will be later expanded into control-
1967 switch (RetVT.SimpleTy) {
1968 default: return false;
1969 case MVT::i8: Opc = X86::CMOV_GR8; break;
1970 case MVT::i16: Opc = X86::CMOV_GR16; break;
1971 case MVT::i32: Opc = X86::CMOV_GR32; break;
1972 case MVT::f32: Opc = X86::CMOV_FR32; break;
1973 case MVT::f64: Opc = X86::CMOV_FR64; break;
1976 const Value *Cond = I->getOperand(0);
1977 X86::CondCode CC = X86::COND_NE;
1979 // Optimize conditons coming from a compare if both instructions are in the
1980 // same basic block (values defined in other basic blocks may not have
1981 // initialized registers).
1982 const auto *CI = dyn_cast<CmpInst>(Cond);
1983 if (CI && (CI->getParent() == I->getParent())) {
1985 std::tie(CC, NeedSwap) = getX86ConditonCode(CI->getPredicate());
1986 if (CC > X86::LAST_VALID_COND)
1989 const Value *CmpLHS = CI->getOperand(0);
1990 const Value *CmpRHS = CI->getOperand(1);
1993 std::swap(CmpLHS, CmpRHS);
1995 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1996 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1999 unsigned CondReg = getRegForValue(Cond);
2002 bool CondIsKill = hasTrivialKill(Cond);
2003 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2004 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2007 const Value *LHS = I->getOperand(1);
2008 const Value *RHS = I->getOperand(2);
2010 unsigned LHSReg = getRegForValue(LHS);
2011 bool LHSIsKill = hasTrivialKill(LHS);
2013 unsigned RHSReg = getRegForValue(RHS);
2014 bool RHSIsKill = hasTrivialKill(RHS);
2016 if (!LHSReg || !RHSReg)
2019 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2021 unsigned ResultReg =
2022 FastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2023 UpdateValueMap(I, ResultReg);
2027 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2029 if (!isTypeLegal(I->getType(), RetVT))
2032 // Check if we can fold the select.
2033 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2034 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2035 const Value *Opnd = nullptr;
2036 switch (Predicate) {
2038 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2039 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2041 // No need for a select anymore - this is an unconditional move.
2043 unsigned OpReg = getRegForValue(Opnd);
2046 bool OpIsKill = hasTrivialKill(Opnd);
2047 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2048 unsigned ResultReg = createResultReg(RC);
2049 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2050 TII.get(TargetOpcode::COPY), ResultReg)
2051 .addReg(OpReg, getKillRegState(OpIsKill));
2052 UpdateValueMap(I, ResultReg);
2057 // First try to use real conditional move instructions.
2058 if (X86FastEmitCMoveSelect(I))
2061 // Try to use a sequence of SSE instructions to simulate a conditonal move.
2062 if (X86FastEmitSSESelect(I))
2065 // Fall-back to pseudo conditional move instructions, which will be later
2066 // converted to control-flow.
2067 if (X86FastEmitPseudoSelect(I))
2073 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2074 // fpext from float to double.
2075 if (X86ScalarSSEf64 &&
2076 I->getType()->isDoubleTy()) {
2077 const Value *V = I->getOperand(0);
2078 if (V->getType()->isFloatTy()) {
2079 unsigned OpReg = getRegForValue(V);
2080 if (OpReg == 0) return false;
2081 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
2082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2083 TII.get(X86::CVTSS2SDrr), ResultReg)
2085 UpdateValueMap(I, ResultReg);
2093 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2094 if (X86ScalarSSEf64) {
2095 if (I->getType()->isFloatTy()) {
2096 const Value *V = I->getOperand(0);
2097 if (V->getType()->isDoubleTy()) {
2098 unsigned OpReg = getRegForValue(V);
2099 if (OpReg == 0) return false;
2100 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
2101 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2102 TII.get(X86::CVTSD2SSrr), ResultReg)
2104 UpdateValueMap(I, ResultReg);
2113 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2114 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2115 EVT DstVT = TLI.getValueType(I->getType());
2117 // This code only handles truncation to byte.
2118 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2120 if (!TLI.isTypeLegal(SrcVT))
2123 unsigned InputReg = getRegForValue(I->getOperand(0));
2125 // Unhandled operand. Halt "fast" selection and bail.
2128 if (SrcVT == MVT::i8) {
2129 // Truncate from i8 to i1; no code needed.
2130 UpdateValueMap(I, InputReg);
2134 if (!Subtarget->is64Bit()) {
2135 // If we're on x86-32; we can't extract an i8 from a general register.
2136 // First issue a copy to GR16_ABCD or GR32_ABCD.
2137 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
2138 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
2139 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
2140 unsigned CopyReg = createResultReg(CopyRC);
2141 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
2142 CopyReg).addReg(InputReg);
2146 // Issue an extract_subreg.
2147 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
2148 InputReg, /*Kill=*/true,
2153 UpdateValueMap(I, ResultReg);
2157 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2158 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2161 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2162 X86AddressMode SrcAM, uint64_t Len) {
2164 // Make sure we don't bloat code by inlining very large memcpy's.
2165 if (!IsMemcpySmall(Len))
2168 bool i64Legal = Subtarget->is64Bit();
2170 // We don't care about alignment here since we just emit integer accesses.
2173 if (Len >= 8 && i64Legal)
2184 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2185 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2186 assert(RV && "Failed to emit load or store??");
2188 unsigned Size = VT.getSizeInBits()/8;
2190 DestAM.Disp += Size;
2197 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
2198 switch (I.getIntrinsicID()) {
2199 case Intrinsic::sadd_with_overflow:
2200 case Intrinsic::uadd_with_overflow:
2201 case Intrinsic::smul_with_overflow:
2202 case Intrinsic::umul_with_overflow:
2209 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
2210 // FIXME: Handle more intrinsics.
2211 switch (I.getIntrinsicID()) {
2212 default: return false;
2213 case Intrinsic::frameaddress: {
2214 Type *RetTy = I.getCalledFunction()->getReturnType();
2217 if (!isTypeLegal(RetTy, VT))
2221 const TargetRegisterClass *RC = nullptr;
2223 switch (VT.SimpleTy) {
2224 default: llvm_unreachable("Invalid result type for frameaddress.");
2225 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2226 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2229 // This needs to be set before we call getFrameRegister, otherwise we get
2230 // the wrong frame register.
2231 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2232 MFI->setFrameAddressIsTaken(true);
2234 const X86RegisterInfo *RegInfo =
2235 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2236 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
2237 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2238 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2239 "Invalid Frame Register!");
2241 // Always make a copy of the frame register to to a vreg first, so that we
2242 // never directly reference the frame register (the TwoAddressInstruction-
2243 // Pass doesn't like that).
2244 unsigned SrcReg = createResultReg(RC);
2245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2246 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2248 // Now recursively load from the frame address.
2249 // movq (%rbp), %rax
2250 // movq (%rax), %rax
2251 // movq (%rax), %rax
2254 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2256 DestReg = createResultReg(RC);
2257 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2258 TII.get(Opc), DestReg), SrcReg);
2262 UpdateValueMap(&I, SrcReg);
2265 case Intrinsic::memcpy: {
2266 const MemCpyInst &MCI = cast<MemCpyInst>(I);
2267 // Don't handle volatile or variable length memcpys.
2268 if (MCI.isVolatile())
2271 if (isa<ConstantInt>(MCI.getLength())) {
2272 // Small memcpy's are common enough that we want to do them
2273 // without a call if possible.
2274 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
2275 if (IsMemcpySmall(Len)) {
2276 X86AddressMode DestAM, SrcAM;
2277 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
2278 !X86SelectAddress(MCI.getRawSource(), SrcAM))
2280 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2285 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2286 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
2289 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
2292 return DoSelectCall(&I, "memcpy");
2294 case Intrinsic::memset: {
2295 const MemSetInst &MSI = cast<MemSetInst>(I);
2297 if (MSI.isVolatile())
2300 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2301 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
2304 if (MSI.getDestAddressSpace() > 255)
2307 return DoSelectCall(&I, "memset");
2309 case Intrinsic::stackprotector: {
2310 // Emit code to store the stack guard onto the stack.
2311 EVT PtrTy = TLI.getPointerTy();
2313 const Value *Op1 = I.getArgOperand(0); // The guard's value.
2314 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
2316 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2318 // Grab the frame index.
2320 if (!X86SelectAddress(Slot, AM)) return false;
2321 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2324 case Intrinsic::dbg_declare: {
2325 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
2327 assert(DI->getAddress() && "Null address should be checked earlier!");
2328 if (!X86SelectAddress(DI->getAddress(), AM))
2330 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2331 // FIXME may need to add RegState::Debug to any registers produced,
2332 // although ESP/EBP should be the only ones at the moment.
2333 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2334 addImm(0).addMetadata(DI->getVariable());
2337 case Intrinsic::trap: {
2338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2341 case Intrinsic::sqrt: {
2342 if (!Subtarget->hasSSE1())
2345 Type *RetTy = I.getCalledFunction()->getReturnType();
2348 if (!isTypeLegal(RetTy, VT))
2351 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
2352 // is not generated by FastISel yet.
2353 // FIXME: Update this code once tablegen can handle it.
2354 static const unsigned SqrtOpc[2][2] = {
2355 {X86::SQRTSSr, X86::VSQRTSSr},
2356 {X86::SQRTSDr, X86::VSQRTSDr}
2358 bool HasAVX = Subtarget->hasAVX();
2360 const TargetRegisterClass *RC;
2361 switch (VT.SimpleTy) {
2362 default: return false;
2363 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2364 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2367 const Value *SrcVal = I.getArgOperand(0);
2368 unsigned SrcReg = getRegForValue(SrcVal);
2373 unsigned ImplicitDefReg = 0;
2375 ImplicitDefReg = createResultReg(RC);
2376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2377 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2380 unsigned ResultReg = createResultReg(RC);
2381 MachineInstrBuilder MIB;
2382 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2386 MIB.addReg(ImplicitDefReg);
2390 UpdateValueMap(&I, ResultReg);
2393 case Intrinsic::sadd_with_overflow:
2394 case Intrinsic::uadd_with_overflow:
2395 case Intrinsic::ssub_with_overflow:
2396 case Intrinsic::usub_with_overflow:
2397 case Intrinsic::smul_with_overflow:
2398 case Intrinsic::umul_with_overflow: {
2399 // This implements the basic lowering of the xalu with overflow intrinsics
2400 // into add/sub/mul folowed by either seto or setb.
2401 const Function *Callee = I.getCalledFunction();
2402 auto *Ty = cast<StructType>(Callee->getReturnType());
2403 Type *RetTy = Ty->getTypeAtIndex(0U);
2404 Type *CondTy = Ty->getTypeAtIndex(1);
2407 if (!isTypeLegal(RetTy, VT))
2410 if (VT < MVT::i8 || VT > MVT::i64)
2413 const Value *LHS = I.getArgOperand(0);
2414 const Value *RHS = I.getArgOperand(1);
2416 // Canonicalize immediates to the RHS.
2417 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2418 isCommutativeIntrinsic(I))
2419 std::swap(LHS, RHS);
2421 unsigned BaseOpc, CondOpc;
2422 switch (I.getIntrinsicID()) {
2423 default: llvm_unreachable("Unexpected intrinsic!");
2424 case Intrinsic::sadd_with_overflow:
2425 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2426 case Intrinsic::uadd_with_overflow:
2427 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2428 case Intrinsic::ssub_with_overflow:
2429 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2430 case Intrinsic::usub_with_overflow:
2431 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2432 case Intrinsic::smul_with_overflow:
2433 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
2434 case Intrinsic::umul_with_overflow:
2435 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2438 unsigned LHSReg = getRegForValue(LHS);
2441 bool LHSIsKill = hasTrivialKill(LHS);
2443 unsigned ResultReg = 0;
2444 // Check if we have an immediate version.
2445 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2446 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2453 RHSReg = getRegForValue(RHS);
2456 RHSIsKill = hasTrivialKill(RHS);
2457 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2461 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
2462 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2463 static const unsigned MULOpc[] =
2464 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2465 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2466 // First copy the first operand into RAX, which is an implicit input to
2467 // the X86::MUL*r instruction.
2468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2469 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2470 .addReg(LHSReg, getKillRegState(LHSIsKill));
2471 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2472 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2478 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2479 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2483 UpdateValueMap(&I, ResultReg, 2);
2486 case Intrinsic::x86_sse_cvttss2si:
2487 case Intrinsic::x86_sse_cvttss2si64:
2488 case Intrinsic::x86_sse2_cvttsd2si:
2489 case Intrinsic::x86_sse2_cvttsd2si64: {
2491 switch (I.getIntrinsicID()) {
2492 default: llvm_unreachable("Unexpected intrinsic.");
2493 case Intrinsic::x86_sse_cvttss2si:
2494 case Intrinsic::x86_sse_cvttss2si64:
2495 if (!Subtarget->hasSSE1())
2497 IsInputDouble = false;
2499 case Intrinsic::x86_sse2_cvttsd2si:
2500 case Intrinsic::x86_sse2_cvttsd2si64:
2501 if (!Subtarget->hasSSE2())
2503 IsInputDouble = true;
2507 Type *RetTy = I.getCalledFunction()->getReturnType();
2509 if (!isTypeLegal(RetTy, VT))
2512 static const unsigned CvtOpc[2][2][2] = {
2513 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2514 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2515 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2516 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2518 bool HasAVX = Subtarget->hasAVX();
2520 switch (VT.SimpleTy) {
2521 default: llvm_unreachable("Unexpected result type.");
2522 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2523 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2526 // Check if we can fold insertelement instructions into the convert.
2527 const Value *Op = I.getArgOperand(0);
2528 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2529 const Value *Index = IE->getOperand(2);
2530 if (!isa<ConstantInt>(Index))
2532 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2535 Op = IE->getOperand(1);
2538 Op = IE->getOperand(0);
2541 unsigned Reg = getRegForValue(Op);
2545 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2546 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2549 UpdateValueMap(&I, ResultReg);
2555 bool X86FastISel::FastLowerArguments() {
2556 if (!FuncInfo.CanLowerReturn)
2559 const Function *F = FuncInfo.Fn;
2563 CallingConv::ID CC = F->getCallingConv();
2564 if (CC != CallingConv::C)
2567 if (Subtarget->isCallingConvWin64(CC))
2570 if (!Subtarget->is64Bit())
2573 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2574 unsigned GPRCnt = 0;
2575 unsigned FPRCnt = 0;
2577 for (auto const &Arg : F->args()) {
2578 // The first argument is at index 1.
2580 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2581 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2582 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2583 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2586 Type *ArgTy = Arg.getType();
2587 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2590 EVT ArgVT = TLI.getValueType(ArgTy);
2591 if (!ArgVT.isSimple()) return false;
2592 switch (ArgVT.getSimpleVT().SimpleTy) {
2593 default: return false;
2600 if (!Subtarget->hasSSE1())
2613 static const MCPhysReg GPR32ArgRegs[] = {
2614 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2616 static const MCPhysReg GPR64ArgRegs[] = {
2617 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2619 static const MCPhysReg XMMArgRegs[] = {
2620 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2621 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2624 unsigned GPRIdx = 0;
2625 unsigned FPRIdx = 0;
2626 for (auto const &Arg : F->args()) {
2627 MVT VT = TLI.getSimpleValueType(Arg.getType());
2628 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2630 switch (VT.SimpleTy) {
2631 default: llvm_unreachable("Unexpected value type.");
2632 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2633 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2634 case MVT::f32: // fall-through
2635 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2637 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2638 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2639 // Without this, EmitLiveInCopies may eliminate the livein if its only
2640 // use is a bitcast (which isn't turned into an instruction).
2641 unsigned ResultReg = createResultReg(RC);
2642 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2643 TII.get(TargetOpcode::COPY), ResultReg)
2644 .addReg(DstReg, getKillRegState(true));
2645 UpdateValueMap(&Arg, ResultReg);
2650 bool X86FastISel::X86SelectCall(const Instruction *I) {
2651 const CallInst *CI = cast<CallInst>(I);
2652 const Value *Callee = CI->getCalledValue();
2654 // Can't handle inline asm yet.
2655 if (isa<InlineAsm>(Callee))
2658 // Handle intrinsic calls.
2659 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2660 return X86VisitIntrinsicCall(*II);
2662 // Allow SelectionDAG isel to handle tail calls.
2663 if (cast<CallInst>(I)->isTailCall())
2666 return DoSelectCall(I, nullptr);
2669 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2670 const ImmutableCallSite &CS) {
2671 if (Subtarget.is64Bit())
2673 if (Subtarget.getTargetTriple().isOSMSVCRT())
2675 CallingConv::ID CC = CS.getCallingConv();
2676 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2678 if (!CS.paramHasAttr(1, Attribute::StructRet))
2680 if (CS.paramHasAttr(1, Attribute::InReg))
2685 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2686 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2687 const CallInst *CI = cast<CallInst>(I);
2688 const Value *Callee = CI->getCalledValue();
2690 // Handle only C and fastcc calling conventions for now.
2691 ImmutableCallSite CS(CI);
2692 CallingConv::ID CC = CS.getCallingConv();
2693 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2694 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2695 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2696 CC != CallingConv::X86_64_SysV)
2699 // fastcc with -tailcallopt is intended to provide a guaranteed
2700 // tail call optimization. Fastisel doesn't know how to do that.
2701 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2704 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2705 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2706 bool isVarArg = FTy->isVarArg();
2708 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2709 // x86-32. Special handling for x86-64 is implemented.
2710 if (isVarArg && isWin64)
2713 // Don't know about inalloca yet.
2714 if (CS.hasInAllocaArgument())
2717 // Fast-isel doesn't know about callee-pop yet.
2718 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2719 TM.Options.GuaranteedTailCallOpt))
2722 // Check whether the function can return without sret-demotion.
2723 SmallVector<ISD::OutputArg, 4> Outs;
2724 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2725 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2726 *FuncInfo.MF, FTy->isVarArg(),
2727 Outs, FTy->getContext());
2728 if (!CanLowerReturn)
2731 // Materialize callee address in a register. FIXME: GV address can be
2732 // handled with a CALLpcrel32 instead.
2733 X86AddressMode CalleeAM;
2734 if (!X86SelectCallAddress(Callee, CalleeAM))
2736 unsigned CalleeOp = 0;
2737 const GlobalValue *GV = nullptr;
2738 if (CalleeAM.GV != nullptr) {
2740 } else if (CalleeAM.Base.Reg != 0) {
2741 CalleeOp = CalleeAM.Base.Reg;
2745 // Deal with call operands first.
2746 SmallVector<const Value *, 8> ArgVals;
2747 SmallVector<unsigned, 8> Args;
2748 SmallVector<MVT, 8> ArgVTs;
2749 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2750 unsigned arg_size = CS.arg_size();
2751 Args.reserve(arg_size);
2752 ArgVals.reserve(arg_size);
2753 ArgVTs.reserve(arg_size);
2754 ArgFlags.reserve(arg_size);
2755 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2757 // If we're lowering a mem intrinsic instead of a regular call, skip the
2758 // last two arguments, which should not passed to the underlying functions.
2759 if (MemIntName && e-i <= 2)
2762 ISD::ArgFlagsTy Flags;
2763 unsigned AttrInd = i - CS.arg_begin() + 1;
2764 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2766 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2769 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2770 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2771 Type *ElementTy = Ty->getElementType();
2772 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2773 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2775 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2777 Flags.setByValSize(FrameSize);
2778 Flags.setByValAlign(FrameAlign);
2779 if (!IsMemcpySmall(FrameSize))
2783 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2785 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2788 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2789 // instruction. This is safe because it is common to all fastisel supported
2790 // calling conventions on x86.
2791 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2792 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2793 CI->getBitWidth() == 16) {
2795 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2797 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2803 // Passing bools around ends up doing a trunc to i1 and passing it.
2804 // Codegen this as an argument + "and 1".
2805 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2806 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2807 ArgVal->hasOneUse()) {
2808 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2809 ArgReg = getRegForValue(ArgVal);
2810 if (ArgReg == 0) return false;
2813 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2815 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2816 ArgVal->hasOneUse(), 1);
2818 ArgReg = getRegForValue(ArgVal);
2821 if (ArgReg == 0) return false;
2823 Type *ArgTy = ArgVal->getType();
2825 if (!isTypeLegal(ArgTy, ArgVT))
2827 if (ArgVT == MVT::x86mmx)
2829 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2830 Flags.setOrigAlign(OriginalAlignment);
2832 Args.push_back(ArgReg);
2833 ArgVals.push_back(ArgVal);
2834 ArgVTs.push_back(ArgVT);
2835 ArgFlags.push_back(Flags);
2838 // Analyze operands of the call, assigning locations to each operand.
2839 SmallVector<CCValAssign, 16> ArgLocs;
2840 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2841 I->getParent()->getContext());
2843 // Allocate shadow area for Win64
2845 CCInfo.AllocateStack(32, 8);
2847 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2849 // Get a count of how many bytes are to be pushed on the stack.
2850 unsigned NumBytes = CCInfo.getNextStackOffset();
2852 // Issue CALLSEQ_START
2853 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2854 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2857 // Process argument: walk the register/memloc assignments, inserting
2859 SmallVector<unsigned, 4> RegArgs;
2860 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2861 CCValAssign &VA = ArgLocs[i];
2862 unsigned Arg = Args[VA.getValNo()];
2863 EVT ArgVT = ArgVTs[VA.getValNo()];
2865 // Promote the value if needed.
2866 switch (VA.getLocInfo()) {
2867 case CCValAssign::Full: break;
2868 case CCValAssign::SExt: {
2869 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2870 "Unexpected extend");
2871 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2873 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2874 ArgVT = VA.getLocVT();
2877 case CCValAssign::ZExt: {
2878 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2879 "Unexpected extend");
2880 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2882 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2883 ArgVT = VA.getLocVT();
2886 case CCValAssign::AExt: {
2887 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2888 "Unexpected extend");
2889 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2892 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2895 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2898 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2899 ArgVT = VA.getLocVT();
2902 case CCValAssign::BCvt: {
2903 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2904 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2905 assert(BC != 0 && "Failed to emit a bitcast!");
2907 ArgVT = VA.getLocVT();
2910 case CCValAssign::VExt:
2911 // VExt has not been implemented, so this should be impossible to reach
2912 // for now. However, fallback to Selection DAG isel once implemented.
2914 case CCValAssign::Indirect:
2915 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2918 case CCValAssign::FPExt:
2919 llvm_unreachable("Unexpected loc info!");
2922 if (VA.isRegLoc()) {
2923 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2924 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2925 RegArgs.push_back(VA.getLocReg());
2927 unsigned LocMemOffset = VA.getLocMemOffset();
2929 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2930 getTargetMachine()->getRegisterInfo());
2931 AM.Base.Reg = RegInfo->getStackRegister();
2932 AM.Disp = LocMemOffset;
2933 const Value *ArgVal = ArgVals[VA.getValNo()];
2934 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2936 if (Flags.isByVal()) {
2937 X86AddressMode SrcAM;
2938 SrcAM.Base.Reg = Arg;
2939 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2940 assert(Res && "memcpy length already checked!"); (void)Res;
2941 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2942 // If this is a really simple value, emit this with the Value* version
2943 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2944 // as it can cause us to reevaluate the argument.
2945 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2948 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2954 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2956 if (Subtarget->isPICStyleGOT()) {
2957 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2958 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2959 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2962 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2963 // Count the number of XMM registers allocated.
2964 static const MCPhysReg XMMArgRegs[] = {
2965 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2966 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2968 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2969 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2970 X86::AL).addImm(NumXMMRegs);
2974 MachineInstrBuilder MIB;
2976 // Register-indirect call.
2978 if (Subtarget->is64Bit())
2979 CallOpc = X86::CALL64r;
2981 CallOpc = X86::CALL32r;
2982 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2987 assert(GV && "Not a direct call");
2989 if (Subtarget->is64Bit())
2990 CallOpc = X86::CALL64pcrel32;
2992 CallOpc = X86::CALLpcrel32;
2994 // See if we need any target-specific flags on the GV operand.
2995 unsigned char OpFlags = 0;
2997 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2998 // external symbols most go through the PLT in PIC mode. If the symbol
2999 // has hidden or protected visibility, or if it is static or local, then
3000 // we don't need to use the PLT - we can directly call it.
3001 if (Subtarget->isTargetELF() &&
3002 TM.getRelocationModel() == Reloc::PIC_ &&
3003 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3004 OpFlags = X86II::MO_PLT;
3005 } else if (Subtarget->isPICStyleStubAny() &&
3006 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3007 (!Subtarget->getTargetTriple().isMacOSX() ||
3008 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3009 // PC-relative references to external symbols should go through $stub,
3010 // unless we're building with the leopard linker or later, which
3011 // automatically synthesizes these stubs.
3012 OpFlags = X86II::MO_DARWIN_STUB;
3016 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3018 MIB.addExternalSymbol(MemIntName, OpFlags);
3020 MIB.addGlobalAddress(GV, 0, OpFlags);
3023 // Add a register mask with the call-preserved registers.
3024 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3025 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
3027 // Add an implicit use GOT pointer in EBX.
3028 if (Subtarget->isPICStyleGOT())
3029 MIB.addReg(X86::EBX, RegState::Implicit);
3031 if (Subtarget->is64Bit() && isVarArg && !isWin64)
3032 MIB.addReg(X86::AL, RegState::Implicit);
3034 // Add implicit physical register uses to the call.
3035 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
3036 MIB.addReg(RegArgs[i], RegState::Implicit);
3038 // Issue CALLSEQ_END
3039 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3040 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
3041 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3042 .addImm(NumBytes).addImm(NumBytesCallee);
3044 // Build info for return calling conv lowering code.
3045 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
3046 SmallVector<ISD::InputArg, 32> Ins;
3047 SmallVector<EVT, 4> RetTys;
3048 ComputeValueVTs(TLI, I->getType(), RetTys);
3049 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
3051 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
3052 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
3053 for (unsigned j = 0; j != NumRegs; ++j) {
3054 ISD::InputArg MyFlags;
3055 MyFlags.VT = RegisterVT;
3056 MyFlags.Used = !CS.getInstruction()->use_empty();
3057 if (CS.paramHasAttr(0, Attribute::SExt))
3058 MyFlags.Flags.setSExt();
3059 if (CS.paramHasAttr(0, Attribute::ZExt))
3060 MyFlags.Flags.setZExt();
3061 if (CS.paramHasAttr(0, Attribute::InReg))
3062 MyFlags.Flags.setInReg();
3063 Ins.push_back(MyFlags);
3067 // Now handle call return values.
3068 SmallVector<unsigned, 4> UsedRegs;
3069 SmallVector<CCValAssign, 16> RVLocs;
3070 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
3071 I->getParent()->getContext());
3072 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
3073 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3074 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3075 EVT CopyVT = RVLocs[i].getValVT();
3076 unsigned CopyReg = ResultReg + i;
3078 // If this is a call to a function that returns an fp value on the x87 fp
3079 // stack, but where we prefer to use the value in xmm registers, copy it
3080 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
3081 if ((RVLocs[i].getLocReg() == X86::ST0 ||
3082 RVLocs[i].getLocReg() == X86::ST1)) {
3083 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
3085 CopyReg = createResultReg(&X86::RFP80RegClass);
3087 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3088 TII.get(X86::FpPOP_RETVAL), CopyReg);
3090 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3091 TII.get(TargetOpcode::COPY),
3092 CopyReg).addReg(RVLocs[i].getLocReg());
3093 UsedRegs.push_back(RVLocs[i].getLocReg());
3096 if (CopyVT != RVLocs[i].getValVT()) {
3097 // Round the F80 the right size, which also moves to the appropriate xmm
3098 // register. This is accomplished by storing the F80 value in memory and
3099 // then loading it back. Ewww...
3100 EVT ResVT = RVLocs[i].getValVT();
3101 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3102 unsigned MemSize = ResVT.getSizeInBits()/8;
3103 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3104 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3107 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3108 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3109 TII.get(Opc), ResultReg + i), FI);
3114 UpdateValueMap(I, ResultReg, RVLocs.size());
3116 // Set all unused physreg defs as dead.
3117 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
3124 X86FastISel::TargetSelectInstruction(const Instruction *I) {
3125 switch (I->getOpcode()) {
3127 case Instruction::Load:
3128 return X86SelectLoad(I);
3129 case Instruction::Store:
3130 return X86SelectStore(I);
3131 case Instruction::Ret:
3132 return X86SelectRet(I);
3133 case Instruction::ICmp:
3134 case Instruction::FCmp:
3135 return X86SelectCmp(I);
3136 case Instruction::ZExt:
3137 return X86SelectZExt(I);
3138 case Instruction::Br:
3139 return X86SelectBranch(I);
3140 case Instruction::Call:
3141 return X86SelectCall(I);
3142 case Instruction::LShr:
3143 case Instruction::AShr:
3144 case Instruction::Shl:
3145 return X86SelectShift(I);
3146 case Instruction::SDiv:
3147 case Instruction::UDiv:
3148 case Instruction::SRem:
3149 case Instruction::URem:
3150 return X86SelectDivRem(I);
3151 case Instruction::Select:
3152 return X86SelectSelect(I);
3153 case Instruction::Trunc:
3154 return X86SelectTrunc(I);
3155 case Instruction::FPExt:
3156 return X86SelectFPExt(I);
3157 case Instruction::FPTrunc:
3158 return X86SelectFPTrunc(I);
3159 case Instruction::IntToPtr: // Deliberate fall-through.
3160 case Instruction::PtrToInt: {
3161 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3162 EVT DstVT = TLI.getValueType(I->getType());
3163 if (DstVT.bitsGT(SrcVT))
3164 return X86SelectZExt(I);
3165 if (DstVT.bitsLT(SrcVT))
3166 return X86SelectTrunc(I);
3167 unsigned Reg = getRegForValue(I->getOperand(0));
3168 if (Reg == 0) return false;
3169 UpdateValueMap(I, Reg);
3177 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
3179 if (!isTypeLegal(C->getType(), VT))
3182 // Can't handle alternate code models yet.
3183 if (TM.getCodeModel() != CodeModel::Small)
3186 // Get opcode and regclass of the output for the given load instruction.
3188 const TargetRegisterClass *RC = nullptr;
3189 switch (VT.SimpleTy) {
3193 RC = &X86::GR8RegClass;
3197 RC = &X86::GR16RegClass;
3201 RC = &X86::GR32RegClass;
3204 // Must be in x86-64 mode.
3206 RC = &X86::GR64RegClass;
3209 if (X86ScalarSSEf32) {
3210 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3211 RC = &X86::FR32RegClass;
3213 Opc = X86::LD_Fp32m;
3214 RC = &X86::RFP32RegClass;
3218 if (X86ScalarSSEf64) {
3219 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3220 RC = &X86::FR64RegClass;
3222 Opc = X86::LD_Fp64m;
3223 RC = &X86::RFP64RegClass;
3227 // No f80 support yet.
3231 // Materialize addresses with LEA/MOV instructions.
3232 if (isa<GlobalValue>(C)) {
3234 if (X86SelectAddress(C, AM)) {
3235 // If the expression is just a basereg, then we're done, otherwise we need
3237 if (AM.BaseType == X86AddressMode::RegBase &&
3238 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3241 unsigned ResultReg = createResultReg(RC);
3242 if (TM.getRelocationModel() == Reloc::Static &&
3243 TLI.getPointerTy() == MVT::i64) {
3244 // The displacement code be more than 32 bits away so we need to use
3245 // an instruction with a 64 bit immediate
3247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3248 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
3250 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
3251 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3252 TII.get(Opc), ResultReg), AM);
3259 // MachineConstantPool wants an explicit alignment.
3260 unsigned Align = DL.getPrefTypeAlignment(C->getType());
3262 // Alignment of vector types. FIXME!
3263 Align = DL.getTypeAllocSize(C->getType());
3266 // x86-32 PIC requires a PIC base register for constant pools.
3267 unsigned PICBase = 0;
3268 unsigned char OpFlag = 0;
3269 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3270 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3271 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3272 } else if (Subtarget->isPICStyleGOT()) {
3273 OpFlag = X86II::MO_GOTOFF;
3274 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3275 } else if (Subtarget->isPICStyleRIPRel() &&
3276 TM.getCodeModel() == CodeModel::Small) {
3280 // Create the load from the constant pool.
3281 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
3282 unsigned ResultReg = createResultReg(RC);
3283 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3284 TII.get(Opc), ResultReg),
3285 MCPOffset, PICBase, OpFlag);
3290 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
3291 // Fail on dynamic allocas. At this point, getRegForValue has already
3292 // checked its CSE maps, so if we're here trying to handle a dynamic
3293 // alloca, we're not going to succeed. X86SelectAddress has a
3294 // check for dynamic allocas, because it's called directly from
3295 // various places, but TargetMaterializeAlloca also needs a check
3296 // in order to avoid recursion between getRegForValue,
3297 // X86SelectAddrss, and TargetMaterializeAlloca.
3298 if (!FuncInfo.StaticAllocaMap.count(C))
3300 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3303 if (!X86SelectAddress(C, AM))
3305 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3306 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3307 unsigned ResultReg = createResultReg(RC);
3308 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3309 TII.get(Opc), ResultReg), AM);
3313 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3315 if (!isTypeLegal(CF->getType(), VT))
3318 // Get opcode and regclass for the given zero.
3320 const TargetRegisterClass *RC = nullptr;
3321 switch (VT.SimpleTy) {
3324 if (X86ScalarSSEf32) {
3325 Opc = X86::FsFLD0SS;
3326 RC = &X86::FR32RegClass;
3328 Opc = X86::LD_Fp032;
3329 RC = &X86::RFP32RegClass;
3333 if (X86ScalarSSEf64) {
3334 Opc = X86::FsFLD0SD;
3335 RC = &X86::FR64RegClass;
3337 Opc = X86::LD_Fp064;
3338 RC = &X86::RFP64RegClass;
3342 // No f80 support yet.
3346 unsigned ResultReg = createResultReg(RC);
3347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3352 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3353 const LoadInst *LI) {
3354 const Value *Ptr = LI->getPointerOperand();
3356 if (!X86SelectAddress(Ptr, AM))
3359 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3361 unsigned Size = DL.getTypeAllocSize(LI->getType());
3362 unsigned Alignment = LI->getAlignment();
3364 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3365 Alignment = DL.getABITypeAlignment(LI->getType());
3367 SmallVector<MachineOperand, 8> AddrOps;
3368 AM.getFullAddress(AddrOps);
3370 MachineInstr *Result =
3371 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3375 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3376 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3377 MI->eraseFromParent();
3383 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3384 const TargetLibraryInfo *libInfo) {
3385 return new X86FastISel(funcInfo, libInfo);