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);
162 } // end anonymous namespace.
164 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
165 // If both operands are the same, then try to optimize or fold the cmp.
166 CmpInst::Predicate Predicate = CI->getPredicate();
167 if (CI->getOperand(0) != CI->getOperand(1))
171 default: llvm_unreachable("Invalid predicate!");
172 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
173 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
174 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
175 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
176 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
177 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
178 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
179 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
180 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
181 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
182 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
183 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
184 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
185 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
186 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
187 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
189 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
190 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
191 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
192 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
193 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
194 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
195 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
196 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
197 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
198 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
204 static std::pair<X86::CondCode, bool>
205 getX86ConditonCode(CmpInst::Predicate Predicate) {
206 X86::CondCode CC = X86::COND_INVALID;
207 bool NeedSwap = false;
210 // Floating-point Predicates
211 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
212 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
213 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
214 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
215 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
216 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
217 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
218 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
219 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
220 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
221 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
222 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
223 case CmpInst::FCMP_OEQ: // fall-through
224 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
226 // Integer Predicates
227 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
228 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
229 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
230 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
231 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
232 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
233 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
234 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
235 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
236 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
239 return std::make_pair(CC, NeedSwap);
242 static std::pair<unsigned, bool>
243 getX86SSECondtionCode(CmpInst::Predicate Predicate) {
245 bool NeedSwap = false;
247 // SSE Condition code mapping:
257 default: llvm_unreachable("Unexpected predicate");
258 case CmpInst::FCMP_OEQ: CC = 0; break;
259 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
260 case CmpInst::FCMP_OLT: CC = 1; break;
261 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
262 case CmpInst::FCMP_OLE: CC = 2; break;
263 case CmpInst::FCMP_UNO: CC = 3; break;
264 case CmpInst::FCMP_UNE: CC = 4; break;
265 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
266 case CmpInst::FCMP_UGE: CC = 5; break;
267 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
268 case CmpInst::FCMP_UGT: CC = 6; break;
269 case CmpInst::FCMP_ORD: CC = 7; break;
270 case CmpInst::FCMP_UEQ:
271 case CmpInst::FCMP_ONE: CC = 8; break;
274 return std::make_pair(CC, NeedSwap);
277 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
278 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
279 if (evt == MVT::Other || !evt.isSimple())
280 // Unhandled type. Halt "fast" selection and bail.
283 VT = evt.getSimpleVT();
284 // For now, require SSE/SSE2 for performing floating-point operations,
285 // since x87 requires additional work.
286 if (VT == MVT::f64 && !X86ScalarSSEf64)
288 if (VT == MVT::f32 && !X86ScalarSSEf32)
290 // Similarly, no f80 support yet.
293 // We only handle legal types. For example, on x86-32 the instruction
294 // selector contains all of the 64-bit instructions from x86-64,
295 // under the assumption that i64 won't be used if the target doesn't
297 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
300 #include "X86GenCallingConv.inc"
302 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
303 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
304 /// Return true and the result register by reference if it is possible.
305 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
306 MachineMemOperand *MMO, unsigned &ResultReg) {
307 // Get opcode and regclass of the output for the given load instruction.
309 const TargetRegisterClass *RC = nullptr;
310 switch (VT.getSimpleVT().SimpleTy) {
311 default: return false;
315 RC = &X86::GR8RegClass;
319 RC = &X86::GR16RegClass;
323 RC = &X86::GR32RegClass;
326 // Must be in x86-64 mode.
328 RC = &X86::GR64RegClass;
331 if (X86ScalarSSEf32) {
332 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
333 RC = &X86::FR32RegClass;
336 RC = &X86::RFP32RegClass;
340 if (X86ScalarSSEf64) {
341 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
342 RC = &X86::FR64RegClass;
345 RC = &X86::RFP64RegClass;
349 // No f80 support yet.
353 ResultReg = createResultReg(RC);
354 MachineInstrBuilder MIB =
355 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
356 addFullAddress(MIB, AM);
358 MIB->addMemOperand(*FuncInfo.MF, MMO);
362 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
363 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
364 /// and a displacement offset, or a GlobalAddress,
365 /// i.e. V. Return true if it is possible.
366 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
367 const X86AddressMode &AM,
368 MachineMemOperand *MMO, bool Aligned) {
369 // Get opcode and regclass of the output for the given store instruction.
371 switch (VT.getSimpleVT().SimpleTy) {
372 case MVT::f80: // No f80 support yet.
373 default: return false;
375 // Mask out all but lowest bit.
376 unsigned AndResult = createResultReg(&X86::GR8RegClass);
377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
378 TII.get(X86::AND8ri), AndResult)
379 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
382 // FALLTHROUGH, handling i1 as i8.
383 case MVT::i8: Opc = X86::MOV8mr; break;
384 case MVT::i16: Opc = X86::MOV16mr; break;
385 case MVT::i32: Opc = X86::MOV32mr; break;
386 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
388 Opc = X86ScalarSSEf32 ?
389 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
392 Opc = X86ScalarSSEf64 ?
393 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
397 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
399 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
403 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
405 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
412 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
414 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
418 MachineInstrBuilder MIB =
419 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
420 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
422 MIB->addMemOperand(*FuncInfo.MF, MMO);
427 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
428 const X86AddressMode &AM,
429 MachineMemOperand *MMO, bool Aligned) {
430 // Handle 'null' like i32/i64 0.
431 if (isa<ConstantPointerNull>(Val))
432 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
434 // If this is a store of a simple constant, fold the constant into the store.
435 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
438 switch (VT.getSimpleVT().SimpleTy) {
440 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
441 case MVT::i8: Opc = X86::MOV8mi; break;
442 case MVT::i16: Opc = X86::MOV16mi; break;
443 case MVT::i32: Opc = X86::MOV32mi; break;
445 // Must be a 32-bit sign extended value.
446 if (isInt<32>(CI->getSExtValue()))
447 Opc = X86::MOV64mi32;
452 MachineInstrBuilder MIB =
453 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
454 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
455 : CI->getZExtValue());
457 MIB->addMemOperand(*FuncInfo.MF, MMO);
462 unsigned ValReg = getRegForValue(Val);
466 bool ValKill = hasTrivialKill(Val);
467 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
470 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
471 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
472 /// ISD::SIGN_EXTEND).
473 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
474 unsigned Src, EVT SrcVT,
475 unsigned &ResultReg) {
476 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
477 Src, /*TODO: Kill=*/false);
485 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
486 // Handle constant address.
487 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
488 // Can't handle alternate code models yet.
489 if (TM.getCodeModel() != CodeModel::Small)
492 // Can't handle TLS yet.
493 if (GV->isThreadLocal())
496 // RIP-relative addresses can't have additional register operands, so if
497 // we've already folded stuff into the addressing mode, just force the
498 // global value into its own register, which we can use as the basereg.
499 if (!Subtarget->isPICStyleRIPRel() ||
500 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
501 // Okay, we've committed to selecting this global. Set up the address.
504 // Allow the subtarget to classify the global.
505 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
507 // If this reference is relative to the pic base, set it now.
508 if (isGlobalRelativeToPICBase(GVFlags)) {
509 // FIXME: How do we know Base.Reg is free??
510 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
513 // Unless the ABI requires an extra load, return a direct reference to
515 if (!isGlobalStubReference(GVFlags)) {
516 if (Subtarget->isPICStyleRIPRel()) {
517 // Use rip-relative addressing if we can. Above we verified that the
518 // base and index registers are unused.
519 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
520 AM.Base.Reg = X86::RIP;
522 AM.GVOpFlags = GVFlags;
526 // Ok, we need to do a load from a stub. If we've already loaded from
527 // this stub, reuse the loaded pointer, otherwise emit the load now.
528 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
530 if (I != LocalValueMap.end() && I->second != 0) {
533 // Issue load from stub.
535 const TargetRegisterClass *RC = nullptr;
536 X86AddressMode StubAM;
537 StubAM.Base.Reg = AM.Base.Reg;
539 StubAM.GVOpFlags = GVFlags;
541 // Prepare for inserting code in the local-value area.
542 SavePoint SaveInsertPt = enterLocalValueArea();
544 if (TLI.getPointerTy() == MVT::i64) {
546 RC = &X86::GR64RegClass;
548 if (Subtarget->isPICStyleRIPRel())
549 StubAM.Base.Reg = X86::RIP;
552 RC = &X86::GR32RegClass;
555 LoadReg = createResultReg(RC);
556 MachineInstrBuilder LoadMI =
557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
558 addFullAddress(LoadMI, StubAM);
560 // Ok, back to normal mode.
561 leaveLocalValueArea(SaveInsertPt);
563 // Prevent loading GV stub multiple times in same MBB.
564 LocalValueMap[V] = LoadReg;
567 // Now construct the final address. Note that the Disp, Scale,
568 // and Index values may already be set here.
569 AM.Base.Reg = LoadReg;
575 // If all else fails, try to materialize the value in a register.
576 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
577 if (AM.Base.Reg == 0) {
578 AM.Base.Reg = getRegForValue(V);
579 return AM.Base.Reg != 0;
581 if (AM.IndexReg == 0) {
582 assert(AM.Scale == 1 && "Scale with no index!");
583 AM.IndexReg = getRegForValue(V);
584 return AM.IndexReg != 0;
591 /// X86SelectAddress - Attempt to fill in an address from the given value.
593 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
594 SmallVector<const Value *, 32> GEPs;
596 const User *U = nullptr;
597 unsigned Opcode = Instruction::UserOp1;
598 if (const Instruction *I = dyn_cast<Instruction>(V)) {
599 // Don't walk into other basic blocks; it's possible we haven't
600 // visited them yet, so the instructions may not yet be assigned
601 // virtual registers.
602 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
603 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
604 Opcode = I->getOpcode();
607 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
608 Opcode = C->getOpcode();
612 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
613 if (Ty->getAddressSpace() > 255)
614 // Fast instruction selection doesn't support the special
620 case Instruction::BitCast:
621 // Look past bitcasts.
622 return X86SelectAddress(U->getOperand(0), AM);
624 case Instruction::IntToPtr:
625 // Look past no-op inttoptrs.
626 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
627 return X86SelectAddress(U->getOperand(0), AM);
630 case Instruction::PtrToInt:
631 // Look past no-op ptrtoints.
632 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
633 return X86SelectAddress(U->getOperand(0), AM);
636 case Instruction::Alloca: {
637 // Do static allocas.
638 const AllocaInst *A = cast<AllocaInst>(V);
639 DenseMap<const AllocaInst*, int>::iterator SI =
640 FuncInfo.StaticAllocaMap.find(A);
641 if (SI != FuncInfo.StaticAllocaMap.end()) {
642 AM.BaseType = X86AddressMode::FrameIndexBase;
643 AM.Base.FrameIndex = SI->second;
649 case Instruction::Add: {
650 // Adds of constants are common and easy enough.
651 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
652 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
653 // They have to fit in the 32-bit signed displacement field though.
654 if (isInt<32>(Disp)) {
655 AM.Disp = (uint32_t)Disp;
656 return X86SelectAddress(U->getOperand(0), AM);
662 case Instruction::GetElementPtr: {
663 X86AddressMode SavedAM = AM;
665 // Pattern-match simple GEPs.
666 uint64_t Disp = (int32_t)AM.Disp;
667 unsigned IndexReg = AM.IndexReg;
668 unsigned Scale = AM.Scale;
669 gep_type_iterator GTI = gep_type_begin(U);
670 // Iterate through the indices, folding what we can. Constants can be
671 // folded, and one dynamic index can be handled, if the scale is supported.
672 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
673 i != e; ++i, ++GTI) {
674 const Value *Op = *i;
675 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
676 const StructLayout *SL = DL.getStructLayout(STy);
677 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
681 // A array/variable index is always of the form i*S where S is the
682 // constant scale size. See if we can push the scale into immediates.
683 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
685 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
686 // Constant-offset addressing.
687 Disp += CI->getSExtValue() * S;
690 if (canFoldAddIntoGEP(U, Op)) {
691 // A compatible add with a constant operand. Fold the constant.
693 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
694 Disp += CI->getSExtValue() * S;
695 // Iterate on the other operand.
696 Op = cast<AddOperator>(Op)->getOperand(0);
700 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
701 (S == 1 || S == 2 || S == 4 || S == 8)) {
702 // Scaled-index addressing.
704 IndexReg = getRegForGEPIndex(Op).first;
710 goto unsupported_gep;
714 // Check for displacement overflow.
715 if (!isInt<32>(Disp))
718 AM.IndexReg = IndexReg;
720 AM.Disp = (uint32_t)Disp;
723 if (const GetElementPtrInst *GEP =
724 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
725 // Ok, the GEP indices were covered by constant-offset and scaled-index
726 // addressing. Update the address state and move on to examining the base.
729 } else if (X86SelectAddress(U->getOperand(0), AM)) {
733 // If we couldn't merge the gep value into this addr mode, revert back to
734 // our address and just match the value instead of completely failing.
737 for (SmallVectorImpl<const Value *>::reverse_iterator
738 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
739 if (handleConstantAddresses(*I, AM))
744 // Ok, the GEP indices weren't all covered.
749 return handleConstantAddresses(V, AM);
752 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
754 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
755 const User *U = nullptr;
756 unsigned Opcode = Instruction::UserOp1;
757 const Instruction *I = dyn_cast<Instruction>(V);
758 // Record if the value is defined in the same basic block.
760 // This information is crucial to know whether or not folding an
762 // Indeed, FastISel generates or reuses a virtual register for all
763 // operands of all instructions it selects. Obviously, the definition and
764 // its uses must use the same virtual register otherwise the produced
765 // code is incorrect.
766 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
767 // registers for values that are alive across basic blocks. This ensures
768 // that the values are consistently set between across basic block, even
769 // if different instruction selection mechanisms are used (e.g., a mix of
770 // SDISel and FastISel).
771 // For values local to a basic block, the instruction selection process
772 // generates these virtual registers with whatever method is appropriate
773 // for its needs. In particular, FastISel and SDISel do not share the way
774 // local virtual registers are set.
775 // Therefore, this is impossible (or at least unsafe) to share values
776 // between basic blocks unless they use the same instruction selection
777 // method, which is not guarantee for X86.
778 // Moreover, things like hasOneUse could not be used accurately, if we
779 // allow to reference values across basic blocks whereas they are not
780 // alive across basic blocks initially.
783 Opcode = I->getOpcode();
785 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
786 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
787 Opcode = C->getOpcode();
793 case Instruction::BitCast:
794 // Look past bitcasts if its operand is in the same BB.
796 return X86SelectCallAddress(U->getOperand(0), AM);
799 case Instruction::IntToPtr:
800 // Look past no-op inttoptrs if its operand is in the same BB.
802 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
803 return X86SelectCallAddress(U->getOperand(0), AM);
806 case Instruction::PtrToInt:
807 // Look past no-op ptrtoints if its operand is in the same BB.
809 TLI.getValueType(U->getType()) == TLI.getPointerTy())
810 return X86SelectCallAddress(U->getOperand(0), AM);
814 // Handle constant address.
815 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
816 // Can't handle alternate code models yet.
817 if (TM.getCodeModel() != CodeModel::Small)
820 // RIP-relative addresses can't have additional register operands.
821 if (Subtarget->isPICStyleRIPRel() &&
822 (AM.Base.Reg != 0 || AM.IndexReg != 0))
825 // Can't handle DbgLocLImport.
826 if (GV->hasDLLImportStorageClass())
830 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
831 if (GVar->isThreadLocal())
834 // Okay, we've committed to selecting this global. Set up the basic address.
837 // No ABI requires an extra load for anything other than DLLImport, which
838 // we rejected above. Return a direct reference to the global.
839 if (Subtarget->isPICStyleRIPRel()) {
840 // Use rip-relative addressing if we can. Above we verified that the
841 // base and index registers are unused.
842 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
843 AM.Base.Reg = X86::RIP;
844 } else if (Subtarget->isPICStyleStubPIC()) {
845 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
846 } else if (Subtarget->isPICStyleGOT()) {
847 AM.GVOpFlags = X86II::MO_GOTOFF;
853 // If all else fails, try to materialize the value in a register.
854 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
855 if (AM.Base.Reg == 0) {
856 AM.Base.Reg = getRegForValue(V);
857 return AM.Base.Reg != 0;
859 if (AM.IndexReg == 0) {
860 assert(AM.Scale == 1 && "Scale with no index!");
861 AM.IndexReg = getRegForValue(V);
862 return AM.IndexReg != 0;
870 /// X86SelectStore - Select and emit code to implement store instructions.
871 bool X86FastISel::X86SelectStore(const Instruction *I) {
872 // Atomic stores need special handling.
873 const StoreInst *S = cast<StoreInst>(I);
878 const Value *Val = S->getValueOperand();
879 const Value *Ptr = S->getPointerOperand();
882 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
885 unsigned Alignment = S->getAlignment();
886 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
887 if (Alignment == 0) // Ensure that codegen never sees alignment 0
888 Alignment = ABIAlignment;
889 bool Aligned = Alignment >= ABIAlignment;
892 if (!X86SelectAddress(Ptr, AM))
895 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
898 /// X86SelectRet - Select and emit code to implement ret instructions.
899 bool X86FastISel::X86SelectRet(const Instruction *I) {
900 const ReturnInst *Ret = cast<ReturnInst>(I);
901 const Function &F = *I->getParent()->getParent();
902 const X86MachineFunctionInfo *X86MFInfo =
903 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
905 if (!FuncInfo.CanLowerReturn)
908 CallingConv::ID CC = F.getCallingConv();
909 if (CC != CallingConv::C &&
910 CC != CallingConv::Fast &&
911 CC != CallingConv::X86_FastCall &&
912 CC != CallingConv::X86_64_SysV)
915 if (Subtarget->isCallingConvWin64(CC))
918 // Don't handle popping bytes on return for now.
919 if (X86MFInfo->getBytesToPopOnReturn() != 0)
922 // fastcc with -tailcallopt is intended to provide a guaranteed
923 // tail call optimization. Fastisel doesn't know how to do that.
924 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
927 // Let SDISel handle vararg functions.
931 // Build a list of return value registers.
932 SmallVector<unsigned, 4> RetRegs;
934 if (Ret->getNumOperands() > 0) {
935 SmallVector<ISD::OutputArg, 4> Outs;
936 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
938 // Analyze operands of the call, assigning locations to each operand.
939 SmallVector<CCValAssign, 16> ValLocs;
940 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
942 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
944 const Value *RV = Ret->getOperand(0);
945 unsigned Reg = getRegForValue(RV);
949 // Only handle a single return value for now.
950 if (ValLocs.size() != 1)
953 CCValAssign &VA = ValLocs[0];
955 // Don't bother handling odd stuff for now.
956 if (VA.getLocInfo() != CCValAssign::Full)
958 // Only handle register returns for now.
962 // The calling-convention tables for x87 returns don't tell
964 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
967 unsigned SrcReg = Reg + VA.getValNo();
968 EVT SrcVT = TLI.getValueType(RV->getType());
969 EVT DstVT = VA.getValVT();
970 // Special handling for extended integers.
971 if (SrcVT != DstVT) {
972 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
975 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
978 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
980 if (SrcVT == MVT::i1) {
981 if (Outs[0].Flags.isSExt())
983 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
986 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
988 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
989 SrcReg, /*TODO: Kill=*/false);
993 unsigned DstReg = VA.getLocReg();
994 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
995 // Avoid a cross-class copy. This is very unlikely.
996 if (!SrcRC->contains(DstReg))
998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
999 DstReg).addReg(SrcReg);
1001 // Add register to return instruction.
1002 RetRegs.push_back(VA.getLocReg());
1005 // The x86-64 ABI for returning structs by value requires that we copy
1006 // the sret argument into %rax for the return. We saved the argument into
1007 // a virtual register in the entry block, so now we copy the value out
1008 // and into %rax. We also do the same with %eax for Win32.
1009 if (F.hasStructRetAttr() &&
1010 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1011 unsigned Reg = X86MFInfo->getSRetReturnReg();
1013 "SRetReturnReg should have been set in LowerFormalArguments()!");
1014 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1016 RetReg).addReg(Reg);
1017 RetRegs.push_back(RetReg);
1020 // Now emit the RET.
1021 MachineInstrBuilder MIB =
1022 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1023 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1024 MIB.addReg(RetRegs[i], RegState::Implicit);
1028 /// X86SelectLoad - Select and emit code to implement load instructions.
1030 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1031 const LoadInst *LI = cast<LoadInst>(I);
1033 // Atomic loads need special handling.
1038 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1041 const Value *Ptr = LI->getPointerOperand();
1044 if (!X86SelectAddress(Ptr, AM))
1047 unsigned ResultReg = 0;
1048 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1051 UpdateValueMap(I, ResultReg);
1055 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1056 bool HasAVX = Subtarget->hasAVX();
1057 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1058 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1060 switch (VT.getSimpleVT().SimpleTy) {
1062 case MVT::i8: return X86::CMP8rr;
1063 case MVT::i16: return X86::CMP16rr;
1064 case MVT::i32: return X86::CMP32rr;
1065 case MVT::i64: return X86::CMP64rr;
1067 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1069 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1073 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1074 /// of the comparison, return an opcode that works for the compare (e.g.
1075 /// CMP32ri) otherwise return 0.
1076 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1077 switch (VT.getSimpleVT().SimpleTy) {
1078 // Otherwise, we can't fold the immediate into this comparison.
1080 case MVT::i8: return X86::CMP8ri;
1081 case MVT::i16: return X86::CMP16ri;
1082 case MVT::i32: return X86::CMP32ri;
1084 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1086 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1087 return X86::CMP64ri32;
1092 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1094 unsigned Op0Reg = getRegForValue(Op0);
1095 if (Op0Reg == 0) return false;
1097 // Handle 'null' like i32/i64 0.
1098 if (isa<ConstantPointerNull>(Op1))
1099 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1101 // We have two options: compare with register or immediate. If the RHS of
1102 // the compare is an immediate that we can fold into this compare, use
1103 // CMPri, otherwise use CMPrr.
1104 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1105 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1106 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1108 .addImm(Op1C->getSExtValue());
1113 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1114 if (CompareOpc == 0) return false;
1116 unsigned Op1Reg = getRegForValue(Op1);
1117 if (Op1Reg == 0) return false;
1118 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1125 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1126 const CmpInst *CI = cast<CmpInst>(I);
1129 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1132 // Try to optimize or fold the cmp.
1133 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1134 unsigned ResultReg = 0;
1135 switch (Predicate) {
1137 case CmpInst::FCMP_FALSE: {
1138 ResultReg = createResultReg(&X86::GR32RegClass);
1139 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1141 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1147 case CmpInst::FCMP_TRUE: {
1148 ResultReg = createResultReg(&X86::GR8RegClass);
1149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1150 ResultReg).addImm(1);
1156 UpdateValueMap(I, ResultReg);
1160 const Value *LHS = CI->getOperand(0);
1161 const Value *RHS = CI->getOperand(1);
1163 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1164 // We don't have to materialize a zero constant for this case and can just use
1165 // %x again on the RHS.
1166 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1167 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1168 if (RHSC && RHSC->isNullValue())
1172 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1173 static unsigned SETFOpcTable[2][3] = {
1174 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1175 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1177 unsigned *SETFOpc = nullptr;
1178 switch (Predicate) {
1180 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1181 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1184 ResultReg = createResultReg(&X86::GR8RegClass);
1186 if (!X86FastEmitCompare(LHS, RHS, VT))
1189 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1190 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1191 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1193 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1196 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1197 UpdateValueMap(I, ResultReg);
1203 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1204 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1205 unsigned Opc = X86::getSETFromCond(CC);
1208 std::swap(LHS, RHS);
1210 // Emit a compare of LHS/RHS.
1211 if (!X86FastEmitCompare(LHS, RHS, VT))
1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1215 UpdateValueMap(I, ResultReg);
1219 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1220 EVT DstVT = TLI.getValueType(I->getType());
1221 if (!TLI.isTypeLegal(DstVT))
1224 unsigned ResultReg = getRegForValue(I->getOperand(0));
1228 // Handle zero-extension from i1 to i8, which is common.
1229 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1230 if (SrcVT.SimpleTy == MVT::i1) {
1231 // Set the high bits to zero.
1232 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1239 if (DstVT == MVT::i64) {
1240 // Handle extension to 64-bits via sub-register shenanigans.
1243 switch (SrcVT.SimpleTy) {
1244 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1245 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1246 case MVT::i32: MovInst = X86::MOV32rr; break;
1247 default: llvm_unreachable("Unexpected zext to i64 source type");
1250 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1254 ResultReg = createResultReg(&X86::GR64RegClass);
1255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1257 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1258 } else if (DstVT != MVT::i8) {
1259 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1260 ResultReg, /*Kill=*/true);
1265 UpdateValueMap(I, ResultReg);
1270 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1271 // Unconditional branches are selected by tablegen-generated code.
1272 // Handle a conditional branch.
1273 const BranchInst *BI = cast<BranchInst>(I);
1274 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1275 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1277 // Fold the common case of a conditional branch with a comparison
1278 // in the same block (values defined on other blocks may not have
1279 // initialized registers).
1280 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1281 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1282 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1284 // Try to optimize or fold the cmp.
1285 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1286 switch (Predicate) {
1288 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1289 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1292 const Value *CmpLHS = CI->getOperand(0);
1293 const Value *CmpRHS = CI->getOperand(1);
1295 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1297 // We don't have to materialize a zero constant for this case and can just
1298 // use %x again on the RHS.
1299 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1300 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1301 if (CmpRHSC && CmpRHSC->isNullValue())
1305 // Try to take advantage of fallthrough opportunities.
1306 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1307 std::swap(TrueMBB, FalseMBB);
1308 Predicate = CmpInst::getInversePredicate(Predicate);
1311 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1312 // code check. Instead two branch instructions are required to check all
1313 // the flags. First we change the predicate to a supported conditon code,
1314 // which will be the first branch. Later one we will emit the second
1316 bool NeedExtraBranch = false;
1317 switch (Predicate) {
1319 case CmpInst::FCMP_OEQ:
1320 std::swap(TrueMBB, FalseMBB); // fall-through
1321 case CmpInst::FCMP_UNE:
1322 NeedExtraBranch = true;
1323 Predicate = CmpInst::FCMP_ONE;
1330 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1331 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1333 BranchOpc = X86::GetCondBranchFromCond(CC);
1335 std::swap(CmpLHS, CmpRHS);
1337 // Emit a compare of the LHS and RHS, setting the flags.
1338 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1344 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1346 if (NeedExtraBranch) {
1347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1351 // Obtain the branch weight and add the TrueBB to the successor list.
1352 uint32_t BranchWeight = 0;
1354 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1355 TrueMBB->getBasicBlock());
1356 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1358 // Emits an unconditional branch to the FalseBB, obtains the branch
1359 // weight, and adds it to the successor list.
1360 FastEmitBranch(FalseMBB, DbgLoc);
1364 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1365 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1366 // typically happen for _Bool and C++ bools.
1368 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1369 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1370 unsigned TestOpc = 0;
1371 switch (SourceVT.SimpleTy) {
1373 case MVT::i8: TestOpc = X86::TEST8ri; break;
1374 case MVT::i16: TestOpc = X86::TEST16ri; break;
1375 case MVT::i32: TestOpc = X86::TEST32ri; break;
1376 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1379 unsigned OpReg = getRegForValue(TI->getOperand(0));
1380 if (OpReg == 0) return false;
1381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1382 .addReg(OpReg).addImm(1);
1384 unsigned JmpOpc = X86::JNE_4;
1385 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1386 std::swap(TrueMBB, FalseMBB);
1390 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1392 FastEmitBranch(FalseMBB, DbgLoc);
1393 uint32_t BranchWeight = 0;
1395 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1396 TrueMBB->getBasicBlock());
1397 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1401 } else if (auto *EV = dyn_cast<ExtractValueInst>(BI->getCondition())) {
1402 bool FoldIntrinsic = false;
1403 if (const auto *II = dyn_cast<IntrinsicInst>(EV->getAggregateOperand())) {
1404 switch (II->getIntrinsicID()) {
1406 case Intrinsic::sadd_with_overflow:
1407 case Intrinsic::uadd_with_overflow:
1408 case Intrinsic::ssub_with_overflow:
1409 case Intrinsic::usub_with_overflow:
1410 case Intrinsic::smul_with_overflow:
1411 case Intrinsic::umul_with_overflow: FoldIntrinsic = true; break;
1414 // Check if both instructions are in the same basic block.
1415 if (FoldIntrinsic && (II->getParent() != I->getParent()))
1416 FoldIntrinsic = false;
1418 // Make sure nothing is in the way
1419 if (FoldIntrinsic) {
1420 BasicBlock::const_iterator Start = I;
1421 BasicBlock::const_iterator End = II;
1422 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
1423 // We only expect extractvalue instructions between the intrinsic and
1425 if (!isa<ExtractValueInst>(Itr)) {
1426 FoldIntrinsic = false;
1430 // Check that the extractvalue operand comes from the intrinsic.
1431 const auto *EVI = cast<ExtractValueInst>(Itr);
1432 if (EVI->getAggregateOperand() != II) {
1433 FoldIntrinsic = false;
1440 if (FoldIntrinsic) {
1442 const IntrinsicInst *II = cast<IntrinsicInst>(EV->getAggregateOperand());
1443 const Function *Callee = II->getCalledFunction();
1445 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
1446 if (!isTypeLegal(RetTy, RetVT))
1449 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1452 // Fake request the condition, otherwise the intrinsic might be completely
1454 unsigned TmpReg = getRegForValue(EV);
1458 unsigned BranchOpc = 0;
1459 switch (II->getIntrinsicID()) {
1460 default: llvm_unreachable("Unexpected intrinsic instruction.");
1461 case Intrinsic::sadd_with_overflow:
1462 case Intrinsic::ssub_with_overflow:
1463 case Intrinsic::smul_with_overflow:
1464 case Intrinsic::umul_with_overflow: BranchOpc = X86::JO_4; break;
1465 case Intrinsic::uadd_with_overflow:
1466 case Intrinsic::usub_with_overflow: BranchOpc = X86::JB_4; break;
1469 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1471 FastEmitBranch(FalseMBB, DbgLoc);
1472 uint32_t BranchWeight = 0;
1474 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1475 TrueMBB->getBasicBlock());
1476 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1481 // Otherwise do a clumsy setcc and re-test it.
1482 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1483 // in an explicit cast, so make sure to handle that correctly.
1484 unsigned OpReg = getRegForValue(BI->getCondition());
1485 if (OpReg == 0) return false;
1487 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1488 .addReg(OpReg).addImm(1);
1489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1491 FastEmitBranch(FalseMBB, DbgLoc);
1492 uint32_t BranchWeight = 0;
1494 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1495 TrueMBB->getBasicBlock());
1496 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1500 bool X86FastISel::X86SelectShift(const Instruction *I) {
1501 unsigned CReg = 0, OpReg = 0;
1502 const TargetRegisterClass *RC = nullptr;
1503 if (I->getType()->isIntegerTy(8)) {
1505 RC = &X86::GR8RegClass;
1506 switch (I->getOpcode()) {
1507 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1508 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1509 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1510 default: return false;
1512 } else if (I->getType()->isIntegerTy(16)) {
1514 RC = &X86::GR16RegClass;
1515 switch (I->getOpcode()) {
1516 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1517 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1518 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1519 default: return false;
1521 } else if (I->getType()->isIntegerTy(32)) {
1523 RC = &X86::GR32RegClass;
1524 switch (I->getOpcode()) {
1525 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1526 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1527 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1528 default: return false;
1530 } else if (I->getType()->isIntegerTy(64)) {
1532 RC = &X86::GR64RegClass;
1533 switch (I->getOpcode()) {
1534 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1535 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1536 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1537 default: return false;
1544 if (!isTypeLegal(I->getType(), VT))
1547 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1548 if (Op0Reg == 0) return false;
1550 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1551 if (Op1Reg == 0) return false;
1552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1553 CReg).addReg(Op1Reg);
1555 // The shift instruction uses X86::CL. If we defined a super-register
1556 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1557 if (CReg != X86::CL)
1558 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1559 TII.get(TargetOpcode::KILL), X86::CL)
1560 .addReg(CReg, RegState::Kill);
1562 unsigned ResultReg = createResultReg(RC);
1563 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1565 UpdateValueMap(I, ResultReg);
1569 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1570 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1571 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1572 const static bool S = true; // IsSigned
1573 const static bool U = false; // !IsSigned
1574 const static unsigned Copy = TargetOpcode::COPY;
1575 // For the X86 DIV/IDIV instruction, in most cases the dividend
1576 // (numerator) must be in a specific register pair highreg:lowreg,
1577 // producing the quotient in lowreg and the remainder in highreg.
1578 // For most data types, to set up the instruction, the dividend is
1579 // copied into lowreg, and lowreg is sign-extended or zero-extended
1580 // into highreg. The exception is i8, where the dividend is defined
1581 // as a single register rather than a register pair, and we
1582 // therefore directly sign-extend or zero-extend the dividend into
1583 // lowreg, instead of copying, and ignore the highreg.
1584 const static struct DivRemEntry {
1585 // The following portion depends only on the data type.
1586 const TargetRegisterClass *RC;
1587 unsigned LowInReg; // low part of the register pair
1588 unsigned HighInReg; // high part of the register pair
1589 // The following portion depends on both the data type and the operation.
1590 struct DivRemResult {
1591 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1592 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1593 // highreg, or copying a zero into highreg.
1594 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1595 // zero/sign-extending into lowreg for i8.
1596 unsigned DivRemResultReg; // Register containing the desired result.
1597 bool IsOpSigned; // Whether to use signed or unsigned form.
1598 } ResultTable[NumOps];
1599 } OpTable[NumTypes] = {
1600 { &X86::GR8RegClass, X86::AX, 0, {
1601 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1602 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1603 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1604 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1607 { &X86::GR16RegClass, X86::AX, X86::DX, {
1608 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1609 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1610 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1611 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1614 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1615 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1616 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1617 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1618 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1621 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1622 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1623 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1624 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1625 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1631 if (!isTypeLegal(I->getType(), VT))
1634 unsigned TypeIndex, OpIndex;
1635 switch (VT.SimpleTy) {
1636 default: return false;
1637 case MVT::i8: TypeIndex = 0; break;
1638 case MVT::i16: TypeIndex = 1; break;
1639 case MVT::i32: TypeIndex = 2; break;
1640 case MVT::i64: TypeIndex = 3;
1641 if (!Subtarget->is64Bit())
1646 switch (I->getOpcode()) {
1647 default: llvm_unreachable("Unexpected div/rem opcode");
1648 case Instruction::SDiv: OpIndex = 0; break;
1649 case Instruction::SRem: OpIndex = 1; break;
1650 case Instruction::UDiv: OpIndex = 2; break;
1651 case Instruction::URem: OpIndex = 3; break;
1654 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1655 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1656 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1659 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1663 // Move op0 into low-order input register.
1664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1665 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1666 // Zero-extend or sign-extend into high-order input register.
1667 if (OpEntry.OpSignExtend) {
1668 if (OpEntry.IsOpSigned)
1669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1670 TII.get(OpEntry.OpSignExtend));
1672 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1674 TII.get(X86::MOV32r0), Zero32);
1676 // Copy the zero into the appropriate sub/super/identical physical
1677 // register. Unfortunately the operations needed are not uniform enough to
1678 // fit neatly into the table above.
1679 if (VT.SimpleTy == MVT::i16) {
1680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1681 TII.get(Copy), TypeEntry.HighInReg)
1682 .addReg(Zero32, 0, X86::sub_16bit);
1683 } else if (VT.SimpleTy == MVT::i32) {
1684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1685 TII.get(Copy), TypeEntry.HighInReg)
1687 } else if (VT.SimpleTy == MVT::i64) {
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1689 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1690 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1694 // Generate the DIV/IDIV instruction.
1695 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1696 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1697 // For i8 remainder, we can't reference AH directly, as we'll end
1698 // up with bogus copies like %R9B = COPY %AH. Reference AX
1699 // instead to prevent AH references in a REX instruction.
1701 // The current assumption of the fast register allocator is that isel
1702 // won't generate explicit references to the GPR8_NOREX registers. If
1703 // the allocator and/or the backend get enhanced to be more robust in
1704 // that regard, this can be, and should be, removed.
1705 unsigned ResultReg = 0;
1706 if ((I->getOpcode() == Instruction::SRem ||
1707 I->getOpcode() == Instruction::URem) &&
1708 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1709 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1710 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1712 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1714 // Shift AX right by 8 bits instead of using AH.
1715 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1716 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1718 // Now reference the 8-bit subreg of the result.
1719 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1720 /*Kill=*/true, X86::sub_8bit);
1722 // Copy the result out of the physreg if we haven't already.
1724 ResultReg = createResultReg(TypeEntry.RC);
1725 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1726 .addReg(OpEntry.DivRemResultReg);
1728 UpdateValueMap(I, ResultReg);
1733 /// \brief Emit a conditional move instruction (if the are supported) to lower
1735 bool X86FastISel::X86FastEmitCMoveSelect(const Instruction *I) {
1737 if (!isTypeLegal(I->getType(), RetVT))
1740 // Check if the subtarget supports these instructions.
1741 if (!Subtarget->hasCMov())
1744 // FIXME: Add support for i8.
1746 switch (RetVT.SimpleTy) {
1747 default: return false;
1748 case MVT::i16: Opc = X86::CMOVNE16rr; break;
1749 case MVT::i32: Opc = X86::CMOVNE32rr; break;
1750 case MVT::i64: Opc = X86::CMOVNE64rr; break;
1753 const Value *Cond = I->getOperand(0);
1754 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1755 bool NeedTest = true;
1757 // Optimize conditons coming from a compare if both instructions are in the
1758 // same basic block (values defined in other basic blocks may not have
1759 // initialized registers).
1760 const auto *CI = dyn_cast<CmpInst>(Cond);
1761 if (CI && (CI->getParent() == I->getParent())) {
1762 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1764 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1765 static unsigned SETFOpcTable[2][3] = {
1766 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1767 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1769 unsigned *SETFOpc = nullptr;
1770 switch (Predicate) {
1772 case CmpInst::FCMP_OEQ:
1773 SETFOpc = &SETFOpcTable[0][0];
1774 Predicate = CmpInst::ICMP_NE;
1776 case CmpInst::FCMP_UNE:
1777 SETFOpc = &SETFOpcTable[1][0];
1778 Predicate = CmpInst::ICMP_NE;
1784 std::tie(CC, NeedSwap) = getX86ConditonCode(Predicate);
1785 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1786 Opc = X86::getCMovFromCond(CC, RC->getSize());
1788 const Value *CmpLHS = CI->getOperand(0);
1789 const Value *CmpRHS = CI->getOperand(1);
1791 std::swap(CmpLHS, CmpRHS);
1793 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1794 // Emit a compare of the LHS and RHS, setting the flags.
1795 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
1799 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1800 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1801 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1803 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1805 auto const &II = TII.get(SETFOpc[2]);
1806 if (II.getNumDefs()) {
1807 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1808 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1809 .addReg(FlagReg2).addReg(FlagReg1);
1811 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1812 .addReg(FlagReg2).addReg(FlagReg1);
1816 } else if (auto *EV = dyn_cast<ExtractValueInst>(Cond)) {
1817 bool FoldIntrinsic = false;
1818 if (const auto *II = dyn_cast<IntrinsicInst>(EV->getAggregateOperand())) {
1819 switch (II->getIntrinsicID()) {
1821 case Intrinsic::sadd_with_overflow:
1822 case Intrinsic::uadd_with_overflow:
1823 case Intrinsic::ssub_with_overflow:
1824 case Intrinsic::usub_with_overflow:
1825 case Intrinsic::smul_with_overflow:
1826 case Intrinsic::umul_with_overflow: FoldIntrinsic = true; break;
1829 // Check if both instructions are in the same basic block.
1830 if (FoldIntrinsic && (II->getParent() != I->getParent()))
1831 FoldIntrinsic = false;
1833 // Make sure nothing is in the way
1834 if (FoldIntrinsic) {
1835 BasicBlock::const_iterator Start = I;
1836 BasicBlock::const_iterator End = II;
1837 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
1838 // We only expect extractvalue instructions between the intrinsic and
1840 if (!isa<ExtractValueInst>(Itr)) {
1841 FoldIntrinsic = false;
1845 // Check that the extractvalue operand comes from the intrinsic.
1846 const auto *EVI = cast<ExtractValueInst>(Itr);
1847 if (EVI->getAggregateOperand() != II) {
1848 FoldIntrinsic = false;
1855 if (FoldIntrinsic) {
1857 const IntrinsicInst *II = cast<IntrinsicInst>(EV->getAggregateOperand());
1858 const Function *Callee = II->getCalledFunction();
1860 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
1861 if (!isTypeLegal(RetTy, RetVT))
1864 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1867 // Fake request the condition, otherwise the intrinsic might be completely
1869 unsigned TmpReg = getRegForValue(EV);
1873 switch (II->getIntrinsicID()) {
1874 default: llvm_unreachable("Unexpected intrinsic instruction.");
1875 case Intrinsic::sadd_with_overflow:
1876 case Intrinsic::ssub_with_overflow:
1877 case Intrinsic::smul_with_overflow:
1878 case Intrinsic::umul_with_overflow:
1879 Opc = X86::getCMovFromCond(X86::COND_O, RC->getSize());
1881 case Intrinsic::uadd_with_overflow:
1882 case Intrinsic::usub_with_overflow:
1883 Opc = X86::getCMovFromCond(X86::COND_B, RC->getSize());
1891 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1892 // garbage. Indeed, only the less significant bit is supposed to be
1893 // accurate. If we read more than the lsb, we may see non-zero values
1894 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1895 // the select. This is achieved by performing TEST against 1.
1896 unsigned CondReg = getRegForValue(Cond);
1899 bool CondIsKill = hasTrivialKill(Cond);
1901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1902 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1905 const Value *LHS = I->getOperand(1);
1906 const Value *RHS = I->getOperand(2);
1908 unsigned RHSReg = getRegForValue(RHS);
1909 bool RHSIsKill = hasTrivialKill(RHS);
1911 unsigned LHSReg = getRegForValue(LHS);
1912 bool LHSIsKill = hasTrivialKill(LHS);
1914 if (!LHSReg || !RHSReg)
1917 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1919 UpdateValueMap(I, ResultReg);
1923 /// \brief Emit SSE instructions to lower the select.
1925 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1926 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1927 /// SSE instructions are available.
1928 bool X86FastISel::X86FastEmitSSESelect(const Instruction *I) {
1930 if (!isTypeLegal(I->getType(), RetVT))
1933 // Optimize conditons coming from a compare if both instructions are in the
1934 // same basic block (values defined in other basic blocks may not have
1935 // initialized registers).
1936 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1937 if (!CI || (CI->getParent() != I->getParent()))
1940 if (I->getType() != CI->getOperand(0)->getType() ||
1941 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1942 (Subtarget->hasSSE2() && RetVT == MVT::f64) ))
1945 const Value *CmpLHS = CI->getOperand(0);
1946 const Value *CmpRHS = CI->getOperand(1);
1947 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1949 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1950 // We don't have to materialize a zero constant for this case and can just use
1951 // %x again on the RHS.
1952 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1953 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1954 if (CmpRHSC && CmpRHSC->isNullValue())
1960 std::tie(CC, NeedSwap) = getX86SSECondtionCode(Predicate);
1965 std::swap(CmpLHS, CmpRHS);
1967 static unsigned OpcTable[2][2][4] = {
1968 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1969 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1970 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1971 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1974 bool HasAVX = Subtarget->hasAVX();
1975 unsigned *Opc = nullptr;
1976 switch (RetVT.SimpleTy) {
1977 default: return false;
1978 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1979 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1982 const Value *LHS = I->getOperand(1);
1983 const Value *RHS = I->getOperand(2);
1985 unsigned LHSReg = getRegForValue(LHS);
1986 bool LHSIsKill = hasTrivialKill(LHS);
1988 unsigned RHSReg = getRegForValue(RHS);
1989 bool RHSIsKill = hasTrivialKill(RHS);
1991 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1992 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1994 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1995 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1997 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2000 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2001 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2002 CmpRHSReg, CmpRHSIsKill, CC);
2003 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2005 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2007 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2008 AndReg, /*IsKill=*/true);
2009 UpdateValueMap(I, ResultReg);
2013 bool X86FastISel::X86FastEmitPseudoSelect(const Instruction *I) {
2015 if (!isTypeLegal(I->getType(), RetVT))
2018 // These are pseudo CMOV instructions and will be later expanded into control-
2021 switch (RetVT.SimpleTy) {
2022 default: return false;
2023 case MVT::i8: Opc = X86::CMOV_GR8; break;
2024 case MVT::i16: Opc = X86::CMOV_GR16; break;
2025 case MVT::i32: Opc = X86::CMOV_GR32; break;
2026 case MVT::f32: Opc = X86::CMOV_FR32; break;
2027 case MVT::f64: Opc = X86::CMOV_FR64; break;
2030 const Value *Cond = I->getOperand(0);
2031 X86::CondCode CC = X86::COND_NE;
2033 // Optimize conditons coming from a compare if both instructions are in the
2034 // same basic block (values defined in other basic blocks may not have
2035 // initialized registers).
2036 const auto *CI = dyn_cast<CmpInst>(Cond);
2037 if (CI && (CI->getParent() == I->getParent())) {
2039 std::tie(CC, NeedSwap) = getX86ConditonCode(CI->getPredicate());
2040 if (CC > X86::LAST_VALID_COND)
2043 const Value *CmpLHS = CI->getOperand(0);
2044 const Value *CmpRHS = CI->getOperand(1);
2047 std::swap(CmpLHS, CmpRHS);
2049 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
2050 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT))
2053 unsigned CondReg = getRegForValue(Cond);
2056 bool CondIsKill = hasTrivialKill(Cond);
2057 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2058 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2061 const Value *LHS = I->getOperand(1);
2062 const Value *RHS = I->getOperand(2);
2064 unsigned LHSReg = getRegForValue(LHS);
2065 bool LHSIsKill = hasTrivialKill(LHS);
2067 unsigned RHSReg = getRegForValue(RHS);
2068 bool RHSIsKill = hasTrivialKill(RHS);
2070 if (!LHSReg || !RHSReg)
2073 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2075 unsigned ResultReg =
2076 FastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2077 UpdateValueMap(I, ResultReg);
2081 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2083 if (!isTypeLegal(I->getType(), RetVT))
2086 // Check if we can fold the select.
2087 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2088 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2089 const Value *Opnd = nullptr;
2090 switch (Predicate) {
2092 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2093 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2095 // No need for a select anymore - this is an unconditional move.
2097 unsigned OpReg = getRegForValue(Opnd);
2100 bool OpIsKill = hasTrivialKill(Opnd);
2101 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2102 unsigned ResultReg = createResultReg(RC);
2103 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2104 TII.get(TargetOpcode::COPY), ResultReg)
2105 .addReg(OpReg, getKillRegState(OpIsKill));
2106 UpdateValueMap(I, ResultReg);
2111 // First try to use real conditional move instructions.
2112 if (X86FastEmitCMoveSelect(I))
2115 // Try to use a sequence of SSE instructions to simulate a conditonal move.
2116 if (X86FastEmitSSESelect(I))
2119 // Fall-back to pseudo conditional move instructions, which will be later
2120 // converted to control-flow.
2121 if (X86FastEmitPseudoSelect(I))
2127 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2128 // fpext from float to double.
2129 if (X86ScalarSSEf64 &&
2130 I->getType()->isDoubleTy()) {
2131 const Value *V = I->getOperand(0);
2132 if (V->getType()->isFloatTy()) {
2133 unsigned OpReg = getRegForValue(V);
2134 if (OpReg == 0) return false;
2135 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
2136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2137 TII.get(X86::CVTSS2SDrr), ResultReg)
2139 UpdateValueMap(I, ResultReg);
2147 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2148 if (X86ScalarSSEf64) {
2149 if (I->getType()->isFloatTy()) {
2150 const Value *V = I->getOperand(0);
2151 if (V->getType()->isDoubleTy()) {
2152 unsigned OpReg = getRegForValue(V);
2153 if (OpReg == 0) return false;
2154 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
2155 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2156 TII.get(X86::CVTSD2SSrr), ResultReg)
2158 UpdateValueMap(I, ResultReg);
2167 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2168 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2169 EVT DstVT = TLI.getValueType(I->getType());
2171 // This code only handles truncation to byte.
2172 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2174 if (!TLI.isTypeLegal(SrcVT))
2177 unsigned InputReg = getRegForValue(I->getOperand(0));
2179 // Unhandled operand. Halt "fast" selection and bail.
2182 if (SrcVT == MVT::i8) {
2183 // Truncate from i8 to i1; no code needed.
2184 UpdateValueMap(I, InputReg);
2188 if (!Subtarget->is64Bit()) {
2189 // If we're on x86-32; we can't extract an i8 from a general register.
2190 // First issue a copy to GR16_ABCD or GR32_ABCD.
2191 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
2192 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
2193 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
2194 unsigned CopyReg = createResultReg(CopyRC);
2195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
2196 CopyReg).addReg(InputReg);
2200 // Issue an extract_subreg.
2201 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
2202 InputReg, /*Kill=*/true,
2207 UpdateValueMap(I, ResultReg);
2211 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2212 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2215 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2216 X86AddressMode SrcAM, uint64_t Len) {
2218 // Make sure we don't bloat code by inlining very large memcpy's.
2219 if (!IsMemcpySmall(Len))
2222 bool i64Legal = Subtarget->is64Bit();
2224 // We don't care about alignment here since we just emit integer accesses.
2227 if (Len >= 8 && i64Legal)
2238 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2239 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2240 assert(RV && "Failed to emit load or store??");
2242 unsigned Size = VT.getSizeInBits()/8;
2244 DestAM.Disp += Size;
2251 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
2252 switch (I.getIntrinsicID()) {
2253 case Intrinsic::sadd_with_overflow:
2254 case Intrinsic::uadd_with_overflow:
2255 case Intrinsic::smul_with_overflow:
2256 case Intrinsic::umul_with_overflow:
2263 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
2264 // FIXME: Handle more intrinsics.
2265 switch (I.getIntrinsicID()) {
2266 default: return false;
2267 case Intrinsic::frameaddress: {
2268 Type *RetTy = I.getCalledFunction()->getReturnType();
2271 if (!isTypeLegal(RetTy, VT))
2275 const TargetRegisterClass *RC = nullptr;
2277 switch (VT.SimpleTy) {
2278 default: llvm_unreachable("Invalid result type for frameaddress.");
2279 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2280 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2283 // This needs to be set before we call getFrameRegister, otherwise we get
2284 // the wrong frame register.
2285 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2286 MFI->setFrameAddressIsTaken(true);
2288 const X86RegisterInfo *RegInfo =
2289 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2290 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
2291 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2292 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2293 "Invalid Frame Register!");
2295 // Always make a copy of the frame register to to a vreg first, so that we
2296 // never directly reference the frame register (the TwoAddressInstruction-
2297 // Pass doesn't like that).
2298 unsigned SrcReg = createResultReg(RC);
2299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2300 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2302 // Now recursively load from the frame address.
2303 // movq (%rbp), %rax
2304 // movq (%rax), %rax
2305 // movq (%rax), %rax
2308 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2310 DestReg = createResultReg(RC);
2311 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2312 TII.get(Opc), DestReg), SrcReg);
2316 UpdateValueMap(&I, SrcReg);
2319 case Intrinsic::memcpy: {
2320 const MemCpyInst &MCI = cast<MemCpyInst>(I);
2321 // Don't handle volatile or variable length memcpys.
2322 if (MCI.isVolatile())
2325 if (isa<ConstantInt>(MCI.getLength())) {
2326 // Small memcpy's are common enough that we want to do them
2327 // without a call if possible.
2328 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
2329 if (IsMemcpySmall(Len)) {
2330 X86AddressMode DestAM, SrcAM;
2331 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
2332 !X86SelectAddress(MCI.getRawSource(), SrcAM))
2334 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2339 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2340 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
2343 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
2346 return DoSelectCall(&I, "memcpy");
2348 case Intrinsic::memset: {
2349 const MemSetInst &MSI = cast<MemSetInst>(I);
2351 if (MSI.isVolatile())
2354 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2355 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
2358 if (MSI.getDestAddressSpace() > 255)
2361 return DoSelectCall(&I, "memset");
2363 case Intrinsic::stackprotector: {
2364 // Emit code to store the stack guard onto the stack.
2365 EVT PtrTy = TLI.getPointerTy();
2367 const Value *Op1 = I.getArgOperand(0); // The guard's value.
2368 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
2370 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2372 // Grab the frame index.
2374 if (!X86SelectAddress(Slot, AM)) return false;
2375 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2378 case Intrinsic::dbg_declare: {
2379 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
2381 assert(DI->getAddress() && "Null address should be checked earlier!");
2382 if (!X86SelectAddress(DI->getAddress(), AM))
2384 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2385 // FIXME may need to add RegState::Debug to any registers produced,
2386 // although ESP/EBP should be the only ones at the moment.
2387 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
2388 addImm(0).addMetadata(DI->getVariable());
2391 case Intrinsic::trap: {
2392 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2395 case Intrinsic::sqrt: {
2396 if (!Subtarget->hasSSE1())
2399 Type *RetTy = I.getCalledFunction()->getReturnType();
2402 if (!isTypeLegal(RetTy, VT))
2405 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
2406 // is not generated by FastISel yet.
2407 // FIXME: Update this code once tablegen can handle it.
2408 static const unsigned SqrtOpc[2][2] = {
2409 {X86::SQRTSSr, X86::VSQRTSSr},
2410 {X86::SQRTSDr, X86::VSQRTSDr}
2412 bool HasAVX = Subtarget->hasAVX();
2414 const TargetRegisterClass *RC;
2415 switch (VT.SimpleTy) {
2416 default: return false;
2417 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2418 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2421 const Value *SrcVal = I.getArgOperand(0);
2422 unsigned SrcReg = getRegForValue(SrcVal);
2427 unsigned ImplicitDefReg = 0;
2429 ImplicitDefReg = createResultReg(RC);
2430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2431 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2434 unsigned ResultReg = createResultReg(RC);
2435 MachineInstrBuilder MIB;
2436 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2440 MIB.addReg(ImplicitDefReg);
2444 UpdateValueMap(&I, ResultReg);
2447 case Intrinsic::sadd_with_overflow:
2448 case Intrinsic::uadd_with_overflow:
2449 case Intrinsic::ssub_with_overflow:
2450 case Intrinsic::usub_with_overflow:
2451 case Intrinsic::smul_with_overflow:
2452 case Intrinsic::umul_with_overflow: {
2453 // This implements the basic lowering of the xalu with overflow intrinsics
2454 // into add/sub/mul folowed by either seto or setb.
2455 const Function *Callee = I.getCalledFunction();
2456 auto *Ty = cast<StructType>(Callee->getReturnType());
2457 Type *RetTy = Ty->getTypeAtIndex(0U);
2458 Type *CondTy = Ty->getTypeAtIndex(1);
2461 if (!isTypeLegal(RetTy, VT))
2464 if (VT < MVT::i8 || VT > MVT::i64)
2467 const Value *LHS = I.getArgOperand(0);
2468 const Value *RHS = I.getArgOperand(1);
2470 // Canonicalize immediates to the RHS.
2471 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2472 isCommutativeIntrinsic(I))
2473 std::swap(LHS, RHS);
2475 unsigned BaseOpc, CondOpc;
2476 switch (I.getIntrinsicID()) {
2477 default: llvm_unreachable("Unexpected intrinsic!");
2478 case Intrinsic::sadd_with_overflow:
2479 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2480 case Intrinsic::uadd_with_overflow:
2481 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2482 case Intrinsic::ssub_with_overflow:
2483 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2484 case Intrinsic::usub_with_overflow:
2485 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2486 case Intrinsic::smul_with_overflow:
2487 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
2488 case Intrinsic::umul_with_overflow:
2489 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2492 unsigned LHSReg = getRegForValue(LHS);
2495 bool LHSIsKill = hasTrivialKill(LHS);
2497 unsigned ResultReg = 0;
2498 // Check if we have an immediate version.
2499 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2500 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2507 RHSReg = getRegForValue(RHS);
2510 RHSIsKill = hasTrivialKill(RHS);
2511 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2515 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
2516 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2517 static const unsigned MULOpc[] =
2518 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2519 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2520 // First copy the first operand into RAX, which is an implicit input to
2521 // the X86::MUL*r instruction.
2522 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2523 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2524 .addReg(LHSReg, getKillRegState(LHSIsKill));
2525 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2526 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2532 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2533 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2534 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2537 UpdateValueMap(&I, ResultReg, 2);
2540 case Intrinsic::x86_sse_cvttss2si:
2541 case Intrinsic::x86_sse_cvttss2si64:
2542 case Intrinsic::x86_sse2_cvttsd2si:
2543 case Intrinsic::x86_sse2_cvttsd2si64: {
2545 switch (I.getIntrinsicID()) {
2546 default: llvm_unreachable("Unexpected intrinsic.");
2547 case Intrinsic::x86_sse_cvttss2si:
2548 case Intrinsic::x86_sse_cvttss2si64:
2549 if (!Subtarget->hasSSE1())
2551 IsInputDouble = false;
2553 case Intrinsic::x86_sse2_cvttsd2si:
2554 case Intrinsic::x86_sse2_cvttsd2si64:
2555 if (!Subtarget->hasSSE2())
2557 IsInputDouble = true;
2561 Type *RetTy = I.getCalledFunction()->getReturnType();
2563 if (!isTypeLegal(RetTy, VT))
2566 static const unsigned CvtOpc[2][2][2] = {
2567 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2568 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2569 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2570 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2572 bool HasAVX = Subtarget->hasAVX();
2574 switch (VT.SimpleTy) {
2575 default: llvm_unreachable("Unexpected result type.");
2576 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2577 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2580 // Check if we can fold insertelement instructions into the convert.
2581 const Value *Op = I.getArgOperand(0);
2582 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2583 const Value *Index = IE->getOperand(2);
2584 if (!isa<ConstantInt>(Index))
2586 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2589 Op = IE->getOperand(1);
2592 Op = IE->getOperand(0);
2595 unsigned Reg = getRegForValue(Op);
2599 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2600 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2603 UpdateValueMap(&I, ResultReg);
2609 bool X86FastISel::FastLowerArguments() {
2610 if (!FuncInfo.CanLowerReturn)
2613 const Function *F = FuncInfo.Fn;
2617 CallingConv::ID CC = F->getCallingConv();
2618 if (CC != CallingConv::C)
2621 if (Subtarget->isCallingConvWin64(CC))
2624 if (!Subtarget->is64Bit())
2627 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2628 unsigned GPRCnt = 0;
2629 unsigned FPRCnt = 0;
2631 for (auto const &Arg : F->args()) {
2632 // The first argument is at index 1.
2634 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2635 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2636 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2637 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2640 Type *ArgTy = Arg.getType();
2641 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2644 EVT ArgVT = TLI.getValueType(ArgTy);
2645 if (!ArgVT.isSimple()) return false;
2646 switch (ArgVT.getSimpleVT().SimpleTy) {
2647 default: return false;
2654 if (!Subtarget->hasSSE1())
2667 static const MCPhysReg GPR32ArgRegs[] = {
2668 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2670 static const MCPhysReg GPR64ArgRegs[] = {
2671 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2673 static const MCPhysReg XMMArgRegs[] = {
2674 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2675 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2678 unsigned GPRIdx = 0;
2679 unsigned FPRIdx = 0;
2680 for (auto const &Arg : F->args()) {
2681 MVT VT = TLI.getSimpleValueType(Arg.getType());
2682 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2684 switch (VT.SimpleTy) {
2685 default: llvm_unreachable("Unexpected value type.");
2686 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2687 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2688 case MVT::f32: // fall-through
2689 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2691 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2692 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2693 // Without this, EmitLiveInCopies may eliminate the livein if its only
2694 // use is a bitcast (which isn't turned into an instruction).
2695 unsigned ResultReg = createResultReg(RC);
2696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2697 TII.get(TargetOpcode::COPY), ResultReg)
2698 .addReg(DstReg, getKillRegState(true));
2699 UpdateValueMap(&Arg, ResultReg);
2704 bool X86FastISel::X86SelectCall(const Instruction *I) {
2705 const CallInst *CI = cast<CallInst>(I);
2706 const Value *Callee = CI->getCalledValue();
2708 // Can't handle inline asm yet.
2709 if (isa<InlineAsm>(Callee))
2712 // Handle intrinsic calls.
2713 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2714 return X86VisitIntrinsicCall(*II);
2716 // Allow SelectionDAG isel to handle tail calls.
2717 if (cast<CallInst>(I)->isTailCall())
2720 return DoSelectCall(I, nullptr);
2723 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2724 const ImmutableCallSite &CS) {
2725 if (Subtarget.is64Bit())
2727 if (Subtarget.getTargetTriple().isOSMSVCRT())
2729 CallingConv::ID CC = CS.getCallingConv();
2730 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2732 if (!CS.paramHasAttr(1, Attribute::StructRet))
2734 if (CS.paramHasAttr(1, Attribute::InReg))
2739 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2740 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2741 const CallInst *CI = cast<CallInst>(I);
2742 const Value *Callee = CI->getCalledValue();
2744 // Handle only C and fastcc calling conventions for now.
2745 ImmutableCallSite CS(CI);
2746 CallingConv::ID CC = CS.getCallingConv();
2747 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2748 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2749 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2750 CC != CallingConv::X86_64_SysV)
2753 // fastcc with -tailcallopt is intended to provide a guaranteed
2754 // tail call optimization. Fastisel doesn't know how to do that.
2755 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2758 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2759 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2760 bool isVarArg = FTy->isVarArg();
2762 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2763 // x86-32. Special handling for x86-64 is implemented.
2764 if (isVarArg && isWin64)
2767 // Don't know about inalloca yet.
2768 if (CS.hasInAllocaArgument())
2771 // Fast-isel doesn't know about callee-pop yet.
2772 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2773 TM.Options.GuaranteedTailCallOpt))
2776 // Check whether the function can return without sret-demotion.
2777 SmallVector<ISD::OutputArg, 4> Outs;
2778 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2779 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2780 *FuncInfo.MF, FTy->isVarArg(),
2781 Outs, FTy->getContext());
2782 if (!CanLowerReturn)
2785 // Materialize callee address in a register. FIXME: GV address can be
2786 // handled with a CALLpcrel32 instead.
2787 X86AddressMode CalleeAM;
2788 if (!X86SelectCallAddress(Callee, CalleeAM))
2790 unsigned CalleeOp = 0;
2791 const GlobalValue *GV = nullptr;
2792 if (CalleeAM.GV != nullptr) {
2794 } else if (CalleeAM.Base.Reg != 0) {
2795 CalleeOp = CalleeAM.Base.Reg;
2799 // Deal with call operands first.
2800 SmallVector<const Value *, 8> ArgVals;
2801 SmallVector<unsigned, 8> Args;
2802 SmallVector<MVT, 8> ArgVTs;
2803 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2804 unsigned arg_size = CS.arg_size();
2805 Args.reserve(arg_size);
2806 ArgVals.reserve(arg_size);
2807 ArgVTs.reserve(arg_size);
2808 ArgFlags.reserve(arg_size);
2809 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2811 // If we're lowering a mem intrinsic instead of a regular call, skip the
2812 // last two arguments, which should not passed to the underlying functions.
2813 if (MemIntName && e-i <= 2)
2816 ISD::ArgFlagsTy Flags;
2817 unsigned AttrInd = i - CS.arg_begin() + 1;
2818 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2820 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2823 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2824 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2825 Type *ElementTy = Ty->getElementType();
2826 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2827 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2829 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2831 Flags.setByValSize(FrameSize);
2832 Flags.setByValAlign(FrameAlign);
2833 if (!IsMemcpySmall(FrameSize))
2837 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2839 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2842 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2843 // instruction. This is safe because it is common to all fastisel supported
2844 // calling conventions on x86.
2845 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2846 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2847 CI->getBitWidth() == 16) {
2849 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2851 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2857 // Passing bools around ends up doing a trunc to i1 and passing it.
2858 // Codegen this as an argument + "and 1".
2859 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2860 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2861 ArgVal->hasOneUse()) {
2862 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2863 ArgReg = getRegForValue(ArgVal);
2864 if (ArgReg == 0) return false;
2867 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2869 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2870 ArgVal->hasOneUse(), 1);
2872 ArgReg = getRegForValue(ArgVal);
2875 if (ArgReg == 0) return false;
2877 Type *ArgTy = ArgVal->getType();
2879 if (!isTypeLegal(ArgTy, ArgVT))
2881 if (ArgVT == MVT::x86mmx)
2883 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2884 Flags.setOrigAlign(OriginalAlignment);
2886 Args.push_back(ArgReg);
2887 ArgVals.push_back(ArgVal);
2888 ArgVTs.push_back(ArgVT);
2889 ArgFlags.push_back(Flags);
2892 // Analyze operands of the call, assigning locations to each operand.
2893 SmallVector<CCValAssign, 16> ArgLocs;
2894 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2895 I->getParent()->getContext());
2897 // Allocate shadow area for Win64
2899 CCInfo.AllocateStack(32, 8);
2901 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2903 // Get a count of how many bytes are to be pushed on the stack.
2904 unsigned NumBytes = CCInfo.getNextStackOffset();
2906 // Issue CALLSEQ_START
2907 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2908 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2911 // Process argument: walk the register/memloc assignments, inserting
2913 SmallVector<unsigned, 4> RegArgs;
2914 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2915 CCValAssign &VA = ArgLocs[i];
2916 unsigned Arg = Args[VA.getValNo()];
2917 EVT ArgVT = ArgVTs[VA.getValNo()];
2919 // Promote the value if needed.
2920 switch (VA.getLocInfo()) {
2921 case CCValAssign::Full: break;
2922 case CCValAssign::SExt: {
2923 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2924 "Unexpected extend");
2925 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2927 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2928 ArgVT = VA.getLocVT();
2931 case CCValAssign::ZExt: {
2932 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2933 "Unexpected extend");
2934 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2936 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2937 ArgVT = VA.getLocVT();
2940 case CCValAssign::AExt: {
2941 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2942 "Unexpected extend");
2943 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2946 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2949 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2952 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2953 ArgVT = VA.getLocVT();
2956 case CCValAssign::BCvt: {
2957 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2958 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2959 assert(BC != 0 && "Failed to emit a bitcast!");
2961 ArgVT = VA.getLocVT();
2964 case CCValAssign::VExt:
2965 // VExt has not been implemented, so this should be impossible to reach
2966 // for now. However, fallback to Selection DAG isel once implemented.
2968 case CCValAssign::Indirect:
2969 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2972 case CCValAssign::FPExt:
2973 llvm_unreachable("Unexpected loc info!");
2976 if (VA.isRegLoc()) {
2977 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2978 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2979 RegArgs.push_back(VA.getLocReg());
2981 unsigned LocMemOffset = VA.getLocMemOffset();
2983 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2984 getTargetMachine()->getRegisterInfo());
2985 AM.Base.Reg = RegInfo->getStackRegister();
2986 AM.Disp = LocMemOffset;
2987 const Value *ArgVal = ArgVals[VA.getValNo()];
2988 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2990 if (Flags.isByVal()) {
2991 X86AddressMode SrcAM;
2992 SrcAM.Base.Reg = Arg;
2993 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2994 assert(Res && "memcpy length already checked!"); (void)Res;
2995 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2996 // If this is a really simple value, emit this with the Value* version
2997 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2998 // as it can cause us to reevaluate the argument.
2999 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
3002 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
3008 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3010 if (Subtarget->isPICStyleGOT()) {
3011 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3013 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3016 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
3017 // Count the number of XMM registers allocated.
3018 static const MCPhysReg XMMArgRegs[] = {
3019 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3020 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3022 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
3023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3024 X86::AL).addImm(NumXMMRegs);
3028 MachineInstrBuilder MIB;
3030 // Register-indirect call.
3032 if (Subtarget->is64Bit())
3033 CallOpc = X86::CALL64r;
3035 CallOpc = X86::CALL32r;
3036 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3041 assert(GV && "Not a direct call");
3043 if (Subtarget->is64Bit())
3044 CallOpc = X86::CALL64pcrel32;
3046 CallOpc = X86::CALLpcrel32;
3048 // See if we need any target-specific flags on the GV operand.
3049 unsigned char OpFlags = 0;
3051 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3052 // external symbols most go through the PLT in PIC mode. If the symbol
3053 // has hidden or protected visibility, or if it is static or local, then
3054 // we don't need to use the PLT - we can directly call it.
3055 if (Subtarget->isTargetELF() &&
3056 TM.getRelocationModel() == Reloc::PIC_ &&
3057 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3058 OpFlags = X86II::MO_PLT;
3059 } else if (Subtarget->isPICStyleStubAny() &&
3060 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3061 (!Subtarget->getTargetTriple().isMacOSX() ||
3062 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3063 // PC-relative references to external symbols should go through $stub,
3064 // unless we're building with the leopard linker or later, which
3065 // automatically synthesizes these stubs.
3066 OpFlags = X86II::MO_DARWIN_STUB;
3070 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3072 MIB.addExternalSymbol(MemIntName, OpFlags);
3074 MIB.addGlobalAddress(GV, 0, OpFlags);
3077 // Add a register mask with the call-preserved registers.
3078 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3079 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
3081 // Add an implicit use GOT pointer in EBX.
3082 if (Subtarget->isPICStyleGOT())
3083 MIB.addReg(X86::EBX, RegState::Implicit);
3085 if (Subtarget->is64Bit() && isVarArg && !isWin64)
3086 MIB.addReg(X86::AL, RegState::Implicit);
3088 // Add implicit physical register uses to the call.
3089 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
3090 MIB.addReg(RegArgs[i], RegState::Implicit);
3092 // Issue CALLSEQ_END
3093 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3094 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
3095 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3096 .addImm(NumBytes).addImm(NumBytesCallee);
3098 // Build info for return calling conv lowering code.
3099 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
3100 SmallVector<ISD::InputArg, 32> Ins;
3101 SmallVector<EVT, 4> RetTys;
3102 ComputeValueVTs(TLI, I->getType(), RetTys);
3103 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
3105 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
3106 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
3107 for (unsigned j = 0; j != NumRegs; ++j) {
3108 ISD::InputArg MyFlags;
3109 MyFlags.VT = RegisterVT;
3110 MyFlags.Used = !CS.getInstruction()->use_empty();
3111 if (CS.paramHasAttr(0, Attribute::SExt))
3112 MyFlags.Flags.setSExt();
3113 if (CS.paramHasAttr(0, Attribute::ZExt))
3114 MyFlags.Flags.setZExt();
3115 if (CS.paramHasAttr(0, Attribute::InReg))
3116 MyFlags.Flags.setInReg();
3117 Ins.push_back(MyFlags);
3121 // Now handle call return values.
3122 SmallVector<unsigned, 4> UsedRegs;
3123 SmallVector<CCValAssign, 16> RVLocs;
3124 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
3125 I->getParent()->getContext());
3126 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
3127 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3128 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3129 EVT CopyVT = RVLocs[i].getValVT();
3130 unsigned CopyReg = ResultReg + i;
3132 // If this is a call to a function that returns an fp value on the x87 fp
3133 // stack, but where we prefer to use the value in xmm registers, copy it
3134 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
3135 if ((RVLocs[i].getLocReg() == X86::ST0 ||
3136 RVLocs[i].getLocReg() == X86::ST1)) {
3137 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
3139 CopyReg = createResultReg(&X86::RFP80RegClass);
3141 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3142 TII.get(X86::FpPOP_RETVAL), CopyReg);
3144 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3145 TII.get(TargetOpcode::COPY),
3146 CopyReg).addReg(RVLocs[i].getLocReg());
3147 UsedRegs.push_back(RVLocs[i].getLocReg());
3150 if (CopyVT != RVLocs[i].getValVT()) {
3151 // Round the F80 the right size, which also moves to the appropriate xmm
3152 // register. This is accomplished by storing the F80 value in memory and
3153 // then loading it back. Ewww...
3154 EVT ResVT = RVLocs[i].getValVT();
3155 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3156 unsigned MemSize = ResVT.getSizeInBits()/8;
3157 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3158 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3161 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3162 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3163 TII.get(Opc), ResultReg + i), FI);
3168 UpdateValueMap(I, ResultReg, RVLocs.size());
3170 // Set all unused physreg defs as dead.
3171 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
3178 X86FastISel::TargetSelectInstruction(const Instruction *I) {
3179 switch (I->getOpcode()) {
3181 case Instruction::Load:
3182 return X86SelectLoad(I);
3183 case Instruction::Store:
3184 return X86SelectStore(I);
3185 case Instruction::Ret:
3186 return X86SelectRet(I);
3187 case Instruction::ICmp:
3188 case Instruction::FCmp:
3189 return X86SelectCmp(I);
3190 case Instruction::ZExt:
3191 return X86SelectZExt(I);
3192 case Instruction::Br:
3193 return X86SelectBranch(I);
3194 case Instruction::Call:
3195 return X86SelectCall(I);
3196 case Instruction::LShr:
3197 case Instruction::AShr:
3198 case Instruction::Shl:
3199 return X86SelectShift(I);
3200 case Instruction::SDiv:
3201 case Instruction::UDiv:
3202 case Instruction::SRem:
3203 case Instruction::URem:
3204 return X86SelectDivRem(I);
3205 case Instruction::Select:
3206 return X86SelectSelect(I);
3207 case Instruction::Trunc:
3208 return X86SelectTrunc(I);
3209 case Instruction::FPExt:
3210 return X86SelectFPExt(I);
3211 case Instruction::FPTrunc:
3212 return X86SelectFPTrunc(I);
3213 case Instruction::IntToPtr: // Deliberate fall-through.
3214 case Instruction::PtrToInt: {
3215 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3216 EVT DstVT = TLI.getValueType(I->getType());
3217 if (DstVT.bitsGT(SrcVT))
3218 return X86SelectZExt(I);
3219 if (DstVT.bitsLT(SrcVT))
3220 return X86SelectTrunc(I);
3221 unsigned Reg = getRegForValue(I->getOperand(0));
3222 if (Reg == 0) return false;
3223 UpdateValueMap(I, Reg);
3231 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
3233 if (!isTypeLegal(C->getType(), VT))
3236 // Can't handle alternate code models yet.
3237 if (TM.getCodeModel() != CodeModel::Small)
3240 // Get opcode and regclass of the output for the given load instruction.
3242 const TargetRegisterClass *RC = nullptr;
3243 switch (VT.SimpleTy) {
3247 RC = &X86::GR8RegClass;
3251 RC = &X86::GR16RegClass;
3255 RC = &X86::GR32RegClass;
3258 // Must be in x86-64 mode.
3260 RC = &X86::GR64RegClass;
3263 if (X86ScalarSSEf32) {
3264 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3265 RC = &X86::FR32RegClass;
3267 Opc = X86::LD_Fp32m;
3268 RC = &X86::RFP32RegClass;
3272 if (X86ScalarSSEf64) {
3273 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3274 RC = &X86::FR64RegClass;
3276 Opc = X86::LD_Fp64m;
3277 RC = &X86::RFP64RegClass;
3281 // No f80 support yet.
3285 // Materialize addresses with LEA/MOV instructions.
3286 if (isa<GlobalValue>(C)) {
3288 if (X86SelectAddress(C, AM)) {
3289 // If the expression is just a basereg, then we're done, otherwise we need
3291 if (AM.BaseType == X86AddressMode::RegBase &&
3292 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3295 unsigned ResultReg = createResultReg(RC);
3296 if (TM.getRelocationModel() == Reloc::Static &&
3297 TLI.getPointerTy() == MVT::i64) {
3298 // The displacement code be more than 32 bits away so we need to use
3299 // an instruction with a 64 bit immediate
3301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3302 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
3304 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
3305 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3306 TII.get(Opc), ResultReg), AM);
3313 // MachineConstantPool wants an explicit alignment.
3314 unsigned Align = DL.getPrefTypeAlignment(C->getType());
3316 // Alignment of vector types. FIXME!
3317 Align = DL.getTypeAllocSize(C->getType());
3320 // x86-32 PIC requires a PIC base register for constant pools.
3321 unsigned PICBase = 0;
3322 unsigned char OpFlag = 0;
3323 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3324 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3325 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3326 } else if (Subtarget->isPICStyleGOT()) {
3327 OpFlag = X86II::MO_GOTOFF;
3328 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3329 } else if (Subtarget->isPICStyleRIPRel() &&
3330 TM.getCodeModel() == CodeModel::Small) {
3334 // Create the load from the constant pool.
3335 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
3336 unsigned ResultReg = createResultReg(RC);
3337 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3338 TII.get(Opc), ResultReg),
3339 MCPOffset, PICBase, OpFlag);
3344 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
3345 // Fail on dynamic allocas. At this point, getRegForValue has already
3346 // checked its CSE maps, so if we're here trying to handle a dynamic
3347 // alloca, we're not going to succeed. X86SelectAddress has a
3348 // check for dynamic allocas, because it's called directly from
3349 // various places, but TargetMaterializeAlloca also needs a check
3350 // in order to avoid recursion between getRegForValue,
3351 // X86SelectAddrss, and TargetMaterializeAlloca.
3352 if (!FuncInfo.StaticAllocaMap.count(C))
3354 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3357 if (!X86SelectAddress(C, AM))
3359 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
3360 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3361 unsigned ResultReg = createResultReg(RC);
3362 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3363 TII.get(Opc), ResultReg), AM);
3367 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
3369 if (!isTypeLegal(CF->getType(), VT))
3372 // Get opcode and regclass for the given zero.
3374 const TargetRegisterClass *RC = nullptr;
3375 switch (VT.SimpleTy) {
3378 if (X86ScalarSSEf32) {
3379 Opc = X86::FsFLD0SS;
3380 RC = &X86::FR32RegClass;
3382 Opc = X86::LD_Fp032;
3383 RC = &X86::RFP32RegClass;
3387 if (X86ScalarSSEf64) {
3388 Opc = X86::FsFLD0SD;
3389 RC = &X86::FR64RegClass;
3391 Opc = X86::LD_Fp064;
3392 RC = &X86::RFP64RegClass;
3396 // No f80 support yet.
3400 unsigned ResultReg = createResultReg(RC);
3401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3406 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3407 const LoadInst *LI) {
3408 const Value *Ptr = LI->getPointerOperand();
3410 if (!X86SelectAddress(Ptr, AM))
3413 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
3415 unsigned Size = DL.getTypeAllocSize(LI->getType());
3416 unsigned Alignment = LI->getAlignment();
3418 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3419 Alignment = DL.getABITypeAlignment(LI->getType());
3421 SmallVector<MachineOperand, 8> AddrOps;
3422 AM.getFullAddress(AddrOps);
3424 MachineInstr *Result =
3425 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
3429 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3430 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3431 MI->eraseFromParent();
3437 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3438 const TargetLibraryInfo *libInfo) {
3439 return new X86FastISel(funcInfo, libInfo);