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 "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetOptions.h"
43 class X86FastISel : public FastISel {
44 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
45 /// make the right decision when generating code for different targets.
46 const X86Subtarget *Subtarget;
48 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
49 /// floating point ops.
50 /// When SSE is available, use it for f32 operations.
51 /// When SSE2 is available, use it for f64 operations.
56 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
57 const TargetLibraryInfo *libInfo)
58 : FastISel(funcInfo, libInfo) {
59 Subtarget = &TM.getSubtarget<X86Subtarget>();
60 X86ScalarSSEf64 = Subtarget->hasSSE2();
61 X86ScalarSSEf32 = Subtarget->hasSSE1();
64 virtual bool TargetSelectInstruction(const Instruction *I);
66 /// \brief The specified machine instr operand is a vreg, and that
67 /// vreg is being provided by the specified load instruction. If possible,
68 /// try to fold the load as an operand to the instruction, returning true if
70 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
73 virtual bool FastLowerArguments();
75 #include "X86GenFastISel.inc"
78 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
80 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
82 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
83 bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
85 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
88 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
89 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
91 bool X86SelectLoad(const Instruction *I);
93 bool X86SelectStore(const Instruction *I);
95 bool X86SelectRet(const Instruction *I);
97 bool X86SelectCmp(const Instruction *I);
99 bool X86SelectZExt(const Instruction *I);
101 bool X86SelectBranch(const Instruction *I);
103 bool X86SelectShift(const Instruction *I);
105 bool X86SelectDivRem(const Instruction *I);
107 bool X86SelectSelect(const Instruction *I);
109 bool X86SelectTrunc(const Instruction *I);
111 bool X86SelectFPExt(const Instruction *I);
112 bool X86SelectFPTrunc(const Instruction *I);
114 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
115 bool X86SelectCall(const Instruction *I);
117 bool DoSelectCall(const Instruction *I, const char *MemIntName);
119 const X86InstrInfo *getInstrInfo() const {
120 return getTargetMachine()->getInstrInfo();
122 const X86TargetMachine *getTargetMachine() const {
123 return static_cast<const X86TargetMachine *>(&TM);
126 unsigned TargetMaterializeConstant(const Constant *C);
128 unsigned TargetMaterializeAlloca(const AllocaInst *C);
130 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
132 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
133 /// computed in an SSE register, not on the X87 floating point stack.
134 bool isScalarFPTypeInSSEReg(EVT VT) const {
135 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
136 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
139 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
141 bool IsMemcpySmall(uint64_t Len);
143 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
144 X86AddressMode SrcAM, uint64_t Len);
147 } // end anonymous namespace.
149 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
150 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
151 if (evt == MVT::Other || !evt.isSimple())
152 // Unhandled type. Halt "fast" selection and bail.
155 VT = evt.getSimpleVT();
156 // For now, require SSE/SSE2 for performing floating-point operations,
157 // since x87 requires additional work.
158 if (VT == MVT::f64 && !X86ScalarSSEf64)
160 if (VT == MVT::f32 && !X86ScalarSSEf32)
162 // Similarly, no f80 support yet.
165 // We only handle legal types. For example, on x86-32 the instruction
166 // selector contains all of the 64-bit instructions from x86-64,
167 // under the assumption that i64 won't be used if the target doesn't
169 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
172 #include "X86GenCallingConv.inc"
174 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
175 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
176 /// Return true and the result register by reference if it is possible.
177 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
178 unsigned &ResultReg) {
179 // Get opcode and regclass of the output for the given load instruction.
181 const TargetRegisterClass *RC = NULL;
182 switch (VT.getSimpleVT().SimpleTy) {
183 default: return false;
187 RC = &X86::GR8RegClass;
191 RC = &X86::GR16RegClass;
195 RC = &X86::GR32RegClass;
198 // Must be in x86-64 mode.
200 RC = &X86::GR64RegClass;
203 if (X86ScalarSSEf32) {
204 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
205 RC = &X86::FR32RegClass;
208 RC = &X86::RFP32RegClass;
212 if (X86ScalarSSEf64) {
213 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
214 RC = &X86::FR64RegClass;
217 RC = &X86::RFP64RegClass;
221 // No f80 support yet.
225 ResultReg = createResultReg(RC);
226 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
227 DL, TII.get(Opc), ResultReg), AM);
231 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
232 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
233 /// and a displacement offset, or a GlobalAddress,
234 /// i.e. V. Return true if it is possible.
236 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
237 // Get opcode and regclass of the output for the given store instruction.
239 switch (VT.getSimpleVT().SimpleTy) {
240 case MVT::f80: // No f80 support yet.
241 default: return false;
243 // Mask out all but lowest bit.
244 unsigned AndResult = createResultReg(&X86::GR8RegClass);
245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
246 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
249 // FALLTHROUGH, handling i1 as i8.
250 case MVT::i8: Opc = X86::MOV8mr; break;
251 case MVT::i16: Opc = X86::MOV16mr; break;
252 case MVT::i32: Opc = X86::MOV32mr; break;
253 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
255 Opc = X86ScalarSSEf32 ?
256 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
259 Opc = X86ScalarSSEf64 ?
260 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
276 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
277 DL, TII.get(Opc)), AM).addReg(Val);
281 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
282 const X86AddressMode &AM) {
283 // Handle 'null' like i32/i64 0.
284 if (isa<ConstantPointerNull>(Val))
285 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
287 // If this is a store of a simple constant, fold the constant into the store.
288 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
291 switch (VT.getSimpleVT().SimpleTy) {
293 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
294 case MVT::i8: Opc = X86::MOV8mi; break;
295 case MVT::i16: Opc = X86::MOV16mi; break;
296 case MVT::i32: Opc = X86::MOV32mi; break;
298 // Must be a 32-bit sign extended value.
299 if (isInt<32>(CI->getSExtValue()))
300 Opc = X86::MOV64mi32;
305 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
306 DL, TII.get(Opc)), AM)
307 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
313 unsigned ValReg = getRegForValue(Val);
317 return X86FastEmitStore(VT, ValReg, AM);
320 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
321 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
322 /// ISD::SIGN_EXTEND).
323 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
324 unsigned Src, EVT SrcVT,
325 unsigned &ResultReg) {
326 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
327 Src, /*TODO: Kill=*/false);
335 /// X86SelectAddress - Attempt to fill in an address from the given value.
337 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
338 const User *U = NULL;
339 unsigned Opcode = Instruction::UserOp1;
340 if (const Instruction *I = dyn_cast<Instruction>(V)) {
341 // Don't walk into other basic blocks; it's possible we haven't
342 // visited them yet, so the instructions may not yet be assigned
343 // virtual registers.
344 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
345 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
346 Opcode = I->getOpcode();
349 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
350 Opcode = C->getOpcode();
354 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
355 if (Ty->getAddressSpace() > 255)
356 // Fast instruction selection doesn't support the special
362 case Instruction::BitCast:
363 // Look past bitcasts.
364 return X86SelectAddress(U->getOperand(0), AM);
366 case Instruction::IntToPtr:
367 // Look past no-op inttoptrs.
368 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
369 return X86SelectAddress(U->getOperand(0), AM);
372 case Instruction::PtrToInt:
373 // Look past no-op ptrtoints.
374 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
375 return X86SelectAddress(U->getOperand(0), AM);
378 case Instruction::Alloca: {
379 // Do static allocas.
380 const AllocaInst *A = cast<AllocaInst>(V);
381 DenseMap<const AllocaInst*, int>::iterator SI =
382 FuncInfo.StaticAllocaMap.find(A);
383 if (SI != FuncInfo.StaticAllocaMap.end()) {
384 AM.BaseType = X86AddressMode::FrameIndexBase;
385 AM.Base.FrameIndex = SI->second;
391 case Instruction::Add: {
392 // Adds of constants are common and easy enough.
393 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
394 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
395 // They have to fit in the 32-bit signed displacement field though.
396 if (isInt<32>(Disp)) {
397 AM.Disp = (uint32_t)Disp;
398 return X86SelectAddress(U->getOperand(0), AM);
404 case Instruction::GetElementPtr: {
405 X86AddressMode SavedAM = AM;
407 // Pattern-match simple GEPs.
408 uint64_t Disp = (int32_t)AM.Disp;
409 unsigned IndexReg = AM.IndexReg;
410 unsigned Scale = AM.Scale;
411 gep_type_iterator GTI = gep_type_begin(U);
412 // Iterate through the indices, folding what we can. Constants can be
413 // folded, and one dynamic index can be handled, if the scale is supported.
414 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
415 i != e; ++i, ++GTI) {
416 const Value *Op = *i;
417 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
418 const StructLayout *SL = TD.getStructLayout(STy);
419 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
423 // A array/variable index is always of the form i*S where S is the
424 // constant scale size. See if we can push the scale into immediates.
425 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
427 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
428 // Constant-offset addressing.
429 Disp += CI->getSExtValue() * S;
432 if (isa<AddOperator>(Op) &&
433 (!isa<Instruction>(Op) ||
434 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
436 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
437 // An add (in the same block) with a constant operand. Fold the
440 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
441 Disp += CI->getSExtValue() * S;
442 // Iterate on the other operand.
443 Op = cast<AddOperator>(Op)->getOperand(0);
447 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
448 (S == 1 || S == 2 || S == 4 || S == 8)) {
449 // Scaled-index addressing.
451 IndexReg = getRegForGEPIndex(Op).first;
457 goto unsupported_gep;
460 // Check for displacement overflow.
461 if (!isInt<32>(Disp))
463 // Ok, the GEP indices were covered by constant-offset and scaled-index
464 // addressing. Update the address state and move on to examining the base.
465 AM.IndexReg = IndexReg;
467 AM.Disp = (uint32_t)Disp;
468 if (X86SelectAddress(U->getOperand(0), AM))
471 // If we couldn't merge the gep value into this addr mode, revert back to
472 // our address and just match the value instead of completely failing.
476 // Ok, the GEP indices weren't all covered.
481 // Handle constant address.
482 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
483 // Can't handle alternate code models yet.
484 if (TM.getCodeModel() != CodeModel::Small)
487 // Can't handle TLS yet.
488 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
489 if (GVar->isThreadLocal())
492 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
494 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
495 if (const GlobalVariable *GVar =
496 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
497 if (GVar->isThreadLocal())
500 // RIP-relative addresses can't have additional register operands, so if
501 // we've already folded stuff into the addressing mode, just force the
502 // global value into its own register, which we can use as the basereg.
503 if (!Subtarget->isPICStyleRIPRel() ||
504 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
505 // Okay, we've committed to selecting this global. Set up the address.
508 // Allow the subtarget to classify the global.
509 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
511 // If this reference is relative to the pic base, set it now.
512 if (isGlobalRelativeToPICBase(GVFlags)) {
513 // FIXME: How do we know Base.Reg is free??
514 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
517 // Unless the ABI requires an extra load, return a direct reference to
519 if (!isGlobalStubReference(GVFlags)) {
520 if (Subtarget->isPICStyleRIPRel()) {
521 // Use rip-relative addressing if we can. Above we verified that the
522 // base and index registers are unused.
523 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
524 AM.Base.Reg = X86::RIP;
526 AM.GVOpFlags = GVFlags;
530 // Ok, we need to do a load from a stub. If we've already loaded from
531 // this stub, reuse the loaded pointer, otherwise emit the load now.
532 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
534 if (I != LocalValueMap.end() && I->second != 0) {
537 // Issue load from stub.
539 const TargetRegisterClass *RC = NULL;
540 X86AddressMode StubAM;
541 StubAM.Base.Reg = AM.Base.Reg;
543 StubAM.GVOpFlags = GVFlags;
545 // Prepare for inserting code in the local-value area.
546 SavePoint SaveInsertPt = enterLocalValueArea();
548 if (TLI.getPointerTy() == MVT::i64) {
550 RC = &X86::GR64RegClass;
552 if (Subtarget->isPICStyleRIPRel())
553 StubAM.Base.Reg = X86::RIP;
556 RC = &X86::GR32RegClass;
559 LoadReg = createResultReg(RC);
560 MachineInstrBuilder LoadMI =
561 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
562 addFullAddress(LoadMI, StubAM);
564 // Ok, back to normal mode.
565 leaveLocalValueArea(SaveInsertPt);
567 // Prevent loading GV stub multiple times in same MBB.
568 LocalValueMap[V] = LoadReg;
571 // Now construct the final address. Note that the Disp, Scale,
572 // and Index values may already be set here.
573 AM.Base.Reg = LoadReg;
579 // If all else fails, try to materialize the value in a register.
580 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
581 if (AM.Base.Reg == 0) {
582 AM.Base.Reg = getRegForValue(V);
583 return AM.Base.Reg != 0;
585 if (AM.IndexReg == 0) {
586 assert(AM.Scale == 1 && "Scale with no index!");
587 AM.IndexReg = getRegForValue(V);
588 return AM.IndexReg != 0;
595 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
597 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
598 const User *U = NULL;
599 unsigned Opcode = Instruction::UserOp1;
600 if (const Instruction *I = dyn_cast<Instruction>(V)) {
601 Opcode = I->getOpcode();
603 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
604 Opcode = C->getOpcode();
610 case Instruction::BitCast:
611 // Look past bitcasts.
612 return X86SelectCallAddress(U->getOperand(0), AM);
614 case Instruction::IntToPtr:
615 // Look past no-op inttoptrs.
616 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
617 return X86SelectCallAddress(U->getOperand(0), AM);
620 case Instruction::PtrToInt:
621 // Look past no-op ptrtoints.
622 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
623 return X86SelectCallAddress(U->getOperand(0), AM);
627 // Handle constant address.
628 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
629 // Can't handle alternate code models yet.
630 if (TM.getCodeModel() != CodeModel::Small)
633 // RIP-relative addresses can't have additional register operands.
634 if (Subtarget->isPICStyleRIPRel() &&
635 (AM.Base.Reg != 0 || AM.IndexReg != 0))
638 // Can't handle DLLImport.
639 if (GV->hasDLLImportLinkage())
643 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
644 if (GVar->isThreadLocal())
647 // Okay, we've committed to selecting this global. Set up the basic address.
650 // No ABI requires an extra load for anything other than DLLImport, which
651 // we rejected above. Return a direct reference to the global.
652 if (Subtarget->isPICStyleRIPRel()) {
653 // Use rip-relative addressing if we can. Above we verified that the
654 // base and index registers are unused.
655 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
656 AM.Base.Reg = X86::RIP;
657 } else if (Subtarget->isPICStyleStubPIC()) {
658 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
659 } else if (Subtarget->isPICStyleGOT()) {
660 AM.GVOpFlags = X86II::MO_GOTOFF;
666 // If all else fails, try to materialize the value in a register.
667 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
668 if (AM.Base.Reg == 0) {
669 AM.Base.Reg = getRegForValue(V);
670 return AM.Base.Reg != 0;
672 if (AM.IndexReg == 0) {
673 assert(AM.Scale == 1 && "Scale with no index!");
674 AM.IndexReg = getRegForValue(V);
675 return AM.IndexReg != 0;
683 /// X86SelectStore - Select and emit code to implement store instructions.
684 bool X86FastISel::X86SelectStore(const Instruction *I) {
685 // Atomic stores need special handling.
686 const StoreInst *S = cast<StoreInst>(I);
692 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
696 if (!X86SelectAddress(I->getOperand(1), AM))
699 return X86FastEmitStore(VT, I->getOperand(0), AM);
702 /// X86SelectRet - Select and emit code to implement ret instructions.
703 bool X86FastISel::X86SelectRet(const Instruction *I) {
704 const ReturnInst *Ret = cast<ReturnInst>(I);
705 const Function &F = *I->getParent()->getParent();
706 const X86MachineFunctionInfo *X86MFInfo =
707 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
709 if (!FuncInfo.CanLowerReturn)
712 CallingConv::ID CC = F.getCallingConv();
713 if (CC != CallingConv::C &&
714 CC != CallingConv::Fast &&
715 CC != CallingConv::X86_FastCall)
718 if (Subtarget->isTargetWin64())
721 // Don't handle popping bytes on return for now.
722 if (X86MFInfo->getBytesToPopOnReturn() != 0)
725 // fastcc with -tailcallopt is intended to provide a guaranteed
726 // tail call optimization. Fastisel doesn't know how to do that.
727 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
730 // Let SDISel handle vararg functions.
734 // Build a list of return value registers.
735 SmallVector<unsigned, 4> RetRegs;
737 if (Ret->getNumOperands() > 0) {
738 SmallVector<ISD::OutputArg, 4> Outs;
739 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
741 // Analyze operands of the call, assigning locations to each operand.
742 SmallVector<CCValAssign, 16> ValLocs;
743 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
745 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
747 const Value *RV = Ret->getOperand(0);
748 unsigned Reg = getRegForValue(RV);
752 // Only handle a single return value for now.
753 if (ValLocs.size() != 1)
756 CCValAssign &VA = ValLocs[0];
758 // Don't bother handling odd stuff for now.
759 if (VA.getLocInfo() != CCValAssign::Full)
761 // Only handle register returns for now.
765 // The calling-convention tables for x87 returns don't tell
767 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
770 unsigned SrcReg = Reg + VA.getValNo();
771 EVT SrcVT = TLI.getValueType(RV->getType());
772 EVT DstVT = VA.getValVT();
773 // Special handling for extended integers.
774 if (SrcVT != DstVT) {
775 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
778 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
781 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
783 if (SrcVT == MVT::i1) {
784 if (Outs[0].Flags.isSExt())
786 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
789 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
791 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
792 SrcReg, /*TODO: Kill=*/false);
796 unsigned DstReg = VA.getLocReg();
797 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
798 // Avoid a cross-class copy. This is very unlikely.
799 if (!SrcRC->contains(DstReg))
801 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
802 DstReg).addReg(SrcReg);
804 // Add register to return instruction.
805 RetRegs.push_back(VA.getLocReg());
808 // The x86-64 ABI for returning structs by value requires that we copy
809 // the sret argument into %rax for the return. We saved the argument into
810 // a virtual register in the entry block, so now we copy the value out
811 // and into %rax. We also do the same with %eax for Win32.
812 if (F.hasStructRetAttr() &&
813 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
814 unsigned Reg = X86MFInfo->getSRetReturnReg();
816 "SRetReturnReg should have been set in LowerFormalArguments()!");
817 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
818 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
820 RetRegs.push_back(RetReg);
824 MachineInstrBuilder MIB =
825 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
826 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
827 MIB.addReg(RetRegs[i], RegState::Implicit);
831 /// X86SelectLoad - Select and emit code to implement load instructions.
833 bool X86FastISel::X86SelectLoad(const Instruction *I) {
834 // Atomic loads need special handling.
835 if (cast<LoadInst>(I)->isAtomic())
839 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
843 if (!X86SelectAddress(I->getOperand(0), AM))
846 unsigned ResultReg = 0;
847 if (X86FastEmitLoad(VT, AM, ResultReg)) {
848 UpdateValueMap(I, ResultReg);
854 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
855 bool HasAVX = Subtarget->hasAVX();
856 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
857 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
859 switch (VT.getSimpleVT().SimpleTy) {
861 case MVT::i8: return X86::CMP8rr;
862 case MVT::i16: return X86::CMP16rr;
863 case MVT::i32: return X86::CMP32rr;
864 case MVT::i64: return X86::CMP64rr;
866 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
868 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
872 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
873 /// of the comparison, return an opcode that works for the compare (e.g.
874 /// CMP32ri) otherwise return 0.
875 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
876 switch (VT.getSimpleVT().SimpleTy) {
877 // Otherwise, we can't fold the immediate into this comparison.
879 case MVT::i8: return X86::CMP8ri;
880 case MVT::i16: return X86::CMP16ri;
881 case MVT::i32: return X86::CMP32ri;
883 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
885 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
886 return X86::CMP64ri32;
891 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
893 unsigned Op0Reg = getRegForValue(Op0);
894 if (Op0Reg == 0) return false;
896 // Handle 'null' like i32/i64 0.
897 if (isa<ConstantPointerNull>(Op1))
898 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
900 // We have two options: compare with register or immediate. If the RHS of
901 // the compare is an immediate that we can fold into this compare, use
902 // CMPri, otherwise use CMPrr.
903 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
904 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
905 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
907 .addImm(Op1C->getSExtValue());
912 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
913 if (CompareOpc == 0) return false;
915 unsigned Op1Reg = getRegForValue(Op1);
916 if (Op1Reg == 0) return false;
917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
924 bool X86FastISel::X86SelectCmp(const Instruction *I) {
925 const CmpInst *CI = cast<CmpInst>(I);
928 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
931 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
933 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
934 switch (CI->getPredicate()) {
935 case CmpInst::FCMP_OEQ: {
936 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
939 unsigned EReg = createResultReg(&X86::GR8RegClass);
940 unsigned NPReg = createResultReg(&X86::GR8RegClass);
941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
942 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
943 TII.get(X86::SETNPr), NPReg);
944 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
945 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
946 UpdateValueMap(I, ResultReg);
949 case CmpInst::FCMP_UNE: {
950 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
953 unsigned NEReg = createResultReg(&X86::GR8RegClass);
954 unsigned PReg = createResultReg(&X86::GR8RegClass);
955 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
958 .addReg(PReg).addReg(NEReg);
959 UpdateValueMap(I, ResultReg);
962 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
963 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
964 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
965 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
966 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
967 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
968 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
969 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
970 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
971 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
972 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
973 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
975 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
976 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
977 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
978 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
979 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
980 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
981 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
982 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
983 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
984 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
989 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
993 // Emit a compare of Op0/Op1.
994 if (!X86FastEmitCompare(Op0, Op1, VT))
997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
998 UpdateValueMap(I, ResultReg);
1002 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1003 EVT DstVT = TLI.getValueType(I->getType());
1004 if (!TLI.isTypeLegal(DstVT))
1007 unsigned ResultReg = getRegForValue(I->getOperand(0));
1011 // Handle zero-extension from i1 to i8, which is common.
1012 MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()).getSimpleVT();
1013 if (SrcVT.SimpleTy == MVT::i1) {
1014 // Set the high bits to zero.
1015 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1022 if (DstVT == MVT::i64) {
1023 // Handle extension to 64-bits via sub-register shenanigans.
1026 switch (SrcVT.SimpleTy) {
1027 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1028 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1029 case MVT::i32: MovInst = X86::MOV32rr; break;
1030 default: llvm_unreachable("Unexpected zext to i64 source type");
1033 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1034 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32)
1037 ResultReg = createResultReg(&X86::GR64RegClass);
1038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG),
1040 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1041 } else if (DstVT != MVT::i8) {
1042 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1043 ResultReg, /*Kill=*/true);
1048 UpdateValueMap(I, ResultReg);
1053 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1054 // Unconditional branches are selected by tablegen-generated code.
1055 // Handle a conditional branch.
1056 const BranchInst *BI = cast<BranchInst>(I);
1057 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1058 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1060 // Fold the common case of a conditional branch with a comparison
1061 // in the same block (values defined on other blocks may not have
1062 // initialized registers).
1063 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1064 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1065 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1067 // Try to take advantage of fallthrough opportunities.
1068 CmpInst::Predicate Predicate = CI->getPredicate();
1069 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1070 std::swap(TrueMBB, FalseMBB);
1071 Predicate = CmpInst::getInversePredicate(Predicate);
1074 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1075 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1077 switch (Predicate) {
1078 case CmpInst::FCMP_OEQ:
1079 std::swap(TrueMBB, FalseMBB);
1080 Predicate = CmpInst::FCMP_UNE;
1082 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1083 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1084 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1085 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1086 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1087 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1088 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1089 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1090 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1091 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1092 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1093 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1094 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1096 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1097 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1098 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1099 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1100 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1101 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1102 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1103 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1104 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1105 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1110 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1112 std::swap(Op0, Op1);
1114 // Emit a compare of the LHS and RHS, setting the flags.
1115 if (!X86FastEmitCompare(Op0, Op1, VT))
1118 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1121 if (Predicate == CmpInst::FCMP_UNE) {
1122 // X86 requires a second branch to handle UNE (and OEQ,
1123 // which is mapped to UNE above).
1124 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1128 FastEmitBranch(FalseMBB, DL);
1129 FuncInfo.MBB->addSuccessor(TrueMBB);
1132 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1133 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1134 // typically happen for _Bool and C++ bools.
1136 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1137 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1138 unsigned TestOpc = 0;
1139 switch (SourceVT.SimpleTy) {
1141 case MVT::i8: TestOpc = X86::TEST8ri; break;
1142 case MVT::i16: TestOpc = X86::TEST16ri; break;
1143 case MVT::i32: TestOpc = X86::TEST32ri; break;
1144 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1147 unsigned OpReg = getRegForValue(TI->getOperand(0));
1148 if (OpReg == 0) return false;
1149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1150 .addReg(OpReg).addImm(1);
1152 unsigned JmpOpc = X86::JNE_4;
1153 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1154 std::swap(TrueMBB, FalseMBB);
1158 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1160 FastEmitBranch(FalseMBB, DL);
1161 FuncInfo.MBB->addSuccessor(TrueMBB);
1167 // Otherwise do a clumsy setcc and re-test it.
1168 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1169 // in an explicit cast, so make sure to handle that correctly.
1170 unsigned OpReg = getRegForValue(BI->getCondition());
1171 if (OpReg == 0) return false;
1173 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1174 .addReg(OpReg).addImm(1);
1175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1177 FastEmitBranch(FalseMBB, DL);
1178 FuncInfo.MBB->addSuccessor(TrueMBB);
1182 bool X86FastISel::X86SelectShift(const Instruction *I) {
1183 unsigned CReg = 0, OpReg = 0;
1184 const TargetRegisterClass *RC = NULL;
1185 if (I->getType()->isIntegerTy(8)) {
1187 RC = &X86::GR8RegClass;
1188 switch (I->getOpcode()) {
1189 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1190 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1191 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1192 default: return false;
1194 } else if (I->getType()->isIntegerTy(16)) {
1196 RC = &X86::GR16RegClass;
1197 switch (I->getOpcode()) {
1198 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1199 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1200 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1201 default: return false;
1203 } else if (I->getType()->isIntegerTy(32)) {
1205 RC = &X86::GR32RegClass;
1206 switch (I->getOpcode()) {
1207 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1208 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1209 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1210 default: return false;
1212 } else if (I->getType()->isIntegerTy(64)) {
1214 RC = &X86::GR64RegClass;
1215 switch (I->getOpcode()) {
1216 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1217 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1218 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1219 default: return false;
1226 if (!isTypeLegal(I->getType(), VT))
1229 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1230 if (Op0Reg == 0) return false;
1232 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1233 if (Op1Reg == 0) return false;
1234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1235 CReg).addReg(Op1Reg);
1237 // The shift instruction uses X86::CL. If we defined a super-register
1238 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1239 if (CReg != X86::CL)
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1241 TII.get(TargetOpcode::KILL), X86::CL)
1242 .addReg(CReg, RegState::Kill);
1244 unsigned ResultReg = createResultReg(RC);
1245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1247 UpdateValueMap(I, ResultReg);
1251 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1252 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1253 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1254 const static bool S = true; // IsSigned
1255 const static bool U = false; // !IsSigned
1256 const static unsigned Copy = TargetOpcode::COPY;
1257 // For the X86 DIV/IDIV instruction, in most cases the dividend
1258 // (numerator) must be in a specific register pair highreg:lowreg,
1259 // producing the quotient in lowreg and the remainder in highreg.
1260 // For most data types, to set up the instruction, the dividend is
1261 // copied into lowreg, and lowreg is sign-extended or zero-extended
1262 // into highreg. The exception is i8, where the dividend is defined
1263 // as a single register rather than a register pair, and we
1264 // therefore directly sign-extend or zero-extend the dividend into
1265 // lowreg, instead of copying, and ignore the highreg.
1266 const static struct DivRemEntry {
1267 // The following portion depends only on the data type.
1268 const TargetRegisterClass *RC;
1269 unsigned LowInReg; // low part of the register pair
1270 unsigned HighInReg; // high part of the register pair
1271 // The following portion depends on both the data type and the operation.
1272 struct DivRemResult {
1273 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1274 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1275 // highreg, or copying a zero into highreg.
1276 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1277 // zero/sign-extending into lowreg for i8.
1278 unsigned DivRemResultReg; // Register containing the desired result.
1279 bool IsOpSigned; // Whether to use signed or unsigned form.
1280 } ResultTable[NumOps];
1281 } OpTable[NumTypes] = {
1282 { &X86::GR8RegClass, X86::AX, 0, {
1283 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1284 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1285 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1286 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1289 { &X86::GR16RegClass, X86::AX, X86::DX, {
1290 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1291 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1292 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1293 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1296 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1297 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1298 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1299 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1300 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1303 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1304 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1305 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1306 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1307 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1313 if (!isTypeLegal(I->getType(), VT))
1316 unsigned TypeIndex, OpIndex;
1317 switch (VT.SimpleTy) {
1318 default: return false;
1319 case MVT::i8: TypeIndex = 0; break;
1320 case MVT::i16: TypeIndex = 1; break;
1321 case MVT::i32: TypeIndex = 2; break;
1322 case MVT::i64: TypeIndex = 3;
1323 if (!Subtarget->is64Bit())
1328 switch (I->getOpcode()) {
1329 default: llvm_unreachable("Unexpected div/rem opcode");
1330 case Instruction::SDiv: OpIndex = 0; break;
1331 case Instruction::SRem: OpIndex = 1; break;
1332 case Instruction::UDiv: OpIndex = 2; break;
1333 case Instruction::URem: OpIndex = 3; break;
1336 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1337 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1338 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1341 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1345 // Move op0 into low-order input register.
1346 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1347 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1348 // Zero-extend or sign-extend into high-order input register.
1349 if (OpEntry.OpSignExtend) {
1350 if (OpEntry.IsOpSigned)
1351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1352 TII.get(OpEntry.OpSignExtend));
1354 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1355 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1356 TII.get(X86::MOV32r0), Zero32);
1358 // Copy the zero into the appropriate sub/super/identical physical
1359 // register. Unfortunately the operations needed are not uniform enough to
1360 // fit neatly into the table above.
1361 if (VT.SimpleTy == MVT::i16) {
1362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1363 TII.get(Copy), TypeEntry.HighInReg)
1364 .addReg(Zero32, 0, X86::sub_16bit);
1365 } else if (VT.SimpleTy == MVT::i32) {
1366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1367 TII.get(Copy), TypeEntry.HighInReg)
1369 } else if (VT.SimpleTy == MVT::i64) {
1370 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1371 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1372 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1376 // Generate the DIV/IDIV instruction.
1377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1378 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1379 // Copy output register into result register.
1380 unsigned ResultReg = createResultReg(TypeEntry.RC);
1381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1382 TII.get(Copy), ResultReg).addReg(OpEntry.DivRemResultReg);
1383 UpdateValueMap(I, ResultReg);
1388 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1390 if (!isTypeLegal(I->getType(), VT))
1393 // We only use cmov here, if we don't have a cmov instruction bail.
1394 if (!Subtarget->hasCMov()) return false;
1397 const TargetRegisterClass *RC = NULL;
1398 if (VT == MVT::i16) {
1399 Opc = X86::CMOVE16rr;
1400 RC = &X86::GR16RegClass;
1401 } else if (VT == MVT::i32) {
1402 Opc = X86::CMOVE32rr;
1403 RC = &X86::GR32RegClass;
1404 } else if (VT == MVT::i64) {
1405 Opc = X86::CMOVE64rr;
1406 RC = &X86::GR64RegClass;
1411 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1412 if (Op0Reg == 0) return false;
1413 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1414 if (Op1Reg == 0) return false;
1415 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1416 if (Op2Reg == 0) return false;
1418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1419 .addReg(Op0Reg).addReg(Op0Reg);
1420 unsigned ResultReg = createResultReg(RC);
1421 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1422 .addReg(Op1Reg).addReg(Op2Reg);
1423 UpdateValueMap(I, ResultReg);
1427 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1428 // fpext from float to double.
1429 if (X86ScalarSSEf64 &&
1430 I->getType()->isDoubleTy()) {
1431 const Value *V = I->getOperand(0);
1432 if (V->getType()->isFloatTy()) {
1433 unsigned OpReg = getRegForValue(V);
1434 if (OpReg == 0) return false;
1435 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1437 TII.get(X86::CVTSS2SDrr), ResultReg)
1439 UpdateValueMap(I, ResultReg);
1447 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1448 if (X86ScalarSSEf64) {
1449 if (I->getType()->isFloatTy()) {
1450 const Value *V = I->getOperand(0);
1451 if (V->getType()->isDoubleTy()) {
1452 unsigned OpReg = getRegForValue(V);
1453 if (OpReg == 0) return false;
1454 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1455 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1456 TII.get(X86::CVTSD2SSrr), ResultReg)
1458 UpdateValueMap(I, ResultReg);
1467 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1468 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1469 EVT DstVT = TLI.getValueType(I->getType());
1471 // This code only handles truncation to byte.
1472 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1474 if (!TLI.isTypeLegal(SrcVT))
1477 unsigned InputReg = getRegForValue(I->getOperand(0));
1479 // Unhandled operand. Halt "fast" selection and bail.
1482 if (SrcVT == MVT::i8) {
1483 // Truncate from i8 to i1; no code needed.
1484 UpdateValueMap(I, InputReg);
1488 if (!Subtarget->is64Bit()) {
1489 // If we're on x86-32; we can't extract an i8 from a general register.
1490 // First issue a copy to GR16_ABCD or GR32_ABCD.
1491 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1492 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1493 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1494 unsigned CopyReg = createResultReg(CopyRC);
1495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1496 CopyReg).addReg(InputReg);
1500 // Issue an extract_subreg.
1501 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1502 InputReg, /*Kill=*/true,
1507 UpdateValueMap(I, ResultReg);
1511 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1512 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1515 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1516 X86AddressMode SrcAM, uint64_t Len) {
1518 // Make sure we don't bloat code by inlining very large memcpy's.
1519 if (!IsMemcpySmall(Len))
1522 bool i64Legal = Subtarget->is64Bit();
1524 // We don't care about alignment here since we just emit integer accesses.
1527 if (Len >= 8 && i64Legal)
1538 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1539 RV &= X86FastEmitStore(VT, Reg, DestAM);
1540 assert(RV && "Failed to emit load or store??");
1542 unsigned Size = VT.getSizeInBits()/8;
1544 DestAM.Disp += Size;
1551 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1552 // FIXME: Handle more intrinsics.
1553 switch (I.getIntrinsicID()) {
1554 default: return false;
1555 case Intrinsic::memcpy: {
1556 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1557 // Don't handle volatile or variable length memcpys.
1558 if (MCI.isVolatile())
1561 if (isa<ConstantInt>(MCI.getLength())) {
1562 // Small memcpy's are common enough that we want to do them
1563 // without a call if possible.
1564 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1565 if (IsMemcpySmall(Len)) {
1566 X86AddressMode DestAM, SrcAM;
1567 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1568 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1570 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1575 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1576 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1579 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1582 return DoSelectCall(&I, "memcpy");
1584 case Intrinsic::memset: {
1585 const MemSetInst &MSI = cast<MemSetInst>(I);
1587 if (MSI.isVolatile())
1590 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1591 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1594 if (MSI.getDestAddressSpace() > 255)
1597 return DoSelectCall(&I, "memset");
1599 case Intrinsic::stackprotector: {
1600 // Emit code to store the stack guard onto the stack.
1601 EVT PtrTy = TLI.getPointerTy();
1603 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1604 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1606 // Grab the frame index.
1608 if (!X86SelectAddress(Slot, AM)) return false;
1609 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1612 case Intrinsic::dbg_declare: {
1613 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1615 assert(DI->getAddress() && "Null address should be checked earlier!");
1616 if (!X86SelectAddress(DI->getAddress(), AM))
1618 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1619 // FIXME may need to add RegState::Debug to any registers produced,
1620 // although ESP/EBP should be the only ones at the moment.
1621 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1622 addImm(0).addMetadata(DI->getVariable());
1625 case Intrinsic::trap: {
1626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1629 case Intrinsic::sadd_with_overflow:
1630 case Intrinsic::uadd_with_overflow: {
1631 // FIXME: Should fold immediates.
1633 // Replace "add with overflow" intrinsics with an "add" instruction followed
1634 // by a seto/setc instruction.
1635 const Function *Callee = I.getCalledFunction();
1637 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1640 if (!isTypeLegal(RetTy, VT))
1643 const Value *Op1 = I.getArgOperand(0);
1644 const Value *Op2 = I.getArgOperand(1);
1645 unsigned Reg1 = getRegForValue(Op1);
1646 unsigned Reg2 = getRegForValue(Op2);
1648 if (Reg1 == 0 || Reg2 == 0)
1649 // FIXME: Handle values *not* in registers.
1655 else if (VT == MVT::i64)
1660 // The call to CreateRegs builds two sequential registers, to store the
1661 // both the returned values.
1662 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1664 .addReg(Reg1).addReg(Reg2);
1666 unsigned Opc = X86::SETBr;
1667 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1671 UpdateValueMap(&I, ResultReg, 2);
1677 bool X86FastISel::FastLowerArguments() {
1678 if (!FuncInfo.CanLowerReturn)
1681 if (Subtarget->isTargetWin64())
1684 const Function *F = FuncInfo.Fn;
1688 CallingConv::ID CC = F->getCallingConv();
1689 if (CC != CallingConv::C)
1692 if (!Subtarget->is64Bit())
1695 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1697 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1698 I != E; ++I, ++Idx) {
1702 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1703 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1704 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1705 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1708 Type *ArgTy = I->getType();
1709 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1712 EVT ArgVT = TLI.getValueType(ArgTy);
1713 if (!ArgVT.isSimple()) return false;
1714 switch (ArgVT.getSimpleVT().SimpleTy) {
1723 static const uint16_t GPR32ArgRegs[] = {
1724 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1726 static const uint16_t GPR64ArgRegs[] = {
1727 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1731 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1732 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1733 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1734 I != E; ++I, ++Idx) {
1737 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1738 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1739 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1740 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1741 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1742 // Without this, EmitLiveInCopies may eliminate the livein if its only
1743 // use is a bitcast (which isn't turned into an instruction).
1744 unsigned ResultReg = createResultReg(RC);
1745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1746 ResultReg).addReg(DstReg, getKillRegState(true));
1747 UpdateValueMap(I, ResultReg);
1752 bool X86FastISel::X86SelectCall(const Instruction *I) {
1753 const CallInst *CI = cast<CallInst>(I);
1754 const Value *Callee = CI->getCalledValue();
1756 // Can't handle inline asm yet.
1757 if (isa<InlineAsm>(Callee))
1760 // Handle intrinsic calls.
1761 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1762 return X86VisitIntrinsicCall(*II);
1764 // Allow SelectionDAG isel to handle tail calls.
1765 if (cast<CallInst>(I)->isTailCall())
1768 return DoSelectCall(I, 0);
1771 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1772 const ImmutableCallSite &CS) {
1773 if (Subtarget.is64Bit())
1775 if (Subtarget.isTargetWindows())
1777 CallingConv::ID CC = CS.getCallingConv();
1778 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1780 if (!CS.paramHasAttr(1, Attribute::StructRet))
1782 if (CS.paramHasAttr(1, Attribute::InReg))
1787 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1788 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1789 const CallInst *CI = cast<CallInst>(I);
1790 const Value *Callee = CI->getCalledValue();
1792 // Handle only C and fastcc calling conventions for now.
1793 ImmutableCallSite CS(CI);
1794 CallingConv::ID CC = CS.getCallingConv();
1795 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1796 CC != CallingConv::X86_FastCall)
1799 // fastcc with -tailcallopt is intended to provide a guaranteed
1800 // tail call optimization. Fastisel doesn't know how to do that.
1801 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1804 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1805 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1806 bool isVarArg = FTy->isVarArg();
1808 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1809 // x86-32. Special handling for x86-64 is implemented.
1810 if (isVarArg && Subtarget->isTargetWin64())
1813 // Fast-isel doesn't know about callee-pop yet.
1814 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1815 TM.Options.GuaranteedTailCallOpt))
1818 // Check whether the function can return without sret-demotion.
1819 SmallVector<ISD::OutputArg, 4> Outs;
1820 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1821 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1822 *FuncInfo.MF, FTy->isVarArg(),
1823 Outs, FTy->getContext());
1824 if (!CanLowerReturn)
1827 // Materialize callee address in a register. FIXME: GV address can be
1828 // handled with a CALLpcrel32 instead.
1829 X86AddressMode CalleeAM;
1830 if (!X86SelectCallAddress(Callee, CalleeAM))
1832 unsigned CalleeOp = 0;
1833 const GlobalValue *GV = 0;
1834 if (CalleeAM.GV != 0) {
1836 } else if (CalleeAM.Base.Reg != 0) {
1837 CalleeOp = CalleeAM.Base.Reg;
1841 // Deal with call operands first.
1842 SmallVector<const Value *, 8> ArgVals;
1843 SmallVector<unsigned, 8> Args;
1844 SmallVector<MVT, 8> ArgVTs;
1845 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1846 unsigned arg_size = CS.arg_size();
1847 Args.reserve(arg_size);
1848 ArgVals.reserve(arg_size);
1849 ArgVTs.reserve(arg_size);
1850 ArgFlags.reserve(arg_size);
1851 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1853 // If we're lowering a mem intrinsic instead of a regular call, skip the
1854 // last two arguments, which should not passed to the underlying functions.
1855 if (MemIntName && e-i <= 2)
1858 ISD::ArgFlagsTy Flags;
1859 unsigned AttrInd = i - CS.arg_begin() + 1;
1860 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1862 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1865 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1866 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1867 Type *ElementTy = Ty->getElementType();
1868 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1869 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1871 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1873 Flags.setByValSize(FrameSize);
1874 Flags.setByValAlign(FrameAlign);
1875 if (!IsMemcpySmall(FrameSize))
1879 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1881 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1884 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1885 // instruction. This is safe because it is common to all fastisel supported
1886 // calling conventions on x86.
1887 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1888 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1889 CI->getBitWidth() == 16) {
1891 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1893 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1899 // Passing bools around ends up doing a trunc to i1 and passing it.
1900 // Codegen this as an argument + "and 1".
1901 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1902 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1903 ArgVal->hasOneUse()) {
1904 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1905 ArgReg = getRegForValue(ArgVal);
1906 if (ArgReg == 0) return false;
1909 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1911 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1912 ArgVal->hasOneUse(), 1);
1914 ArgReg = getRegForValue(ArgVal);
1917 if (ArgReg == 0) return false;
1919 Type *ArgTy = ArgVal->getType();
1921 if (!isTypeLegal(ArgTy, ArgVT))
1923 if (ArgVT == MVT::x86mmx)
1925 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1926 Flags.setOrigAlign(OriginalAlignment);
1928 Args.push_back(ArgReg);
1929 ArgVals.push_back(ArgVal);
1930 ArgVTs.push_back(ArgVT);
1931 ArgFlags.push_back(Flags);
1934 // Analyze operands of the call, assigning locations to each operand.
1935 SmallVector<CCValAssign, 16> ArgLocs;
1936 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1937 I->getParent()->getContext());
1939 // Allocate shadow area for Win64
1940 if (Subtarget->isTargetWin64())
1941 CCInfo.AllocateStack(32, 8);
1943 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1945 // Get a count of how many bytes are to be pushed on the stack.
1946 unsigned NumBytes = CCInfo.getNextStackOffset();
1948 // Issue CALLSEQ_START
1949 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1950 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1953 // Process argument: walk the register/memloc assignments, inserting
1955 SmallVector<unsigned, 4> RegArgs;
1956 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1957 CCValAssign &VA = ArgLocs[i];
1958 unsigned Arg = Args[VA.getValNo()];
1959 EVT ArgVT = ArgVTs[VA.getValNo()];
1961 // Promote the value if needed.
1962 switch (VA.getLocInfo()) {
1963 case CCValAssign::Full: break;
1964 case CCValAssign::SExt: {
1965 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1966 "Unexpected extend");
1967 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1969 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1970 ArgVT = VA.getLocVT();
1973 case CCValAssign::ZExt: {
1974 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1975 "Unexpected extend");
1976 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1978 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1979 ArgVT = VA.getLocVT();
1982 case CCValAssign::AExt: {
1983 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1984 "Unexpected extend");
1985 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1988 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1991 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1994 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1995 ArgVT = VA.getLocVT();
1998 case CCValAssign::BCvt: {
1999 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2000 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2001 assert(BC != 0 && "Failed to emit a bitcast!");
2003 ArgVT = VA.getLocVT();
2006 case CCValAssign::VExt:
2007 // VExt has not been implemented, so this should be impossible to reach
2008 // for now. However, fallback to Selection DAG isel once implemented.
2010 case CCValAssign::Indirect:
2011 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2016 if (VA.isRegLoc()) {
2017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2018 VA.getLocReg()).addReg(Arg);
2019 RegArgs.push_back(VA.getLocReg());
2021 unsigned LocMemOffset = VA.getLocMemOffset();
2023 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2024 getTargetMachine()->getRegisterInfo());
2025 AM.Base.Reg = RegInfo->getStackRegister();
2026 AM.Disp = LocMemOffset;
2027 const Value *ArgVal = ArgVals[VA.getValNo()];
2028 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2030 if (Flags.isByVal()) {
2031 X86AddressMode SrcAM;
2032 SrcAM.Base.Reg = Arg;
2033 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2034 assert(Res && "memcpy length already checked!"); (void)Res;
2035 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2036 // If this is a really simple value, emit this with the Value* version
2037 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2038 // as it can cause us to reevaluate the argument.
2039 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2042 if (!X86FastEmitStore(ArgVT, Arg, AM))
2048 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2050 if (Subtarget->isPICStyleGOT()) {
2051 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2052 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2053 X86::EBX).addReg(Base);
2056 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
2057 // Count the number of XMM registers allocated.
2058 static const uint16_t XMMArgRegs[] = {
2059 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2060 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2062 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2064 X86::AL).addImm(NumXMMRegs);
2068 MachineInstrBuilder MIB;
2070 // Register-indirect call.
2072 if (Subtarget->is64Bit())
2073 CallOpc = X86::CALL64r;
2075 CallOpc = X86::CALL32r;
2076 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2081 assert(GV && "Not a direct call");
2083 if (Subtarget->is64Bit())
2084 CallOpc = X86::CALL64pcrel32;
2086 CallOpc = X86::CALLpcrel32;
2088 // See if we need any target-specific flags on the GV operand.
2089 unsigned char OpFlags = 0;
2091 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2092 // external symbols most go through the PLT in PIC mode. If the symbol
2093 // has hidden or protected visibility, or if it is static or local, then
2094 // we don't need to use the PLT - we can directly call it.
2095 if (Subtarget->isTargetELF() &&
2096 TM.getRelocationModel() == Reloc::PIC_ &&
2097 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2098 OpFlags = X86II::MO_PLT;
2099 } else if (Subtarget->isPICStyleStubAny() &&
2100 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2101 (!Subtarget->getTargetTriple().isMacOSX() ||
2102 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2103 // PC-relative references to external symbols should go through $stub,
2104 // unless we're building with the leopard linker or later, which
2105 // automatically synthesizes these stubs.
2106 OpFlags = X86II::MO_DARWIN_STUB;
2110 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2112 MIB.addExternalSymbol(MemIntName, OpFlags);
2114 MIB.addGlobalAddress(GV, 0, OpFlags);
2117 // Add a register mask with the call-preserved registers.
2118 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2119 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2121 // Add an implicit use GOT pointer in EBX.
2122 if (Subtarget->isPICStyleGOT())
2123 MIB.addReg(X86::EBX, RegState::Implicit);
2125 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
2126 MIB.addReg(X86::AL, RegState::Implicit);
2128 // Add implicit physical register uses to the call.
2129 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2130 MIB.addReg(RegArgs[i], RegState::Implicit);
2132 // Issue CALLSEQ_END
2133 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2134 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2135 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2136 .addImm(NumBytes).addImm(NumBytesCallee);
2138 // Build info for return calling conv lowering code.
2139 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2140 SmallVector<ISD::InputArg, 32> Ins;
2141 SmallVector<EVT, 4> RetTys;
2142 ComputeValueVTs(TLI, I->getType(), RetTys);
2143 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2145 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2146 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2147 for (unsigned j = 0; j != NumRegs; ++j) {
2148 ISD::InputArg MyFlags;
2149 MyFlags.VT = RegisterVT;
2150 MyFlags.Used = !CS.getInstruction()->use_empty();
2151 if (CS.paramHasAttr(0, Attribute::SExt))
2152 MyFlags.Flags.setSExt();
2153 if (CS.paramHasAttr(0, Attribute::ZExt))
2154 MyFlags.Flags.setZExt();
2155 if (CS.paramHasAttr(0, Attribute::InReg))
2156 MyFlags.Flags.setInReg();
2157 Ins.push_back(MyFlags);
2161 // Now handle call return values.
2162 SmallVector<unsigned, 4> UsedRegs;
2163 SmallVector<CCValAssign, 16> RVLocs;
2164 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2165 I->getParent()->getContext());
2166 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2167 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2168 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2169 EVT CopyVT = RVLocs[i].getValVT();
2170 unsigned CopyReg = ResultReg + i;
2172 // If this is a call to a function that returns an fp value on the x87 fp
2173 // stack, but where we prefer to use the value in xmm registers, copy it
2174 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2175 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2176 RVLocs[i].getLocReg() == X86::ST1)) {
2177 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2179 CopyReg = createResultReg(&X86::RFP80RegClass);
2181 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2184 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2185 CopyReg).addReg(RVLocs[i].getLocReg());
2186 UsedRegs.push_back(RVLocs[i].getLocReg());
2189 if (CopyVT != RVLocs[i].getValVT()) {
2190 // Round the F80 the right size, which also moves to the appropriate xmm
2191 // register. This is accomplished by storing the F80 value in memory and
2192 // then loading it back. Ewww...
2193 EVT ResVT = RVLocs[i].getValVT();
2194 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2195 unsigned MemSize = ResVT.getSizeInBits()/8;
2196 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2197 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2200 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2201 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2202 TII.get(Opc), ResultReg + i), FI);
2207 UpdateValueMap(I, ResultReg, RVLocs.size());
2209 // Set all unused physreg defs as dead.
2210 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2217 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2218 switch (I->getOpcode()) {
2220 case Instruction::Load:
2221 return X86SelectLoad(I);
2222 case Instruction::Store:
2223 return X86SelectStore(I);
2224 case Instruction::Ret:
2225 return X86SelectRet(I);
2226 case Instruction::ICmp:
2227 case Instruction::FCmp:
2228 return X86SelectCmp(I);
2229 case Instruction::ZExt:
2230 return X86SelectZExt(I);
2231 case Instruction::Br:
2232 return X86SelectBranch(I);
2233 case Instruction::Call:
2234 return X86SelectCall(I);
2235 case Instruction::LShr:
2236 case Instruction::AShr:
2237 case Instruction::Shl:
2238 return X86SelectShift(I);
2239 case Instruction::SDiv:
2240 case Instruction::UDiv:
2241 case Instruction::SRem:
2242 case Instruction::URem:
2243 return X86SelectDivRem(I);
2244 case Instruction::Select:
2245 return X86SelectSelect(I);
2246 case Instruction::Trunc:
2247 return X86SelectTrunc(I);
2248 case Instruction::FPExt:
2249 return X86SelectFPExt(I);
2250 case Instruction::FPTrunc:
2251 return X86SelectFPTrunc(I);
2252 case Instruction::IntToPtr: // Deliberate fall-through.
2253 case Instruction::PtrToInt: {
2254 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2255 EVT DstVT = TLI.getValueType(I->getType());
2256 if (DstVT.bitsGT(SrcVT))
2257 return X86SelectZExt(I);
2258 if (DstVT.bitsLT(SrcVT))
2259 return X86SelectTrunc(I);
2260 unsigned Reg = getRegForValue(I->getOperand(0));
2261 if (Reg == 0) return false;
2262 UpdateValueMap(I, Reg);
2270 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2272 if (!isTypeLegal(C->getType(), VT))
2275 // Can't handle alternate code models yet.
2276 if (TM.getCodeModel() != CodeModel::Small)
2279 // Get opcode and regclass of the output for the given load instruction.
2281 const TargetRegisterClass *RC = NULL;
2282 switch (VT.SimpleTy) {
2286 RC = &X86::GR8RegClass;
2290 RC = &X86::GR16RegClass;
2294 RC = &X86::GR32RegClass;
2297 // Must be in x86-64 mode.
2299 RC = &X86::GR64RegClass;
2302 if (X86ScalarSSEf32) {
2303 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2304 RC = &X86::FR32RegClass;
2306 Opc = X86::LD_Fp32m;
2307 RC = &X86::RFP32RegClass;
2311 if (X86ScalarSSEf64) {
2312 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2313 RC = &X86::FR64RegClass;
2315 Opc = X86::LD_Fp64m;
2316 RC = &X86::RFP64RegClass;
2320 // No f80 support yet.
2324 // Materialize addresses with LEA instructions.
2325 if (isa<GlobalValue>(C)) {
2327 if (X86SelectAddress(C, AM)) {
2328 // If the expression is just a basereg, then we're done, otherwise we need
2330 if (AM.BaseType == X86AddressMode::RegBase &&
2331 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2334 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2335 unsigned ResultReg = createResultReg(RC);
2336 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2337 TII.get(Opc), ResultReg), AM);
2343 // MachineConstantPool wants an explicit alignment.
2344 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2346 // Alignment of vector types. FIXME!
2347 Align = TD.getTypeAllocSize(C->getType());
2350 // x86-32 PIC requires a PIC base register for constant pools.
2351 unsigned PICBase = 0;
2352 unsigned char OpFlag = 0;
2353 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2354 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2355 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2356 } else if (Subtarget->isPICStyleGOT()) {
2357 OpFlag = X86II::MO_GOTOFF;
2358 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2359 } else if (Subtarget->isPICStyleRIPRel() &&
2360 TM.getCodeModel() == CodeModel::Small) {
2364 // Create the load from the constant pool.
2365 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2366 unsigned ResultReg = createResultReg(RC);
2367 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2368 TII.get(Opc), ResultReg),
2369 MCPOffset, PICBase, OpFlag);
2374 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2375 // Fail on dynamic allocas. At this point, getRegForValue has already
2376 // checked its CSE maps, so if we're here trying to handle a dynamic
2377 // alloca, we're not going to succeed. X86SelectAddress has a
2378 // check for dynamic allocas, because it's called directly from
2379 // various places, but TargetMaterializeAlloca also needs a check
2380 // in order to avoid recursion between getRegForValue,
2381 // X86SelectAddrss, and TargetMaterializeAlloca.
2382 if (!FuncInfo.StaticAllocaMap.count(C))
2386 if (!X86SelectAddress(C, AM))
2388 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2389 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2390 unsigned ResultReg = createResultReg(RC);
2391 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2392 TII.get(Opc), ResultReg), AM);
2396 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2398 if (!isTypeLegal(CF->getType(), VT))
2401 // Get opcode and regclass for the given zero.
2403 const TargetRegisterClass *RC = NULL;
2404 switch (VT.SimpleTy) {
2407 if (X86ScalarSSEf32) {
2408 Opc = X86::FsFLD0SS;
2409 RC = &X86::FR32RegClass;
2411 Opc = X86::LD_Fp032;
2412 RC = &X86::RFP32RegClass;
2416 if (X86ScalarSSEf64) {
2417 Opc = X86::FsFLD0SD;
2418 RC = &X86::FR64RegClass;
2420 Opc = X86::LD_Fp064;
2421 RC = &X86::RFP64RegClass;
2425 // No f80 support yet.
2429 unsigned ResultReg = createResultReg(RC);
2430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2435 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2436 const LoadInst *LI) {
2438 if (!X86SelectAddress(LI->getOperand(0), AM))
2441 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2443 unsigned Size = TD.getTypeAllocSize(LI->getType());
2444 unsigned Alignment = LI->getAlignment();
2446 SmallVector<MachineOperand, 8> AddrOps;
2447 AM.getFullAddress(AddrOps);
2449 MachineInstr *Result =
2450 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2451 if (Result == 0) return false;
2453 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2454 MI->eraseFromParent();
2460 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2461 const TargetLibraryInfo *libInfo) {
2462 return new X86FastISel(funcInfo, libInfo);