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 X86SelectSelect(const Instruction *I);
116 bool X86SelectTrunc(const Instruction *I);
118 bool X86SelectFPExt(const Instruction *I);
119 bool X86SelectFPTrunc(const Instruction *I);
121 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
122 bool X86SelectCall(const Instruction *I);
124 bool DoSelectCall(const Instruction *I, const char *MemIntName);
126 const X86InstrInfo *getInstrInfo() const {
127 return getTargetMachine()->getInstrInfo();
129 const X86TargetMachine *getTargetMachine() const {
130 return static_cast<const X86TargetMachine *>(&TM);
133 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
135 unsigned TargetMaterializeConstant(const Constant *C) override;
137 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
139 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
141 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
142 /// computed in an SSE register, not on the X87 floating point stack.
143 bool isScalarFPTypeInSSEReg(EVT VT) const {
144 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
145 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
148 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
150 bool IsMemcpySmall(uint64_t Len);
152 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
153 X86AddressMode SrcAM, uint64_t Len);
156 } // end anonymous namespace.
158 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) {
159 // If both operands are the same, then try to optimize or fold the cmp.
160 CmpInst::Predicate Predicate = CI->getPredicate();
161 if (CI->getOperand(0) != CI->getOperand(1))
165 default: llvm_unreachable("Invalid predicate!");
166 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
167 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
168 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
169 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
170 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
171 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
172 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
173 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
174 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
175 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
176 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
177 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
178 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
179 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
180 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
181 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
183 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
184 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
185 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
186 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
187 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
188 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
189 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
190 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
191 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
192 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
198 static std::pair<X86::CondCode, bool>
199 getX86ConditonCode(CmpInst::Predicate Predicate) {
200 X86::CondCode CC = X86::COND_INVALID;
201 bool NeedSwap = false;
204 // Floating-point Predicates
205 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
206 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
207 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
208 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
209 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
210 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
211 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
212 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
213 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
214 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
215 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
216 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
217 case CmpInst::FCMP_OEQ: // fall-through
218 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
220 // Integer Predicates
221 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
222 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
223 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
224 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
225 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
226 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
227 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
228 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
229 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
230 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
233 return std::make_pair(CC, NeedSwap);
236 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
237 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
238 if (evt == MVT::Other || !evt.isSimple())
239 // Unhandled type. Halt "fast" selection and bail.
242 VT = evt.getSimpleVT();
243 // For now, require SSE/SSE2 for performing floating-point operations,
244 // since x87 requires additional work.
245 if (VT == MVT::f64 && !X86ScalarSSEf64)
247 if (VT == MVT::f32 && !X86ScalarSSEf32)
249 // Similarly, no f80 support yet.
252 // We only handle legal types. For example, on x86-32 the instruction
253 // selector contains all of the 64-bit instructions from x86-64,
254 // under the assumption that i64 won't be used if the target doesn't
256 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
259 #include "X86GenCallingConv.inc"
261 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
262 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
263 /// Return true and the result register by reference if it is possible.
264 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
265 MachineMemOperand *MMO, unsigned &ResultReg) {
266 // Get opcode and regclass of the output for the given load instruction.
268 const TargetRegisterClass *RC = nullptr;
269 switch (VT.getSimpleVT().SimpleTy) {
270 default: return false;
274 RC = &X86::GR8RegClass;
278 RC = &X86::GR16RegClass;
282 RC = &X86::GR32RegClass;
285 // Must be in x86-64 mode.
287 RC = &X86::GR64RegClass;
290 if (X86ScalarSSEf32) {
291 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
292 RC = &X86::FR32RegClass;
295 RC = &X86::RFP32RegClass;
299 if (X86ScalarSSEf64) {
300 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
301 RC = &X86::FR64RegClass;
304 RC = &X86::RFP64RegClass;
308 // No f80 support yet.
312 ResultReg = createResultReg(RC);
313 MachineInstrBuilder MIB =
314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
315 addFullAddress(MIB, AM);
317 MIB->addMemOperand(*FuncInfo.MF, MMO);
321 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
322 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
323 /// and a displacement offset, or a GlobalAddress,
324 /// i.e. V. Return true if it is possible.
325 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
326 const X86AddressMode &AM,
327 MachineMemOperand *MMO, bool Aligned) {
328 // Get opcode and regclass of the output for the given store instruction.
330 switch (VT.getSimpleVT().SimpleTy) {
331 case MVT::f80: // No f80 support yet.
332 default: return false;
334 // Mask out all but lowest bit.
335 unsigned AndResult = createResultReg(&X86::GR8RegClass);
336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
337 TII.get(X86::AND8ri), AndResult)
338 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
341 // FALLTHROUGH, handling i1 as i8.
342 case MVT::i8: Opc = X86::MOV8mr; break;
343 case MVT::i16: Opc = X86::MOV16mr; break;
344 case MVT::i32: Opc = X86::MOV32mr; break;
345 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
347 Opc = X86ScalarSSEf32 ?
348 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
351 Opc = X86ScalarSSEf64 ?
352 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
356 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
358 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
362 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
364 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
371 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
373 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
377 MachineInstrBuilder MIB =
378 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
379 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
381 MIB->addMemOperand(*FuncInfo.MF, MMO);
386 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
387 const X86AddressMode &AM,
388 MachineMemOperand *MMO, bool Aligned) {
389 // Handle 'null' like i32/i64 0.
390 if (isa<ConstantPointerNull>(Val))
391 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
393 // If this is a store of a simple constant, fold the constant into the store.
394 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
397 switch (VT.getSimpleVT().SimpleTy) {
399 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
400 case MVT::i8: Opc = X86::MOV8mi; break;
401 case MVT::i16: Opc = X86::MOV16mi; break;
402 case MVT::i32: Opc = X86::MOV32mi; break;
404 // Must be a 32-bit sign extended value.
405 if (isInt<32>(CI->getSExtValue()))
406 Opc = X86::MOV64mi32;
411 MachineInstrBuilder MIB =
412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
413 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
414 : CI->getZExtValue());
416 MIB->addMemOperand(*FuncInfo.MF, MMO);
421 unsigned ValReg = getRegForValue(Val);
425 bool ValKill = hasTrivialKill(Val);
426 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
429 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
430 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
431 /// ISD::SIGN_EXTEND).
432 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
433 unsigned Src, EVT SrcVT,
434 unsigned &ResultReg) {
435 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
436 Src, /*TODO: Kill=*/false);
444 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
445 // Handle constant address.
446 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
447 // Can't handle alternate code models yet.
448 if (TM.getCodeModel() != CodeModel::Small)
451 // Can't handle TLS yet.
452 if (GV->isThreadLocal())
455 // RIP-relative addresses can't have additional register operands, so if
456 // we've already folded stuff into the addressing mode, just force the
457 // global value into its own register, which we can use as the basereg.
458 if (!Subtarget->isPICStyleRIPRel() ||
459 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
460 // Okay, we've committed to selecting this global. Set up the address.
463 // Allow the subtarget to classify the global.
464 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
466 // If this reference is relative to the pic base, set it now.
467 if (isGlobalRelativeToPICBase(GVFlags)) {
468 // FIXME: How do we know Base.Reg is free??
469 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
472 // Unless the ABI requires an extra load, return a direct reference to
474 if (!isGlobalStubReference(GVFlags)) {
475 if (Subtarget->isPICStyleRIPRel()) {
476 // Use rip-relative addressing if we can. Above we verified that the
477 // base and index registers are unused.
478 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
479 AM.Base.Reg = X86::RIP;
481 AM.GVOpFlags = GVFlags;
485 // Ok, we need to do a load from a stub. If we've already loaded from
486 // this stub, reuse the loaded pointer, otherwise emit the load now.
487 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
489 if (I != LocalValueMap.end() && I->second != 0) {
492 // Issue load from stub.
494 const TargetRegisterClass *RC = nullptr;
495 X86AddressMode StubAM;
496 StubAM.Base.Reg = AM.Base.Reg;
498 StubAM.GVOpFlags = GVFlags;
500 // Prepare for inserting code in the local-value area.
501 SavePoint SaveInsertPt = enterLocalValueArea();
503 if (TLI.getPointerTy() == MVT::i64) {
505 RC = &X86::GR64RegClass;
507 if (Subtarget->isPICStyleRIPRel())
508 StubAM.Base.Reg = X86::RIP;
511 RC = &X86::GR32RegClass;
514 LoadReg = createResultReg(RC);
515 MachineInstrBuilder LoadMI =
516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
517 addFullAddress(LoadMI, StubAM);
519 // Ok, back to normal mode.
520 leaveLocalValueArea(SaveInsertPt);
522 // Prevent loading GV stub multiple times in same MBB.
523 LocalValueMap[V] = LoadReg;
526 // Now construct the final address. Note that the Disp, Scale,
527 // and Index values may already be set here.
528 AM.Base.Reg = LoadReg;
534 // If all else fails, try to materialize the value in a register.
535 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
536 if (AM.Base.Reg == 0) {
537 AM.Base.Reg = getRegForValue(V);
538 return AM.Base.Reg != 0;
540 if (AM.IndexReg == 0) {
541 assert(AM.Scale == 1 && "Scale with no index!");
542 AM.IndexReg = getRegForValue(V);
543 return AM.IndexReg != 0;
550 /// X86SelectAddress - Attempt to fill in an address from the given value.
552 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
553 SmallVector<const Value *, 32> GEPs;
555 const User *U = nullptr;
556 unsigned Opcode = Instruction::UserOp1;
557 if (const Instruction *I = dyn_cast<Instruction>(V)) {
558 // Don't walk into other basic blocks; it's possible we haven't
559 // visited them yet, so the instructions may not yet be assigned
560 // virtual registers.
561 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
562 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
563 Opcode = I->getOpcode();
566 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
567 Opcode = C->getOpcode();
571 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
572 if (Ty->getAddressSpace() > 255)
573 // Fast instruction selection doesn't support the special
579 case Instruction::BitCast:
580 // Look past bitcasts.
581 return X86SelectAddress(U->getOperand(0), AM);
583 case Instruction::IntToPtr:
584 // Look past no-op inttoptrs.
585 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
586 return X86SelectAddress(U->getOperand(0), AM);
589 case Instruction::PtrToInt:
590 // Look past no-op ptrtoints.
591 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
592 return X86SelectAddress(U->getOperand(0), AM);
595 case Instruction::Alloca: {
596 // Do static allocas.
597 const AllocaInst *A = cast<AllocaInst>(V);
598 DenseMap<const AllocaInst*, int>::iterator SI =
599 FuncInfo.StaticAllocaMap.find(A);
600 if (SI != FuncInfo.StaticAllocaMap.end()) {
601 AM.BaseType = X86AddressMode::FrameIndexBase;
602 AM.Base.FrameIndex = SI->second;
608 case Instruction::Add: {
609 // Adds of constants are common and easy enough.
610 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
611 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
612 // They have to fit in the 32-bit signed displacement field though.
613 if (isInt<32>(Disp)) {
614 AM.Disp = (uint32_t)Disp;
615 return X86SelectAddress(U->getOperand(0), AM);
621 case Instruction::GetElementPtr: {
622 X86AddressMode SavedAM = AM;
624 // Pattern-match simple GEPs.
625 uint64_t Disp = (int32_t)AM.Disp;
626 unsigned IndexReg = AM.IndexReg;
627 unsigned Scale = AM.Scale;
628 gep_type_iterator GTI = gep_type_begin(U);
629 // Iterate through the indices, folding what we can. Constants can be
630 // folded, and one dynamic index can be handled, if the scale is supported.
631 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
632 i != e; ++i, ++GTI) {
633 const Value *Op = *i;
634 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
635 const StructLayout *SL = DL.getStructLayout(STy);
636 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
640 // A array/variable index is always of the form i*S where S is the
641 // constant scale size. See if we can push the scale into immediates.
642 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
644 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
645 // Constant-offset addressing.
646 Disp += CI->getSExtValue() * S;
649 if (canFoldAddIntoGEP(U, Op)) {
650 // A compatible add with a constant operand. Fold the constant.
652 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
653 Disp += CI->getSExtValue() * S;
654 // Iterate on the other operand.
655 Op = cast<AddOperator>(Op)->getOperand(0);
659 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
660 (S == 1 || S == 2 || S == 4 || S == 8)) {
661 // Scaled-index addressing.
663 IndexReg = getRegForGEPIndex(Op).first;
669 goto unsupported_gep;
673 // Check for displacement overflow.
674 if (!isInt<32>(Disp))
677 AM.IndexReg = IndexReg;
679 AM.Disp = (uint32_t)Disp;
682 if (const GetElementPtrInst *GEP =
683 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
684 // Ok, the GEP indices were covered by constant-offset and scaled-index
685 // addressing. Update the address state and move on to examining the base.
688 } else if (X86SelectAddress(U->getOperand(0), AM)) {
692 // If we couldn't merge the gep value into this addr mode, revert back to
693 // our address and just match the value instead of completely failing.
696 for (SmallVectorImpl<const Value *>::reverse_iterator
697 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
698 if (handleConstantAddresses(*I, AM))
703 // Ok, the GEP indices weren't all covered.
708 return handleConstantAddresses(V, AM);
711 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
713 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
714 const User *U = nullptr;
715 unsigned Opcode = Instruction::UserOp1;
716 const Instruction *I = dyn_cast<Instruction>(V);
717 // Record if the value is defined in the same basic block.
719 // This information is crucial to know whether or not folding an
721 // Indeed, FastISel generates or reuses a virtual register for all
722 // operands of all instructions it selects. Obviously, the definition and
723 // its uses must use the same virtual register otherwise the produced
724 // code is incorrect.
725 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
726 // registers for values that are alive across basic blocks. This ensures
727 // that the values are consistently set between across basic block, even
728 // if different instruction selection mechanisms are used (e.g., a mix of
729 // SDISel and FastISel).
730 // For values local to a basic block, the instruction selection process
731 // generates these virtual registers with whatever method is appropriate
732 // for its needs. In particular, FastISel and SDISel do not share the way
733 // local virtual registers are set.
734 // Therefore, this is impossible (or at least unsafe) to share values
735 // between basic blocks unless they use the same instruction selection
736 // method, which is not guarantee for X86.
737 // Moreover, things like hasOneUse could not be used accurately, if we
738 // allow to reference values across basic blocks whereas they are not
739 // alive across basic blocks initially.
742 Opcode = I->getOpcode();
744 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
745 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
746 Opcode = C->getOpcode();
752 case Instruction::BitCast:
753 // Look past bitcasts if its operand is in the same BB.
755 return X86SelectCallAddress(U->getOperand(0), AM);
758 case Instruction::IntToPtr:
759 // Look past no-op inttoptrs if its operand is in the same BB.
761 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
762 return X86SelectCallAddress(U->getOperand(0), AM);
765 case Instruction::PtrToInt:
766 // Look past no-op ptrtoints if its operand is in the same BB.
768 TLI.getValueType(U->getType()) == TLI.getPointerTy())
769 return X86SelectCallAddress(U->getOperand(0), AM);
773 // Handle constant address.
774 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
775 // Can't handle alternate code models yet.
776 if (TM.getCodeModel() != CodeModel::Small)
779 // RIP-relative addresses can't have additional register operands.
780 if (Subtarget->isPICStyleRIPRel() &&
781 (AM.Base.Reg != 0 || AM.IndexReg != 0))
784 // Can't handle DbgLocLImport.
785 if (GV->hasDLLImportStorageClass())
789 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
790 if (GVar->isThreadLocal())
793 // Okay, we've committed to selecting this global. Set up the basic address.
796 // No ABI requires an extra load for anything other than DLLImport, which
797 // we rejected above. Return a direct reference to the global.
798 if (Subtarget->isPICStyleRIPRel()) {
799 // Use rip-relative addressing if we can. Above we verified that the
800 // base and index registers are unused.
801 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
802 AM.Base.Reg = X86::RIP;
803 } else if (Subtarget->isPICStyleStubPIC()) {
804 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
805 } else if (Subtarget->isPICStyleGOT()) {
806 AM.GVOpFlags = X86II::MO_GOTOFF;
812 // If all else fails, try to materialize the value in a register.
813 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
814 if (AM.Base.Reg == 0) {
815 AM.Base.Reg = getRegForValue(V);
816 return AM.Base.Reg != 0;
818 if (AM.IndexReg == 0) {
819 assert(AM.Scale == 1 && "Scale with no index!");
820 AM.IndexReg = getRegForValue(V);
821 return AM.IndexReg != 0;
829 /// X86SelectStore - Select and emit code to implement store instructions.
830 bool X86FastISel::X86SelectStore(const Instruction *I) {
831 // Atomic stores need special handling.
832 const StoreInst *S = cast<StoreInst>(I);
837 const Value *Val = S->getValueOperand();
838 const Value *Ptr = S->getPointerOperand();
841 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
844 unsigned Alignment = S->getAlignment();
845 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
846 if (Alignment == 0) // Ensure that codegen never sees alignment 0
847 Alignment = ABIAlignment;
848 bool Aligned = Alignment >= ABIAlignment;
851 if (!X86SelectAddress(Ptr, AM))
854 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
857 /// X86SelectRet - Select and emit code to implement ret instructions.
858 bool X86FastISel::X86SelectRet(const Instruction *I) {
859 const ReturnInst *Ret = cast<ReturnInst>(I);
860 const Function &F = *I->getParent()->getParent();
861 const X86MachineFunctionInfo *X86MFInfo =
862 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
864 if (!FuncInfo.CanLowerReturn)
867 CallingConv::ID CC = F.getCallingConv();
868 if (CC != CallingConv::C &&
869 CC != CallingConv::Fast &&
870 CC != CallingConv::X86_FastCall &&
871 CC != CallingConv::X86_64_SysV)
874 if (Subtarget->isCallingConvWin64(CC))
877 // Don't handle popping bytes on return for now.
878 if (X86MFInfo->getBytesToPopOnReturn() != 0)
881 // fastcc with -tailcallopt is intended to provide a guaranteed
882 // tail call optimization. Fastisel doesn't know how to do that.
883 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
886 // Let SDISel handle vararg functions.
890 // Build a list of return value registers.
891 SmallVector<unsigned, 4> RetRegs;
893 if (Ret->getNumOperands() > 0) {
894 SmallVector<ISD::OutputArg, 4> Outs;
895 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
897 // Analyze operands of the call, assigning locations to each operand.
898 SmallVector<CCValAssign, 16> ValLocs;
899 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
901 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
903 const Value *RV = Ret->getOperand(0);
904 unsigned Reg = getRegForValue(RV);
908 // Only handle a single return value for now.
909 if (ValLocs.size() != 1)
912 CCValAssign &VA = ValLocs[0];
914 // Don't bother handling odd stuff for now.
915 if (VA.getLocInfo() != CCValAssign::Full)
917 // Only handle register returns for now.
921 // The calling-convention tables for x87 returns don't tell
923 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
926 unsigned SrcReg = Reg + VA.getValNo();
927 EVT SrcVT = TLI.getValueType(RV->getType());
928 EVT DstVT = VA.getValVT();
929 // Special handling for extended integers.
930 if (SrcVT != DstVT) {
931 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
934 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
937 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
939 if (SrcVT == MVT::i1) {
940 if (Outs[0].Flags.isSExt())
942 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
945 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
947 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
948 SrcReg, /*TODO: Kill=*/false);
952 unsigned DstReg = VA.getLocReg();
953 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
954 // Avoid a cross-class copy. This is very unlikely.
955 if (!SrcRC->contains(DstReg))
957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
958 DstReg).addReg(SrcReg);
960 // Add register to return instruction.
961 RetRegs.push_back(VA.getLocReg());
964 // The x86-64 ABI for returning structs by value requires that we copy
965 // the sret argument into %rax for the return. We saved the argument into
966 // a virtual register in the entry block, so now we copy the value out
967 // and into %rax. We also do the same with %eax for Win32.
968 if (F.hasStructRetAttr() &&
969 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
970 unsigned Reg = X86MFInfo->getSRetReturnReg();
972 "SRetReturnReg should have been set in LowerFormalArguments()!");
973 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
974 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
976 RetRegs.push_back(RetReg);
980 MachineInstrBuilder MIB =
981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
982 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
983 MIB.addReg(RetRegs[i], RegState::Implicit);
987 /// X86SelectLoad - Select and emit code to implement load instructions.
989 bool X86FastISel::X86SelectLoad(const Instruction *I) {
990 const LoadInst *LI = cast<LoadInst>(I);
992 // Atomic loads need special handling.
997 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1000 const Value *Ptr = LI->getPointerOperand();
1003 if (!X86SelectAddress(Ptr, AM))
1006 unsigned ResultReg = 0;
1007 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1010 UpdateValueMap(I, ResultReg);
1014 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1015 bool HasAVX = Subtarget->hasAVX();
1016 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1017 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1019 switch (VT.getSimpleVT().SimpleTy) {
1021 case MVT::i8: return X86::CMP8rr;
1022 case MVT::i16: return X86::CMP16rr;
1023 case MVT::i32: return X86::CMP32rr;
1024 case MVT::i64: return X86::CMP64rr;
1026 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1028 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1032 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1033 /// of the comparison, return an opcode that works for the compare (e.g.
1034 /// CMP32ri) otherwise return 0.
1035 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1036 switch (VT.getSimpleVT().SimpleTy) {
1037 // Otherwise, we can't fold the immediate into this comparison.
1039 case MVT::i8: return X86::CMP8ri;
1040 case MVT::i16: return X86::CMP16ri;
1041 case MVT::i32: return X86::CMP32ri;
1043 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1045 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1046 return X86::CMP64ri32;
1051 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1053 unsigned Op0Reg = getRegForValue(Op0);
1054 if (Op0Reg == 0) return false;
1056 // Handle 'null' like i32/i64 0.
1057 if (isa<ConstantPointerNull>(Op1))
1058 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1060 // We have two options: compare with register or immediate. If the RHS of
1061 // the compare is an immediate that we can fold into this compare, use
1062 // CMPri, otherwise use CMPrr.
1063 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1064 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1067 .addImm(Op1C->getSExtValue());
1072 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1073 if (CompareOpc == 0) return false;
1075 unsigned Op1Reg = getRegForValue(Op1);
1076 if (Op1Reg == 0) return false;
1077 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1084 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1085 const CmpInst *CI = cast<CmpInst>(I);
1088 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1091 // Try to optimize or fold the cmp.
1092 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1093 unsigned ResultReg = 0;
1094 switch (Predicate) {
1096 case CmpInst::FCMP_FALSE: {
1097 ResultReg = createResultReg(&X86::GR32RegClass);
1098 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1100 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1106 case CmpInst::FCMP_TRUE: {
1107 ResultReg = createResultReg(&X86::GR8RegClass);
1108 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1109 ResultReg).addImm(1);
1115 UpdateValueMap(I, ResultReg);
1119 const Value *LHS = CI->getOperand(0);
1120 const Value *RHS = CI->getOperand(1);
1122 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1123 // We don't have to materialize a zero constant for this case and can just use
1124 // %x again on the RHS.
1125 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1126 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1127 if (RHSC && RHSC->isNullValue())
1131 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1132 static unsigned SETFOpcTable[2][3] = {
1133 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1134 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1136 unsigned *SETFOpc = nullptr;
1137 switch (Predicate) {
1139 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1140 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1143 ResultReg = createResultReg(&X86::GR8RegClass);
1145 if (!X86FastEmitCompare(LHS, RHS, VT))
1148 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1149 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1150 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1152 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1154 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1155 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1156 UpdateValueMap(I, ResultReg);
1162 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1163 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1164 unsigned Opc = X86::getSETFromCond(CC);
1167 std::swap(LHS, RHS);
1169 // Emit a compare of LHS/RHS.
1170 if (!X86FastEmitCompare(LHS, RHS, VT))
1173 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1174 UpdateValueMap(I, ResultReg);
1178 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1179 EVT DstVT = TLI.getValueType(I->getType());
1180 if (!TLI.isTypeLegal(DstVT))
1183 unsigned ResultReg = getRegForValue(I->getOperand(0));
1187 // Handle zero-extension from i1 to i8, which is common.
1188 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1189 if (SrcVT.SimpleTy == MVT::i1) {
1190 // Set the high bits to zero.
1191 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1198 if (DstVT == MVT::i64) {
1199 // Handle extension to 64-bits via sub-register shenanigans.
1202 switch (SrcVT.SimpleTy) {
1203 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1204 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1205 case MVT::i32: MovInst = X86::MOV32rr; break;
1206 default: llvm_unreachable("Unexpected zext to i64 source type");
1209 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1210 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1213 ResultReg = createResultReg(&X86::GR64RegClass);
1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1216 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1217 } else if (DstVT != MVT::i8) {
1218 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1219 ResultReg, /*Kill=*/true);
1224 UpdateValueMap(I, ResultReg);
1229 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1230 // Unconditional branches are selected by tablegen-generated code.
1231 // Handle a conditional branch.
1232 const BranchInst *BI = cast<BranchInst>(I);
1233 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1234 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1236 // Fold the common case of a conditional branch with a comparison
1237 // in the same block (values defined on other blocks may not have
1238 // initialized registers).
1239 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1240 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1241 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1243 // Try to optimize or fold the cmp.
1244 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1245 switch (Predicate) {
1247 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true;
1248 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true;
1251 const Value *CmpLHS = CI->getOperand(0);
1252 const Value *CmpRHS = CI->getOperand(1);
1254 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1256 // We don't have to materialize a zero constant for this case and can just
1257 // use %x again on the RHS.
1258 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1259 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1260 if (CmpRHSC && CmpRHSC->isNullValue())
1264 // Try to take advantage of fallthrough opportunities.
1265 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1266 std::swap(TrueMBB, FalseMBB);
1267 Predicate = CmpInst::getInversePredicate(Predicate);
1270 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1271 // code check. Instead two branch instructions are required to check all
1272 // the flags. First we change the predicate to a supported conditon code,
1273 // which will be the first branch. Later one we will emit the second
1275 bool NeedExtraBranch = false;
1276 switch (Predicate) {
1278 case CmpInst::FCMP_OEQ:
1279 std::swap(TrueMBB, FalseMBB); // fall-through
1280 case CmpInst::FCMP_UNE:
1281 NeedExtraBranch = true;
1282 Predicate = CmpInst::FCMP_ONE;
1289 std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1290 assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1292 BranchOpc = X86::GetCondBranchFromCond(CC);
1294 std::swap(CmpLHS, CmpRHS);
1296 // Emit a compare of the LHS and RHS, setting the flags.
1297 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1303 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1305 if (NeedExtraBranch) {
1306 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1310 // Obtain the branch weight and add the TrueBB to the successor list.
1311 uint32_t BranchWeight = 0;
1313 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1314 TrueMBB->getBasicBlock());
1315 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1317 // Emits an unconditional branch to the FalseBB, obtains the branch
1318 // weight, andd adds it to the successor list.
1319 FastEmitBranch(FalseMBB, DbgLoc);
1323 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1324 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1325 // typically happen for _Bool and C++ bools.
1327 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1328 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1329 unsigned TestOpc = 0;
1330 switch (SourceVT.SimpleTy) {
1332 case MVT::i8: TestOpc = X86::TEST8ri; break;
1333 case MVT::i16: TestOpc = X86::TEST16ri; break;
1334 case MVT::i32: TestOpc = X86::TEST32ri; break;
1335 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1338 unsigned OpReg = getRegForValue(TI->getOperand(0));
1339 if (OpReg == 0) return false;
1340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1341 .addReg(OpReg).addImm(1);
1343 unsigned JmpOpc = X86::JNE_4;
1344 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1345 std::swap(TrueMBB, FalseMBB);
1349 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1351 FastEmitBranch(FalseMBB, DbgLoc);
1352 uint32_t BranchWeight = 0;
1354 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1355 TrueMBB->getBasicBlock());
1356 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1362 // Otherwise do a clumsy setcc and re-test it.
1363 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1364 // in an explicit cast, so make sure to handle that correctly.
1365 unsigned OpReg = getRegForValue(BI->getCondition());
1366 if (OpReg == 0) return false;
1368 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1369 .addReg(OpReg).addImm(1);
1370 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1372 FastEmitBranch(FalseMBB, DbgLoc);
1373 uint32_t BranchWeight = 0;
1375 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1376 TrueMBB->getBasicBlock());
1377 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1381 bool X86FastISel::X86SelectShift(const Instruction *I) {
1382 unsigned CReg = 0, OpReg = 0;
1383 const TargetRegisterClass *RC = nullptr;
1384 if (I->getType()->isIntegerTy(8)) {
1386 RC = &X86::GR8RegClass;
1387 switch (I->getOpcode()) {
1388 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1389 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1390 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1391 default: return false;
1393 } else if (I->getType()->isIntegerTy(16)) {
1395 RC = &X86::GR16RegClass;
1396 switch (I->getOpcode()) {
1397 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1398 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1399 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1400 default: return false;
1402 } else if (I->getType()->isIntegerTy(32)) {
1404 RC = &X86::GR32RegClass;
1405 switch (I->getOpcode()) {
1406 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1407 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1408 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1409 default: return false;
1411 } else if (I->getType()->isIntegerTy(64)) {
1413 RC = &X86::GR64RegClass;
1414 switch (I->getOpcode()) {
1415 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1416 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1417 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1418 default: return false;
1425 if (!isTypeLegal(I->getType(), VT))
1428 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1429 if (Op0Reg == 0) return false;
1431 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1432 if (Op1Reg == 0) return false;
1433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1434 CReg).addReg(Op1Reg);
1436 // The shift instruction uses X86::CL. If we defined a super-register
1437 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1438 if (CReg != X86::CL)
1439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1440 TII.get(TargetOpcode::KILL), X86::CL)
1441 .addReg(CReg, RegState::Kill);
1443 unsigned ResultReg = createResultReg(RC);
1444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1446 UpdateValueMap(I, ResultReg);
1450 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1451 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1452 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1453 const static bool S = true; // IsSigned
1454 const static bool U = false; // !IsSigned
1455 const static unsigned Copy = TargetOpcode::COPY;
1456 // For the X86 DIV/IDIV instruction, in most cases the dividend
1457 // (numerator) must be in a specific register pair highreg:lowreg,
1458 // producing the quotient in lowreg and the remainder in highreg.
1459 // For most data types, to set up the instruction, the dividend is
1460 // copied into lowreg, and lowreg is sign-extended or zero-extended
1461 // into highreg. The exception is i8, where the dividend is defined
1462 // as a single register rather than a register pair, and we
1463 // therefore directly sign-extend or zero-extend the dividend into
1464 // lowreg, instead of copying, and ignore the highreg.
1465 const static struct DivRemEntry {
1466 // The following portion depends only on the data type.
1467 const TargetRegisterClass *RC;
1468 unsigned LowInReg; // low part of the register pair
1469 unsigned HighInReg; // high part of the register pair
1470 // The following portion depends on both the data type and the operation.
1471 struct DivRemResult {
1472 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1473 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1474 // highreg, or copying a zero into highreg.
1475 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1476 // zero/sign-extending into lowreg for i8.
1477 unsigned DivRemResultReg; // Register containing the desired result.
1478 bool IsOpSigned; // Whether to use signed or unsigned form.
1479 } ResultTable[NumOps];
1480 } OpTable[NumTypes] = {
1481 { &X86::GR8RegClass, X86::AX, 0, {
1482 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1483 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1484 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1485 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1488 { &X86::GR16RegClass, X86::AX, X86::DX, {
1489 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1490 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1491 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1492 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1495 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1496 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1497 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1498 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1499 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1502 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1503 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1504 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1505 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1506 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1512 if (!isTypeLegal(I->getType(), VT))
1515 unsigned TypeIndex, OpIndex;
1516 switch (VT.SimpleTy) {
1517 default: return false;
1518 case MVT::i8: TypeIndex = 0; break;
1519 case MVT::i16: TypeIndex = 1; break;
1520 case MVT::i32: TypeIndex = 2; break;
1521 case MVT::i64: TypeIndex = 3;
1522 if (!Subtarget->is64Bit())
1527 switch (I->getOpcode()) {
1528 default: llvm_unreachable("Unexpected div/rem opcode");
1529 case Instruction::SDiv: OpIndex = 0; break;
1530 case Instruction::SRem: OpIndex = 1; break;
1531 case Instruction::UDiv: OpIndex = 2; break;
1532 case Instruction::URem: OpIndex = 3; break;
1535 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1536 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1537 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1540 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1544 // Move op0 into low-order input register.
1545 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1546 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1547 // Zero-extend or sign-extend into high-order input register.
1548 if (OpEntry.OpSignExtend) {
1549 if (OpEntry.IsOpSigned)
1550 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1551 TII.get(OpEntry.OpSignExtend));
1553 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1554 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1555 TII.get(X86::MOV32r0), Zero32);
1557 // Copy the zero into the appropriate sub/super/identical physical
1558 // register. Unfortunately the operations needed are not uniform enough to
1559 // fit neatly into the table above.
1560 if (VT.SimpleTy == MVT::i16) {
1561 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1562 TII.get(Copy), TypeEntry.HighInReg)
1563 .addReg(Zero32, 0, X86::sub_16bit);
1564 } else if (VT.SimpleTy == MVT::i32) {
1565 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1566 TII.get(Copy), TypeEntry.HighInReg)
1568 } else if (VT.SimpleTy == MVT::i64) {
1569 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1570 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1571 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1575 // Generate the DIV/IDIV instruction.
1576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1577 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1578 // For i8 remainder, we can't reference AH directly, as we'll end
1579 // up with bogus copies like %R9B = COPY %AH. Reference AX
1580 // instead to prevent AH references in a REX instruction.
1582 // The current assumption of the fast register allocator is that isel
1583 // won't generate explicit references to the GPR8_NOREX registers. If
1584 // the allocator and/or the backend get enhanced to be more robust in
1585 // that regard, this can be, and should be, removed.
1586 unsigned ResultReg = 0;
1587 if ((I->getOpcode() == Instruction::SRem ||
1588 I->getOpcode() == Instruction::URem) &&
1589 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1590 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1591 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1593 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1595 // Shift AX right by 8 bits instead of using AH.
1596 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1597 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1599 // Now reference the 8-bit subreg of the result.
1600 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1601 /*Kill=*/true, X86::sub_8bit);
1603 // Copy the result out of the physreg if we haven't already.
1605 ResultReg = createResultReg(TypeEntry.RC);
1606 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1607 .addReg(OpEntry.DivRemResultReg);
1609 UpdateValueMap(I, ResultReg);
1614 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1616 if (!isTypeLegal(I->getType(), VT))
1619 // We only use cmov here, if we don't have a cmov instruction bail.
1620 if (!Subtarget->hasCMov()) return false;
1623 const TargetRegisterClass *RC = nullptr;
1624 if (VT == MVT::i16) {
1625 Opc = X86::CMOVE16rr;
1626 RC = &X86::GR16RegClass;
1627 } else if (VT == MVT::i32) {
1628 Opc = X86::CMOVE32rr;
1629 RC = &X86::GR32RegClass;
1630 } else if (VT == MVT::i64) {
1631 Opc = X86::CMOVE64rr;
1632 RC = &X86::GR64RegClass;
1637 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1638 if (Op0Reg == 0) return false;
1639 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1640 if (Op1Reg == 0) return false;
1641 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1642 if (Op2Reg == 0) return false;
1644 // Selects operate on i1, however, Op0Reg is 8 bits width and may contain
1645 // garbage. Indeed, only the less significant bit is supposed to be accurate.
1646 // If we read more than the lsb, we may see non-zero values whereas lsb
1647 // is zero. Therefore, we have to truncate Op0Reg to i1 for the select.
1648 // This is achieved by performing TEST against 1.
1649 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1650 .addReg(Op0Reg).addImm(1);
1651 unsigned ResultReg = createResultReg(RC);
1652 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1653 .addReg(Op1Reg).addReg(Op2Reg);
1654 UpdateValueMap(I, ResultReg);
1658 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1659 // fpext from float to double.
1660 if (X86ScalarSSEf64 &&
1661 I->getType()->isDoubleTy()) {
1662 const Value *V = I->getOperand(0);
1663 if (V->getType()->isFloatTy()) {
1664 unsigned OpReg = getRegForValue(V);
1665 if (OpReg == 0) return false;
1666 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1668 TII.get(X86::CVTSS2SDrr), ResultReg)
1670 UpdateValueMap(I, ResultReg);
1678 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1679 if (X86ScalarSSEf64) {
1680 if (I->getType()->isFloatTy()) {
1681 const Value *V = I->getOperand(0);
1682 if (V->getType()->isDoubleTy()) {
1683 unsigned OpReg = getRegForValue(V);
1684 if (OpReg == 0) return false;
1685 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1687 TII.get(X86::CVTSD2SSrr), ResultReg)
1689 UpdateValueMap(I, ResultReg);
1698 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1699 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1700 EVT DstVT = TLI.getValueType(I->getType());
1702 // This code only handles truncation to byte.
1703 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1705 if (!TLI.isTypeLegal(SrcVT))
1708 unsigned InputReg = getRegForValue(I->getOperand(0));
1710 // Unhandled operand. Halt "fast" selection and bail.
1713 if (SrcVT == MVT::i8) {
1714 // Truncate from i8 to i1; no code needed.
1715 UpdateValueMap(I, InputReg);
1719 if (!Subtarget->is64Bit()) {
1720 // If we're on x86-32; we can't extract an i8 from a general register.
1721 // First issue a copy to GR16_ABCD or GR32_ABCD.
1722 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1723 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1724 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1725 unsigned CopyReg = createResultReg(CopyRC);
1726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1727 CopyReg).addReg(InputReg);
1731 // Issue an extract_subreg.
1732 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1733 InputReg, /*Kill=*/true,
1738 UpdateValueMap(I, ResultReg);
1742 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1743 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1746 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1747 X86AddressMode SrcAM, uint64_t Len) {
1749 // Make sure we don't bloat code by inlining very large memcpy's.
1750 if (!IsMemcpySmall(Len))
1753 bool i64Legal = Subtarget->is64Bit();
1755 // We don't care about alignment here since we just emit integer accesses.
1758 if (Len >= 8 && i64Legal)
1769 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
1770 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
1771 assert(RV && "Failed to emit load or store??");
1773 unsigned Size = VT.getSizeInBits()/8;
1775 DestAM.Disp += Size;
1782 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
1783 switch (I.getIntrinsicID()) {
1784 case Intrinsic::sadd_with_overflow:
1785 case Intrinsic::uadd_with_overflow:
1786 case Intrinsic::smul_with_overflow:
1787 case Intrinsic::umul_with_overflow:
1794 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1795 // FIXME: Handle more intrinsics.
1796 switch (I.getIntrinsicID()) {
1797 default: return false;
1798 case Intrinsic::frameaddress: {
1799 Type *RetTy = I.getCalledFunction()->getReturnType();
1802 if (!isTypeLegal(RetTy, VT))
1806 const TargetRegisterClass *RC = nullptr;
1808 switch (VT.SimpleTy) {
1809 default: llvm_unreachable("Invalid result type for frameaddress.");
1810 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
1811 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
1814 // This needs to be set before we call getFrameRegister, otherwise we get
1815 // the wrong frame register.
1816 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1817 MFI->setFrameAddressIsTaken(true);
1819 const X86RegisterInfo *RegInfo =
1820 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
1821 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
1822 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
1823 (FrameReg == X86::EBP && VT == MVT::i32)) &&
1824 "Invalid Frame Register!");
1826 // Always make a copy of the frame register to to a vreg first, so that we
1827 // never directly reference the frame register (the TwoAddressInstruction-
1828 // Pass doesn't like that).
1829 unsigned SrcReg = createResultReg(RC);
1830 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1831 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
1833 // Now recursively load from the frame address.
1834 // movq (%rbp), %rax
1835 // movq (%rax), %rax
1836 // movq (%rax), %rax
1839 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
1841 DestReg = createResultReg(RC);
1842 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1843 TII.get(Opc), DestReg), SrcReg);
1847 UpdateValueMap(&I, SrcReg);
1850 case Intrinsic::memcpy: {
1851 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1852 // Don't handle volatile or variable length memcpys.
1853 if (MCI.isVolatile())
1856 if (isa<ConstantInt>(MCI.getLength())) {
1857 // Small memcpy's are common enough that we want to do them
1858 // without a call if possible.
1859 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1860 if (IsMemcpySmall(Len)) {
1861 X86AddressMode DestAM, SrcAM;
1862 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1863 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1865 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1870 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1871 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1874 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1877 return DoSelectCall(&I, "memcpy");
1879 case Intrinsic::memset: {
1880 const MemSetInst &MSI = cast<MemSetInst>(I);
1882 if (MSI.isVolatile())
1885 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1886 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1889 if (MSI.getDestAddressSpace() > 255)
1892 return DoSelectCall(&I, "memset");
1894 case Intrinsic::stackprotector: {
1895 // Emit code to store the stack guard onto the stack.
1896 EVT PtrTy = TLI.getPointerTy();
1898 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1899 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1901 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
1903 // Grab the frame index.
1905 if (!X86SelectAddress(Slot, AM)) return false;
1906 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1909 case Intrinsic::dbg_declare: {
1910 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1912 assert(DI->getAddress() && "Null address should be checked earlier!");
1913 if (!X86SelectAddress(DI->getAddress(), AM))
1915 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1916 // FIXME may need to add RegState::Debug to any registers produced,
1917 // although ESP/EBP should be the only ones at the moment.
1918 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
1919 addImm(0).addMetadata(DI->getVariable());
1922 case Intrinsic::trap: {
1923 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
1926 case Intrinsic::sqrt: {
1927 if (!Subtarget->hasSSE1())
1930 Type *RetTy = I.getCalledFunction()->getReturnType();
1933 if (!isTypeLegal(RetTy, VT))
1936 // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
1937 // is not generated by FastISel yet.
1938 // FIXME: Update this code once tablegen can handle it.
1939 static const unsigned SqrtOpc[2][2] = {
1940 {X86::SQRTSSr, X86::VSQRTSSr},
1941 {X86::SQRTSDr, X86::VSQRTSDr}
1943 bool HasAVX = Subtarget->hasAVX();
1945 const TargetRegisterClass *RC;
1946 switch (VT.SimpleTy) {
1947 default: return false;
1948 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
1949 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
1952 const Value *SrcVal = I.getArgOperand(0);
1953 unsigned SrcReg = getRegForValue(SrcVal);
1958 unsigned ImplicitDefReg = 0;
1960 ImplicitDefReg = createResultReg(RC);
1961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1962 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
1965 unsigned ResultReg = createResultReg(RC);
1966 MachineInstrBuilder MIB;
1967 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1971 MIB.addReg(ImplicitDefReg);
1975 UpdateValueMap(&I, ResultReg);
1978 case Intrinsic::sadd_with_overflow:
1979 case Intrinsic::uadd_with_overflow:
1980 case Intrinsic::ssub_with_overflow:
1981 case Intrinsic::usub_with_overflow:
1982 case Intrinsic::smul_with_overflow:
1983 case Intrinsic::umul_with_overflow: {
1984 // This implements the basic lowering of the xalu with overflow intrinsics
1985 // into add/sub/mul folowed by either seto or setb.
1986 const Function *Callee = I.getCalledFunction();
1987 auto *Ty = cast<StructType>(Callee->getReturnType());
1988 Type *RetTy = Ty->getTypeAtIndex(0U);
1989 Type *CondTy = Ty->getTypeAtIndex(1);
1992 if (!isTypeLegal(RetTy, VT))
1995 if (VT < MVT::i8 || VT > MVT::i64)
1998 const Value *LHS = I.getArgOperand(0);
1999 const Value *RHS = I.getArgOperand(1);
2001 // Canonicalize immediates to the RHS.
2002 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2003 isCommutativeIntrinsic(I))
2004 std::swap(LHS, RHS);
2006 unsigned BaseOpc, CondOpc;
2007 switch (I.getIntrinsicID()) {
2008 default: llvm_unreachable("Unexpected intrinsic!");
2009 case Intrinsic::sadd_with_overflow:
2010 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
2011 case Intrinsic::uadd_with_overflow:
2012 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2013 case Intrinsic::ssub_with_overflow:
2014 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
2015 case Intrinsic::usub_with_overflow:
2016 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2017 case Intrinsic::smul_with_overflow:
2018 BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
2019 case Intrinsic::umul_with_overflow:
2020 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2023 unsigned LHSReg = getRegForValue(LHS);
2026 bool LHSIsKill = hasTrivialKill(LHS);
2028 unsigned ResultReg = 0;
2029 // Check if we have an immediate version.
2030 if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
2031 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2038 RHSReg = getRegForValue(RHS);
2041 RHSIsKill = hasTrivialKill(RHS);
2042 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2046 // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
2047 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2048 static const unsigned MULOpc[] =
2049 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2050 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2051 // First copy the first operand into RAX, which is an implicit input to
2052 // the X86::MUL*r instruction.
2053 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2054 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2055 .addReg(LHSReg, getKillRegState(LHSIsKill));
2056 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2057 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2063 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2064 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2068 UpdateValueMap(&I, ResultReg, 2);
2071 case Intrinsic::x86_sse_cvttss2si:
2072 case Intrinsic::x86_sse_cvttss2si64:
2073 case Intrinsic::x86_sse2_cvttsd2si:
2074 case Intrinsic::x86_sse2_cvttsd2si64: {
2076 switch (I.getIntrinsicID()) {
2077 default: llvm_unreachable("Unexpected intrinsic.");
2078 case Intrinsic::x86_sse_cvttss2si:
2079 case Intrinsic::x86_sse_cvttss2si64:
2080 if (!Subtarget->hasSSE1())
2082 IsInputDouble = false;
2084 case Intrinsic::x86_sse2_cvttsd2si:
2085 case Intrinsic::x86_sse2_cvttsd2si64:
2086 if (!Subtarget->hasSSE2())
2088 IsInputDouble = true;
2092 Type *RetTy = I.getCalledFunction()->getReturnType();
2094 if (!isTypeLegal(RetTy, VT))
2097 static const unsigned CvtOpc[2][2][2] = {
2098 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2099 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2100 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2101 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2103 bool HasAVX = Subtarget->hasAVX();
2105 switch (VT.SimpleTy) {
2106 default: llvm_unreachable("Unexpected result type.");
2107 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2108 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2111 // Check if we can fold insertelement instructions into the convert.
2112 const Value *Op = I.getArgOperand(0);
2113 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2114 const Value *Index = IE->getOperand(2);
2115 if (!isa<ConstantInt>(Index))
2117 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2120 Op = IE->getOperand(1);
2123 Op = IE->getOperand(0);
2126 unsigned Reg = getRegForValue(Op);
2130 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2131 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2134 UpdateValueMap(&I, ResultReg);
2140 bool X86FastISel::FastLowerArguments() {
2141 if (!FuncInfo.CanLowerReturn)
2144 const Function *F = FuncInfo.Fn;
2148 CallingConv::ID CC = F->getCallingConv();
2149 if (CC != CallingConv::C)
2152 if (Subtarget->isCallingConvWin64(CC))
2155 if (!Subtarget->is64Bit())
2158 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2159 unsigned GPRCnt = 0;
2160 unsigned FPRCnt = 0;
2162 for (auto const &Arg : F->args()) {
2163 // The first argument is at index 1.
2165 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2166 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2167 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2168 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2171 Type *ArgTy = Arg.getType();
2172 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2175 EVT ArgVT = TLI.getValueType(ArgTy);
2176 if (!ArgVT.isSimple()) return false;
2177 switch (ArgVT.getSimpleVT().SimpleTy) {
2178 default: return false;
2185 if (!Subtarget->hasSSE1())
2198 static const MCPhysReg GPR32ArgRegs[] = {
2199 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2201 static const MCPhysReg GPR64ArgRegs[] = {
2202 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2204 static const MCPhysReg XMMArgRegs[] = {
2205 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2206 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2209 unsigned GPRIdx = 0;
2210 unsigned FPRIdx = 0;
2211 for (auto const &Arg : F->args()) {
2212 MVT VT = TLI.getSimpleValueType(Arg.getType());
2213 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2215 switch (VT.SimpleTy) {
2216 default: llvm_unreachable("Unexpected value type.");
2217 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2218 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2219 case MVT::f32: // fall-through
2220 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2222 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2223 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2224 // Without this, EmitLiveInCopies may eliminate the livein if its only
2225 // use is a bitcast (which isn't turned into an instruction).
2226 unsigned ResultReg = createResultReg(RC);
2227 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2228 TII.get(TargetOpcode::COPY), ResultReg)
2229 .addReg(DstReg, getKillRegState(true));
2230 UpdateValueMap(&Arg, ResultReg);
2235 bool X86FastISel::X86SelectCall(const Instruction *I) {
2236 const CallInst *CI = cast<CallInst>(I);
2237 const Value *Callee = CI->getCalledValue();
2239 // Can't handle inline asm yet.
2240 if (isa<InlineAsm>(Callee))
2243 // Handle intrinsic calls.
2244 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2245 return X86VisitIntrinsicCall(*II);
2247 // Allow SelectionDAG isel to handle tail calls.
2248 if (cast<CallInst>(I)->isTailCall())
2251 return DoSelectCall(I, nullptr);
2254 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2255 const ImmutableCallSite &CS) {
2256 if (Subtarget.is64Bit())
2258 if (Subtarget.getTargetTriple().isOSMSVCRT())
2260 CallingConv::ID CC = CS.getCallingConv();
2261 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2263 if (!CS.paramHasAttr(1, Attribute::StructRet))
2265 if (CS.paramHasAttr(1, Attribute::InReg))
2270 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2271 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2272 const CallInst *CI = cast<CallInst>(I);
2273 const Value *Callee = CI->getCalledValue();
2275 // Handle only C and fastcc calling conventions for now.
2276 ImmutableCallSite CS(CI);
2277 CallingConv::ID CC = CS.getCallingConv();
2278 bool isWin64 = Subtarget->isCallingConvWin64(CC);
2279 if (CC != CallingConv::C && CC != CallingConv::Fast &&
2280 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2281 CC != CallingConv::X86_64_SysV)
2284 // fastcc with -tailcallopt is intended to provide a guaranteed
2285 // tail call optimization. Fastisel doesn't know how to do that.
2286 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2289 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2290 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2291 bool isVarArg = FTy->isVarArg();
2293 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2294 // x86-32. Special handling for x86-64 is implemented.
2295 if (isVarArg && isWin64)
2298 // Don't know about inalloca yet.
2299 if (CS.hasInAllocaArgument())
2302 // Fast-isel doesn't know about callee-pop yet.
2303 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2304 TM.Options.GuaranteedTailCallOpt))
2307 // Check whether the function can return without sret-demotion.
2308 SmallVector<ISD::OutputArg, 4> Outs;
2309 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2310 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2311 *FuncInfo.MF, FTy->isVarArg(),
2312 Outs, FTy->getContext());
2313 if (!CanLowerReturn)
2316 // Materialize callee address in a register. FIXME: GV address can be
2317 // handled with a CALLpcrel32 instead.
2318 X86AddressMode CalleeAM;
2319 if (!X86SelectCallAddress(Callee, CalleeAM))
2321 unsigned CalleeOp = 0;
2322 const GlobalValue *GV = nullptr;
2323 if (CalleeAM.GV != nullptr) {
2325 } else if (CalleeAM.Base.Reg != 0) {
2326 CalleeOp = CalleeAM.Base.Reg;
2330 // Deal with call operands first.
2331 SmallVector<const Value *, 8> ArgVals;
2332 SmallVector<unsigned, 8> Args;
2333 SmallVector<MVT, 8> ArgVTs;
2334 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2335 unsigned arg_size = CS.arg_size();
2336 Args.reserve(arg_size);
2337 ArgVals.reserve(arg_size);
2338 ArgVTs.reserve(arg_size);
2339 ArgFlags.reserve(arg_size);
2340 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2342 // If we're lowering a mem intrinsic instead of a regular call, skip the
2343 // last two arguments, which should not passed to the underlying functions.
2344 if (MemIntName && e-i <= 2)
2347 ISD::ArgFlagsTy Flags;
2348 unsigned AttrInd = i - CS.arg_begin() + 1;
2349 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2351 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2354 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2355 PointerType *Ty = cast<PointerType>(ArgVal->getType());
2356 Type *ElementTy = Ty->getElementType();
2357 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2358 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2360 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2362 Flags.setByValSize(FrameSize);
2363 Flags.setByValAlign(FrameAlign);
2364 if (!IsMemcpySmall(FrameSize))
2368 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2370 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2373 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2374 // instruction. This is safe because it is common to all fastisel supported
2375 // calling conventions on x86.
2376 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2377 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2378 CI->getBitWidth() == 16) {
2380 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2382 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2388 // Passing bools around ends up doing a trunc to i1 and passing it.
2389 // Codegen this as an argument + "and 1".
2390 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2391 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2392 ArgVal->hasOneUse()) {
2393 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2394 ArgReg = getRegForValue(ArgVal);
2395 if (ArgReg == 0) return false;
2398 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2400 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2401 ArgVal->hasOneUse(), 1);
2403 ArgReg = getRegForValue(ArgVal);
2406 if (ArgReg == 0) return false;
2408 Type *ArgTy = ArgVal->getType();
2410 if (!isTypeLegal(ArgTy, ArgVT))
2412 if (ArgVT == MVT::x86mmx)
2414 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2415 Flags.setOrigAlign(OriginalAlignment);
2417 Args.push_back(ArgReg);
2418 ArgVals.push_back(ArgVal);
2419 ArgVTs.push_back(ArgVT);
2420 ArgFlags.push_back(Flags);
2423 // Analyze operands of the call, assigning locations to each operand.
2424 SmallVector<CCValAssign, 16> ArgLocs;
2425 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2426 I->getParent()->getContext());
2428 // Allocate shadow area for Win64
2430 CCInfo.AllocateStack(32, 8);
2432 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2434 // Get a count of how many bytes are to be pushed on the stack.
2435 unsigned NumBytes = CCInfo.getNextStackOffset();
2437 // Issue CALLSEQ_START
2438 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2442 // Process argument: walk the register/memloc assignments, inserting
2444 SmallVector<unsigned, 4> RegArgs;
2445 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2446 CCValAssign &VA = ArgLocs[i];
2447 unsigned Arg = Args[VA.getValNo()];
2448 EVT ArgVT = ArgVTs[VA.getValNo()];
2450 // Promote the value if needed.
2451 switch (VA.getLocInfo()) {
2452 case CCValAssign::Full: break;
2453 case CCValAssign::SExt: {
2454 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2455 "Unexpected extend");
2456 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2458 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2459 ArgVT = VA.getLocVT();
2462 case CCValAssign::ZExt: {
2463 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2464 "Unexpected extend");
2465 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2467 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2468 ArgVT = VA.getLocVT();
2471 case CCValAssign::AExt: {
2472 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2473 "Unexpected extend");
2474 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2477 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2480 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2483 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2484 ArgVT = VA.getLocVT();
2487 case CCValAssign::BCvt: {
2488 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2489 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2490 assert(BC != 0 && "Failed to emit a bitcast!");
2492 ArgVT = VA.getLocVT();
2495 case CCValAssign::VExt:
2496 // VExt has not been implemented, so this should be impossible to reach
2497 // for now. However, fallback to Selection DAG isel once implemented.
2499 case CCValAssign::Indirect:
2500 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2503 case CCValAssign::FPExt:
2504 llvm_unreachable("Unexpected loc info!");
2507 if (VA.isRegLoc()) {
2508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2509 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2510 RegArgs.push_back(VA.getLocReg());
2512 unsigned LocMemOffset = VA.getLocMemOffset();
2514 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2515 getTargetMachine()->getRegisterInfo());
2516 AM.Base.Reg = RegInfo->getStackRegister();
2517 AM.Disp = LocMemOffset;
2518 const Value *ArgVal = ArgVals[VA.getValNo()];
2519 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2521 if (Flags.isByVal()) {
2522 X86AddressMode SrcAM;
2523 SrcAM.Base.Reg = Arg;
2524 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2525 assert(Res && "memcpy length already checked!"); (void)Res;
2526 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2527 // If this is a really simple value, emit this with the Value* version
2528 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2529 // as it can cause us to reevaluate the argument.
2530 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2533 if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2539 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2541 if (Subtarget->isPICStyleGOT()) {
2542 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2543 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2544 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2547 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2548 // Count the number of XMM registers allocated.
2549 static const MCPhysReg XMMArgRegs[] = {
2550 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2551 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2553 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2554 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2555 X86::AL).addImm(NumXMMRegs);
2559 MachineInstrBuilder MIB;
2561 // Register-indirect call.
2563 if (Subtarget->is64Bit())
2564 CallOpc = X86::CALL64r;
2566 CallOpc = X86::CALL32r;
2567 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2572 assert(GV && "Not a direct call");
2574 if (Subtarget->is64Bit())
2575 CallOpc = X86::CALL64pcrel32;
2577 CallOpc = X86::CALLpcrel32;
2579 // See if we need any target-specific flags on the GV operand.
2580 unsigned char OpFlags = 0;
2582 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2583 // external symbols most go through the PLT in PIC mode. If the symbol
2584 // has hidden or protected visibility, or if it is static or local, then
2585 // we don't need to use the PLT - we can directly call it.
2586 if (Subtarget->isTargetELF() &&
2587 TM.getRelocationModel() == Reloc::PIC_ &&
2588 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2589 OpFlags = X86II::MO_PLT;
2590 } else if (Subtarget->isPICStyleStubAny() &&
2591 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2592 (!Subtarget->getTargetTriple().isMacOSX() ||
2593 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2594 // PC-relative references to external symbols should go through $stub,
2595 // unless we're building with the leopard linker or later, which
2596 // automatically synthesizes these stubs.
2597 OpFlags = X86II::MO_DARWIN_STUB;
2601 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2603 MIB.addExternalSymbol(MemIntName, OpFlags);
2605 MIB.addGlobalAddress(GV, 0, OpFlags);
2608 // Add a register mask with the call-preserved registers.
2609 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2610 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2612 // Add an implicit use GOT pointer in EBX.
2613 if (Subtarget->isPICStyleGOT())
2614 MIB.addReg(X86::EBX, RegState::Implicit);
2616 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2617 MIB.addReg(X86::AL, RegState::Implicit);
2619 // Add implicit physical register uses to the call.
2620 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2621 MIB.addReg(RegArgs[i], RegState::Implicit);
2623 // Issue CALLSEQ_END
2624 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2625 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2627 .addImm(NumBytes).addImm(NumBytesCallee);
2629 // Build info for return calling conv lowering code.
2630 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2631 SmallVector<ISD::InputArg, 32> Ins;
2632 SmallVector<EVT, 4> RetTys;
2633 ComputeValueVTs(TLI, I->getType(), RetTys);
2634 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2636 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2637 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2638 for (unsigned j = 0; j != NumRegs; ++j) {
2639 ISD::InputArg MyFlags;
2640 MyFlags.VT = RegisterVT;
2641 MyFlags.Used = !CS.getInstruction()->use_empty();
2642 if (CS.paramHasAttr(0, Attribute::SExt))
2643 MyFlags.Flags.setSExt();
2644 if (CS.paramHasAttr(0, Attribute::ZExt))
2645 MyFlags.Flags.setZExt();
2646 if (CS.paramHasAttr(0, Attribute::InReg))
2647 MyFlags.Flags.setInReg();
2648 Ins.push_back(MyFlags);
2652 // Now handle call return values.
2653 SmallVector<unsigned, 4> UsedRegs;
2654 SmallVector<CCValAssign, 16> RVLocs;
2655 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2656 I->getParent()->getContext());
2657 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2658 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2659 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2660 EVT CopyVT = RVLocs[i].getValVT();
2661 unsigned CopyReg = ResultReg + i;
2663 // If this is a call to a function that returns an fp value on the x87 fp
2664 // stack, but where we prefer to use the value in xmm registers, copy it
2665 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2666 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2667 RVLocs[i].getLocReg() == X86::ST1)) {
2668 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2670 CopyReg = createResultReg(&X86::RFP80RegClass);
2672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2673 TII.get(X86::FpPOP_RETVAL), CopyReg);
2675 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2676 TII.get(TargetOpcode::COPY),
2677 CopyReg).addReg(RVLocs[i].getLocReg());
2678 UsedRegs.push_back(RVLocs[i].getLocReg());
2681 if (CopyVT != RVLocs[i].getValVT()) {
2682 // Round the F80 the right size, which also moves to the appropriate xmm
2683 // register. This is accomplished by storing the F80 value in memory and
2684 // then loading it back. Ewww...
2685 EVT ResVT = RVLocs[i].getValVT();
2686 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2687 unsigned MemSize = ResVT.getSizeInBits()/8;
2688 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2689 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2692 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2693 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2694 TII.get(Opc), ResultReg + i), FI);
2699 UpdateValueMap(I, ResultReg, RVLocs.size());
2701 // Set all unused physreg defs as dead.
2702 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2709 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2710 switch (I->getOpcode()) {
2712 case Instruction::Load:
2713 return X86SelectLoad(I);
2714 case Instruction::Store:
2715 return X86SelectStore(I);
2716 case Instruction::Ret:
2717 return X86SelectRet(I);
2718 case Instruction::ICmp:
2719 case Instruction::FCmp:
2720 return X86SelectCmp(I);
2721 case Instruction::ZExt:
2722 return X86SelectZExt(I);
2723 case Instruction::Br:
2724 return X86SelectBranch(I);
2725 case Instruction::Call:
2726 return X86SelectCall(I);
2727 case Instruction::LShr:
2728 case Instruction::AShr:
2729 case Instruction::Shl:
2730 return X86SelectShift(I);
2731 case Instruction::SDiv:
2732 case Instruction::UDiv:
2733 case Instruction::SRem:
2734 case Instruction::URem:
2735 return X86SelectDivRem(I);
2736 case Instruction::Select:
2737 return X86SelectSelect(I);
2738 case Instruction::Trunc:
2739 return X86SelectTrunc(I);
2740 case Instruction::FPExt:
2741 return X86SelectFPExt(I);
2742 case Instruction::FPTrunc:
2743 return X86SelectFPTrunc(I);
2744 case Instruction::IntToPtr: // Deliberate fall-through.
2745 case Instruction::PtrToInt: {
2746 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2747 EVT DstVT = TLI.getValueType(I->getType());
2748 if (DstVT.bitsGT(SrcVT))
2749 return X86SelectZExt(I);
2750 if (DstVT.bitsLT(SrcVT))
2751 return X86SelectTrunc(I);
2752 unsigned Reg = getRegForValue(I->getOperand(0));
2753 if (Reg == 0) return false;
2754 UpdateValueMap(I, Reg);
2762 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2764 if (!isTypeLegal(C->getType(), VT))
2767 // Can't handle alternate code models yet.
2768 if (TM.getCodeModel() != CodeModel::Small)
2771 // Get opcode and regclass of the output for the given load instruction.
2773 const TargetRegisterClass *RC = nullptr;
2774 switch (VT.SimpleTy) {
2778 RC = &X86::GR8RegClass;
2782 RC = &X86::GR16RegClass;
2786 RC = &X86::GR32RegClass;
2789 // Must be in x86-64 mode.
2791 RC = &X86::GR64RegClass;
2794 if (X86ScalarSSEf32) {
2795 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2796 RC = &X86::FR32RegClass;
2798 Opc = X86::LD_Fp32m;
2799 RC = &X86::RFP32RegClass;
2803 if (X86ScalarSSEf64) {
2804 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2805 RC = &X86::FR64RegClass;
2807 Opc = X86::LD_Fp64m;
2808 RC = &X86::RFP64RegClass;
2812 // No f80 support yet.
2816 // Materialize addresses with LEA/MOV instructions.
2817 if (isa<GlobalValue>(C)) {
2819 if (X86SelectAddress(C, AM)) {
2820 // If the expression is just a basereg, then we're done, otherwise we need
2822 if (AM.BaseType == X86AddressMode::RegBase &&
2823 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
2826 unsigned ResultReg = createResultReg(RC);
2827 if (TM.getRelocationModel() == Reloc::Static &&
2828 TLI.getPointerTy() == MVT::i64) {
2829 // The displacement code be more than 32 bits away so we need to use
2830 // an instruction with a 64 bit immediate
2832 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2833 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C));
2835 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2836 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2837 TII.get(Opc), ResultReg), AM);
2844 // MachineConstantPool wants an explicit alignment.
2845 unsigned Align = DL.getPrefTypeAlignment(C->getType());
2847 // Alignment of vector types. FIXME!
2848 Align = DL.getTypeAllocSize(C->getType());
2851 // x86-32 PIC requires a PIC base register for constant pools.
2852 unsigned PICBase = 0;
2853 unsigned char OpFlag = 0;
2854 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2855 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2856 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2857 } else if (Subtarget->isPICStyleGOT()) {
2858 OpFlag = X86II::MO_GOTOFF;
2859 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2860 } else if (Subtarget->isPICStyleRIPRel() &&
2861 TM.getCodeModel() == CodeModel::Small) {
2865 // Create the load from the constant pool.
2866 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2867 unsigned ResultReg = createResultReg(RC);
2868 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2869 TII.get(Opc), ResultReg),
2870 MCPOffset, PICBase, OpFlag);
2875 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2876 // Fail on dynamic allocas. At this point, getRegForValue has already
2877 // checked its CSE maps, so if we're here trying to handle a dynamic
2878 // alloca, we're not going to succeed. X86SelectAddress has a
2879 // check for dynamic allocas, because it's called directly from
2880 // various places, but TargetMaterializeAlloca also needs a check
2881 // in order to avoid recursion between getRegForValue,
2882 // X86SelectAddrss, and TargetMaterializeAlloca.
2883 if (!FuncInfo.StaticAllocaMap.count(C))
2885 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
2888 if (!X86SelectAddress(C, AM))
2890 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2891 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2892 unsigned ResultReg = createResultReg(RC);
2893 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2894 TII.get(Opc), ResultReg), AM);
2898 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2900 if (!isTypeLegal(CF->getType(), VT))
2903 // Get opcode and regclass for the given zero.
2905 const TargetRegisterClass *RC = nullptr;
2906 switch (VT.SimpleTy) {
2909 if (X86ScalarSSEf32) {
2910 Opc = X86::FsFLD0SS;
2911 RC = &X86::FR32RegClass;
2913 Opc = X86::LD_Fp032;
2914 RC = &X86::RFP32RegClass;
2918 if (X86ScalarSSEf64) {
2919 Opc = X86::FsFLD0SD;
2920 RC = &X86::FR64RegClass;
2922 Opc = X86::LD_Fp064;
2923 RC = &X86::RFP64RegClass;
2927 // No f80 support yet.
2931 unsigned ResultReg = createResultReg(RC);
2932 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
2937 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2938 const LoadInst *LI) {
2939 const Value *Ptr = LI->getPointerOperand();
2941 if (!X86SelectAddress(Ptr, AM))
2944 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2946 unsigned Size = DL.getTypeAllocSize(LI->getType());
2947 unsigned Alignment = LI->getAlignment();
2949 if (Alignment == 0) // Ensure that codegen never sees alignment 0
2950 Alignment = DL.getABITypeAlignment(LI->getType());
2952 SmallVector<MachineOperand, 8> AddrOps;
2953 AM.getFullAddress(AddrOps);
2955 MachineInstr *Result =
2956 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2960 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
2961 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2962 MI->eraseFromParent();
2968 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2969 const TargetLibraryInfo *libInfo) {
2970 return new X86FastISel(funcInfo, libInfo);