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 "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Operator.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FastISel.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/MachineConstantPool.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.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 /// StackPtr - Register used as the stack pointer.
52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
53 /// floating point ops.
54 /// When SSE is available, use it for f32 operations.
55 /// When SSE2 is available, use it for f64 operations.
60 explicit X86FastISel(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo) {
61 Subtarget = &TM.getSubtarget<X86Subtarget>();
62 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
63 X86ScalarSSEf64 = Subtarget->hasSSE2();
64 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 virtual bool TargetSelectInstruction(const Instruction *I);
69 /// TryToFoldLoad - 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 virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
76 #include "X86GenFastISel.inc"
79 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
81 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
83 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
84 bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
86 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
89 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
90 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
92 bool X86SelectLoad(const Instruction *I);
94 bool X86SelectStore(const Instruction *I);
96 bool X86SelectRet(const Instruction *I);
98 bool X86SelectCmp(const Instruction *I);
100 bool X86SelectZExt(const Instruction *I);
102 bool X86SelectBranch(const Instruction *I);
104 bool X86SelectShift(const Instruction *I);
106 bool X86SelectSelect(const Instruction *I);
108 bool X86SelectTrunc(const Instruction *I);
110 bool X86SelectFPExt(const Instruction *I);
111 bool X86SelectFPTrunc(const Instruction *I);
113 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
114 bool X86SelectCall(const Instruction *I);
116 bool DoSelectCall(const Instruction *I, const char *MemIntName);
118 const X86InstrInfo *getInstrInfo() const {
119 return getTargetMachine()->getInstrInfo();
121 const X86TargetMachine *getTargetMachine() const {
122 return static_cast<const X86TargetMachine *>(&TM);
125 unsigned TargetMaterializeConstant(const Constant *C);
127 unsigned TargetMaterializeAlloca(const AllocaInst *C);
129 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
131 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
132 /// computed in an SSE register, not on the X87 floating point stack.
133 bool isScalarFPTypeInSSEReg(EVT VT) const {
134 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
135 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
138 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
140 bool IsMemcpySmall(uint64_t Len);
142 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
143 X86AddressMode SrcAM, uint64_t Len);
146 } // end anonymous namespace.
148 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
149 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
150 if (evt == MVT::Other || !evt.isSimple())
151 // Unhandled type. Halt "fast" selection and bail.
154 VT = evt.getSimpleVT();
155 // For now, require SSE/SSE2 for performing floating-point operations,
156 // since x87 requires additional work.
157 if (VT == MVT::f64 && !X86ScalarSSEf64)
159 if (VT == MVT::f32 && !X86ScalarSSEf32)
161 // Similarly, no f80 support yet.
164 // We only handle legal types. For example, on x86-32 the instruction
165 // selector contains all of the 64-bit instructions from x86-64,
166 // under the assumption that i64 won't be used if the target doesn't
168 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
171 #include "X86GenCallingConv.inc"
173 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
174 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
175 /// Return true and the result register by reference if it is possible.
176 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
177 unsigned &ResultReg) {
178 // Get opcode and regclass of the output for the given load instruction.
180 const TargetRegisterClass *RC = NULL;
181 switch (VT.getSimpleVT().SimpleTy) {
182 default: return false;
186 RC = &X86::GR8RegClass;
190 RC = &X86::GR16RegClass;
194 RC = &X86::GR32RegClass;
197 // Must be in x86-64 mode.
199 RC = &X86::GR64RegClass;
202 if (X86ScalarSSEf32) {
203 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
204 RC = &X86::FR32RegClass;
207 RC = &X86::RFP32RegClass;
211 if (X86ScalarSSEf64) {
212 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
213 RC = &X86::FR64RegClass;
216 RC = &X86::RFP64RegClass;
220 // No f80 support yet.
224 ResultReg = createResultReg(RC);
225 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
226 DL, TII.get(Opc), ResultReg), AM);
230 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
231 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
232 /// and a displacement offset, or a GlobalAddress,
233 /// i.e. V. Return true if it is possible.
235 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
236 // Get opcode and regclass of the output for the given store instruction.
238 switch (VT.getSimpleVT().SimpleTy) {
239 case MVT::f80: // No f80 support yet.
240 default: return false;
242 // Mask out all but lowest bit.
243 unsigned AndResult = createResultReg(&X86::GR8RegClass);
244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
245 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
248 // FALLTHROUGH, handling i1 as i8.
249 case MVT::i8: Opc = X86::MOV8mr; break;
250 case MVT::i16: Opc = X86::MOV16mr; break;
251 case MVT::i32: Opc = X86::MOV32mr; break;
252 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
254 Opc = X86ScalarSSEf32 ?
255 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
258 Opc = X86ScalarSSEf64 ?
259 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
275 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
276 DL, TII.get(Opc)), AM).addReg(Val);
280 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
281 const X86AddressMode &AM) {
282 // Handle 'null' like i32/i64 0.
283 if (isa<ConstantPointerNull>(Val))
284 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
286 // If this is a store of a simple constant, fold the constant into the store.
287 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
290 switch (VT.getSimpleVT().SimpleTy) {
292 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
293 case MVT::i8: Opc = X86::MOV8mi; break;
294 case MVT::i16: Opc = X86::MOV16mi; break;
295 case MVT::i32: Opc = X86::MOV32mi; break;
297 // Must be a 32-bit sign extended value.
298 if ((int)CI->getSExtValue() == CI->getSExtValue())
299 Opc = X86::MOV64mi32;
304 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
305 DL, TII.get(Opc)), AM)
306 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
312 unsigned ValReg = getRegForValue(Val);
316 return X86FastEmitStore(VT, ValReg, AM);
319 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
320 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
321 /// ISD::SIGN_EXTEND).
322 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
323 unsigned Src, EVT SrcVT,
324 unsigned &ResultReg) {
325 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
326 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);
691 unsigned SABIAlignment =
692 TD.getABITypeAlignment(S->getValueOperand()->getType());
693 if (S->getAlignment() != 0 && S->getAlignment() < SABIAlignment)
697 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
701 if (!X86SelectAddress(I->getOperand(1), AM))
704 return X86FastEmitStore(VT, I->getOperand(0), AM);
707 /// X86SelectRet - Select and emit code to implement ret instructions.
708 bool X86FastISel::X86SelectRet(const Instruction *I) {
709 const ReturnInst *Ret = cast<ReturnInst>(I);
710 const Function &F = *I->getParent()->getParent();
712 if (!FuncInfo.CanLowerReturn)
715 CallingConv::ID CC = F.getCallingConv();
716 if (CC != CallingConv::C &&
717 CC != CallingConv::Fast &&
718 CC != CallingConv::X86_FastCall)
721 if (Subtarget->isTargetWin64())
724 // Don't handle popping bytes on return for now.
725 if (FuncInfo.MF->getInfo<X86MachineFunctionInfo>()
726 ->getBytesToPopOnReturn() != 0)
729 // fastcc with -tailcallopt is intended to provide a guaranteed
730 // tail call optimization. Fastisel doesn't know how to do that.
731 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
734 // Let SDISel handle vararg functions.
738 if (Ret->getNumOperands() > 0) {
739 SmallVector<ISD::OutputArg, 4> Outs;
740 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
743 // Analyze operands of the call, assigning locations to each operand.
744 SmallVector<CCValAssign, 16> ValLocs;
745 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
747 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
749 const Value *RV = Ret->getOperand(0);
750 unsigned Reg = getRegForValue(RV);
754 // Only handle a single return value for now.
755 if (ValLocs.size() != 1)
758 CCValAssign &VA = ValLocs[0];
760 // Don't bother handling odd stuff for now.
761 if (VA.getLocInfo() != CCValAssign::Full)
763 // Only handle register returns for now.
767 // The calling-convention tables for x87 returns don't tell
769 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
772 unsigned SrcReg = Reg + VA.getValNo();
773 EVT SrcVT = TLI.getValueType(RV->getType());
774 EVT DstVT = VA.getValVT();
775 // Special handling for extended integers.
776 if (SrcVT != DstVT) {
777 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
780 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
783 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
785 if (SrcVT == MVT::i1) {
786 if (Outs[0].Flags.isSExt())
788 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
791 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
793 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
794 SrcReg, /*TODO: Kill=*/false);
798 unsigned DstReg = VA.getLocReg();
799 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
800 // Avoid a cross-class copy. This is very unlikely.
801 if (!SrcRC->contains(DstReg))
803 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
804 DstReg).addReg(SrcReg);
806 // Mark the register as live out of the function.
807 MRI.addLiveOut(VA.getLocReg());
811 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
815 /// X86SelectLoad - Select and emit code to implement load instructions.
817 bool X86FastISel::X86SelectLoad(const Instruction *I) {
818 // Atomic loads need special handling.
819 if (cast<LoadInst>(I)->isAtomic())
823 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
827 if (!X86SelectAddress(I->getOperand(0), AM))
830 unsigned ResultReg = 0;
831 if (X86FastEmitLoad(VT, AM, ResultReg)) {
832 UpdateValueMap(I, ResultReg);
838 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
839 bool HasAVX = Subtarget->hasAVX();
840 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
841 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
843 switch (VT.getSimpleVT().SimpleTy) {
845 case MVT::i8: return X86::CMP8rr;
846 case MVT::i16: return X86::CMP16rr;
847 case MVT::i32: return X86::CMP32rr;
848 case MVT::i64: return X86::CMP64rr;
850 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
852 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
856 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
857 /// of the comparison, return an opcode that works for the compare (e.g.
858 /// CMP32ri) otherwise return 0.
859 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
860 switch (VT.getSimpleVT().SimpleTy) {
861 // Otherwise, we can't fold the immediate into this comparison.
863 case MVT::i8: return X86::CMP8ri;
864 case MVT::i16: return X86::CMP16ri;
865 case MVT::i32: return X86::CMP32ri;
867 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
869 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
870 return X86::CMP64ri32;
875 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
877 unsigned Op0Reg = getRegForValue(Op0);
878 if (Op0Reg == 0) return false;
880 // Handle 'null' like i32/i64 0.
881 if (isa<ConstantPointerNull>(Op1))
882 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
884 // We have two options: compare with register or immediate. If the RHS of
885 // the compare is an immediate that we can fold into this compare, use
886 // CMPri, otherwise use CMPrr.
887 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
888 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
889 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
891 .addImm(Op1C->getSExtValue());
896 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
897 if (CompareOpc == 0) return false;
899 unsigned Op1Reg = getRegForValue(Op1);
900 if (Op1Reg == 0) return false;
901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
908 bool X86FastISel::X86SelectCmp(const Instruction *I) {
909 const CmpInst *CI = cast<CmpInst>(I);
912 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
915 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
917 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
918 switch (CI->getPredicate()) {
919 case CmpInst::FCMP_OEQ: {
920 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
923 unsigned EReg = createResultReg(&X86::GR8RegClass);
924 unsigned NPReg = createResultReg(&X86::GR8RegClass);
925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
926 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
927 TII.get(X86::SETNPr), NPReg);
928 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
929 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
930 UpdateValueMap(I, ResultReg);
933 case CmpInst::FCMP_UNE: {
934 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
937 unsigned NEReg = createResultReg(&X86::GR8RegClass);
938 unsigned PReg = createResultReg(&X86::GR8RegClass);
939 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
942 .addReg(PReg).addReg(NEReg);
943 UpdateValueMap(I, ResultReg);
946 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
947 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
948 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
949 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
950 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
951 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
952 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
953 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
954 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
955 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
956 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
957 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
959 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
960 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
961 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
962 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
963 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
964 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
965 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
966 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
967 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
968 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
973 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
977 // Emit a compare of Op0/Op1.
978 if (!X86FastEmitCompare(Op0, Op1, VT))
981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
982 UpdateValueMap(I, ResultReg);
986 bool X86FastISel::X86SelectZExt(const Instruction *I) {
987 // Handle zero-extension from i1 to i8, which is common.
988 if (!I->getOperand(0)->getType()->isIntegerTy(1))
991 EVT DstVT = TLI.getValueType(I->getType());
992 if (!TLI.isTypeLegal(DstVT))
995 unsigned ResultReg = getRegForValue(I->getOperand(0));
999 // Set the high bits to zero.
1000 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1004 if (DstVT != MVT::i8) {
1005 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1006 ResultReg, /*Kill=*/true);
1011 UpdateValueMap(I, ResultReg);
1016 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1017 // Unconditional branches are selected by tablegen-generated code.
1018 // Handle a conditional branch.
1019 const BranchInst *BI = cast<BranchInst>(I);
1020 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1021 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1023 // Fold the common case of a conditional branch with a comparison
1024 // in the same block (values defined on other blocks may not have
1025 // initialized registers).
1026 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1027 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1028 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1030 // Try to take advantage of fallthrough opportunities.
1031 CmpInst::Predicate Predicate = CI->getPredicate();
1032 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1033 std::swap(TrueMBB, FalseMBB);
1034 Predicate = CmpInst::getInversePredicate(Predicate);
1037 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1038 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1040 switch (Predicate) {
1041 case CmpInst::FCMP_OEQ:
1042 std::swap(TrueMBB, FalseMBB);
1043 Predicate = CmpInst::FCMP_UNE;
1045 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1046 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1047 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1048 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1049 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1050 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1051 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1052 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1053 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1054 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1055 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1056 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1057 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1059 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1060 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1061 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1062 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1063 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1064 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1065 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1066 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1067 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1068 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1073 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1075 std::swap(Op0, Op1);
1077 // Emit a compare of the LHS and RHS, setting the flags.
1078 if (!X86FastEmitCompare(Op0, Op1, VT))
1081 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1084 if (Predicate == CmpInst::FCMP_UNE) {
1085 // X86 requires a second branch to handle UNE (and OEQ,
1086 // which is mapped to UNE above).
1087 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1091 FastEmitBranch(FalseMBB, DL);
1092 FuncInfo.MBB->addSuccessor(TrueMBB);
1095 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1096 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1097 // typically happen for _Bool and C++ bools.
1099 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1100 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1101 unsigned TestOpc = 0;
1102 switch (SourceVT.SimpleTy) {
1104 case MVT::i8: TestOpc = X86::TEST8ri; break;
1105 case MVT::i16: TestOpc = X86::TEST16ri; break;
1106 case MVT::i32: TestOpc = X86::TEST32ri; break;
1107 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1110 unsigned OpReg = getRegForValue(TI->getOperand(0));
1111 if (OpReg == 0) return false;
1112 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1113 .addReg(OpReg).addImm(1);
1115 unsigned JmpOpc = X86::JNE_4;
1116 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1117 std::swap(TrueMBB, FalseMBB);
1121 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1123 FastEmitBranch(FalseMBB, DL);
1124 FuncInfo.MBB->addSuccessor(TrueMBB);
1130 // Otherwise do a clumsy setcc and re-test it.
1131 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1132 // in an explicit cast, so make sure to handle that correctly.
1133 unsigned OpReg = getRegForValue(BI->getCondition());
1134 if (OpReg == 0) return false;
1136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1137 .addReg(OpReg).addImm(1);
1138 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1140 FastEmitBranch(FalseMBB, DL);
1141 FuncInfo.MBB->addSuccessor(TrueMBB);
1145 bool X86FastISel::X86SelectShift(const Instruction *I) {
1146 unsigned CReg = 0, OpReg = 0;
1147 const TargetRegisterClass *RC = NULL;
1148 if (I->getType()->isIntegerTy(8)) {
1150 RC = &X86::GR8RegClass;
1151 switch (I->getOpcode()) {
1152 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1153 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1154 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1155 default: return false;
1157 } else if (I->getType()->isIntegerTy(16)) {
1159 RC = &X86::GR16RegClass;
1160 switch (I->getOpcode()) {
1161 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1162 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1163 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1164 default: return false;
1166 } else if (I->getType()->isIntegerTy(32)) {
1168 RC = &X86::GR32RegClass;
1169 switch (I->getOpcode()) {
1170 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1171 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1172 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1173 default: return false;
1175 } else if (I->getType()->isIntegerTy(64)) {
1177 RC = &X86::GR64RegClass;
1178 switch (I->getOpcode()) {
1179 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1180 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1181 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1182 default: return false;
1189 if (!isTypeLegal(I->getType(), VT))
1192 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1193 if (Op0Reg == 0) return false;
1195 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1196 if (Op1Reg == 0) return false;
1197 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1198 CReg).addReg(Op1Reg);
1200 // The shift instruction uses X86::CL. If we defined a super-register
1201 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1202 if (CReg != X86::CL)
1203 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1204 TII.get(TargetOpcode::KILL), X86::CL)
1205 .addReg(CReg, RegState::Kill);
1207 unsigned ResultReg = createResultReg(RC);
1208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1210 UpdateValueMap(I, ResultReg);
1214 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1216 if (!isTypeLegal(I->getType(), VT))
1219 // We only use cmov here, if we don't have a cmov instruction bail.
1220 if (!Subtarget->hasCMov()) return false;
1223 const TargetRegisterClass *RC = NULL;
1224 if (VT == MVT::i16) {
1225 Opc = X86::CMOVE16rr;
1226 RC = &X86::GR16RegClass;
1227 } else if (VT == MVT::i32) {
1228 Opc = X86::CMOVE32rr;
1229 RC = &X86::GR32RegClass;
1230 } else if (VT == MVT::i64) {
1231 Opc = X86::CMOVE64rr;
1232 RC = &X86::GR64RegClass;
1237 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1238 if (Op0Reg == 0) return false;
1239 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1240 if (Op1Reg == 0) return false;
1241 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1242 if (Op2Reg == 0) return false;
1244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1245 .addReg(Op0Reg).addReg(Op0Reg);
1246 unsigned ResultReg = createResultReg(RC);
1247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1248 .addReg(Op1Reg).addReg(Op2Reg);
1249 UpdateValueMap(I, ResultReg);
1253 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1254 // fpext from float to double.
1255 if (X86ScalarSSEf64 &&
1256 I->getType()->isDoubleTy()) {
1257 const Value *V = I->getOperand(0);
1258 if (V->getType()->isFloatTy()) {
1259 unsigned OpReg = getRegForValue(V);
1260 if (OpReg == 0) return false;
1261 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1263 TII.get(X86::CVTSS2SDrr), ResultReg)
1265 UpdateValueMap(I, ResultReg);
1273 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1274 if (X86ScalarSSEf64) {
1275 if (I->getType()->isFloatTy()) {
1276 const Value *V = I->getOperand(0);
1277 if (V->getType()->isDoubleTy()) {
1278 unsigned OpReg = getRegForValue(V);
1279 if (OpReg == 0) return false;
1280 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1282 TII.get(X86::CVTSD2SSrr), ResultReg)
1284 UpdateValueMap(I, ResultReg);
1293 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1294 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1295 EVT DstVT = TLI.getValueType(I->getType());
1297 // This code only handles truncation to byte.
1298 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1300 if (!TLI.isTypeLegal(SrcVT))
1303 unsigned InputReg = getRegForValue(I->getOperand(0));
1305 // Unhandled operand. Halt "fast" selection and bail.
1308 if (SrcVT == MVT::i8) {
1309 // Truncate from i8 to i1; no code needed.
1310 UpdateValueMap(I, InputReg);
1314 if (!Subtarget->is64Bit()) {
1315 // If we're on x86-32; we can't extract an i8 from a general register.
1316 // First issue a copy to GR16_ABCD or GR32_ABCD.
1317 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1318 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1319 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1320 unsigned CopyReg = createResultReg(CopyRC);
1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1322 CopyReg).addReg(InputReg);
1326 // Issue an extract_subreg.
1327 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1328 InputReg, /*Kill=*/true,
1333 UpdateValueMap(I, ResultReg);
1337 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1338 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1341 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1342 X86AddressMode SrcAM, uint64_t Len) {
1344 // Make sure we don't bloat code by inlining very large memcpy's.
1345 if (!IsMemcpySmall(Len))
1348 bool i64Legal = Subtarget->is64Bit();
1350 // We don't care about alignment here since we just emit integer accesses.
1353 if (Len >= 8 && i64Legal)
1365 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1366 RV &= X86FastEmitStore(VT, Reg, DestAM);
1367 assert(RV && "Failed to emit load or store??");
1369 unsigned Size = VT.getSizeInBits()/8;
1371 DestAM.Disp += Size;
1378 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1379 // FIXME: Handle more intrinsics.
1380 switch (I.getIntrinsicID()) {
1381 default: return false;
1382 case Intrinsic::memcpy: {
1383 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1384 // Don't handle volatile or variable length memcpys.
1385 if (MCI.isVolatile())
1388 if (isa<ConstantInt>(MCI.getLength())) {
1389 // Small memcpy's are common enough that we want to do them
1390 // without a call if possible.
1391 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1392 if (IsMemcpySmall(Len)) {
1393 X86AddressMode DestAM, SrcAM;
1394 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1395 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1397 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1402 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1403 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1406 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1409 return DoSelectCall(&I, "memcpy");
1411 case Intrinsic::memset: {
1412 const MemSetInst &MSI = cast<MemSetInst>(I);
1414 if (MSI.isVolatile())
1417 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1418 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1421 if (MSI.getDestAddressSpace() > 255)
1424 return DoSelectCall(&I, "memset");
1426 case Intrinsic::stackprotector: {
1427 // Emit code to store the stack guard onto the stack.
1428 EVT PtrTy = TLI.getPointerTy();
1430 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1431 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1433 // Grab the frame index.
1435 if (!X86SelectAddress(Slot, AM)) return false;
1436 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1439 case Intrinsic::dbg_declare: {
1440 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1442 assert(DI->getAddress() && "Null address should be checked earlier!");
1443 if (!X86SelectAddress(DI->getAddress(), AM))
1445 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1446 // FIXME may need to add RegState::Debug to any registers produced,
1447 // although ESP/EBP should be the only ones at the moment.
1448 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1449 addImm(0).addMetadata(DI->getVariable());
1452 case Intrinsic::trap: {
1453 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1456 case Intrinsic::sadd_with_overflow:
1457 case Intrinsic::uadd_with_overflow: {
1458 // FIXME: Should fold immediates.
1460 // Replace "add with overflow" intrinsics with an "add" instruction followed
1461 // by a seto/setc instruction.
1462 const Function *Callee = I.getCalledFunction();
1464 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1467 if (!isTypeLegal(RetTy, VT))
1470 const Value *Op1 = I.getArgOperand(0);
1471 const Value *Op2 = I.getArgOperand(1);
1472 unsigned Reg1 = getRegForValue(Op1);
1473 unsigned Reg2 = getRegForValue(Op2);
1475 if (Reg1 == 0 || Reg2 == 0)
1476 // FIXME: Handle values *not* in registers.
1482 else if (VT == MVT::i64)
1487 // The call to CreateRegs builds two sequential registers, to store the
1488 // both the returned values.
1489 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1491 .addReg(Reg1).addReg(Reg2);
1493 unsigned Opc = X86::SETBr;
1494 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1496 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1498 UpdateValueMap(&I, ResultReg, 2);
1504 bool X86FastISel::X86SelectCall(const Instruction *I) {
1505 const CallInst *CI = cast<CallInst>(I);
1506 const Value *Callee = CI->getCalledValue();
1508 // Can't handle inline asm yet.
1509 if (isa<InlineAsm>(Callee))
1512 // Handle intrinsic calls.
1513 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1514 return X86VisitIntrinsicCall(*II);
1516 return DoSelectCall(I, 0);
1519 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1520 const ImmutableCallSite &CS) {
1521 if (Subtarget.is64Bit())
1523 if (Subtarget.isTargetWindows())
1525 CallingConv::ID CC = CS.getCallingConv();
1526 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1528 if (!CS.paramHasAttr(1, Attribute::StructRet))
1530 if (CS.paramHasAttr(1, Attribute::InReg))
1535 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1536 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1537 const CallInst *CI = cast<CallInst>(I);
1538 const Value *Callee = CI->getCalledValue();
1540 // Handle only C and fastcc calling conventions for now.
1541 ImmutableCallSite CS(CI);
1542 CallingConv::ID CC = CS.getCallingConv();
1543 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1544 CC != CallingConv::X86_FastCall)
1547 // fastcc with -tailcallopt is intended to provide a guaranteed
1548 // tail call optimization. Fastisel doesn't know how to do that.
1549 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1552 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1553 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1554 bool isVarArg = FTy->isVarArg();
1556 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1557 // x86-32. Special handling for x86-64 is implemented.
1558 if (isVarArg && Subtarget->isTargetWin64())
1561 // Fast-isel doesn't know about callee-pop yet.
1562 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1563 TM.Options.GuaranteedTailCallOpt))
1566 // Check whether the function can return without sret-demotion.
1567 SmallVector<ISD::OutputArg, 4> Outs;
1568 GetReturnInfo(I->getType(), CS.getAttributes().getRetAttributes(),
1570 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1571 *FuncInfo.MF, FTy->isVarArg(),
1572 Outs, FTy->getContext());
1573 if (!CanLowerReturn)
1576 // Materialize callee address in a register. FIXME: GV address can be
1577 // handled with a CALLpcrel32 instead.
1578 X86AddressMode CalleeAM;
1579 if (!X86SelectCallAddress(Callee, CalleeAM))
1581 unsigned CalleeOp = 0;
1582 const GlobalValue *GV = 0;
1583 if (CalleeAM.GV != 0) {
1585 } else if (CalleeAM.Base.Reg != 0) {
1586 CalleeOp = CalleeAM.Base.Reg;
1590 // Deal with call operands first.
1591 SmallVector<const Value *, 8> ArgVals;
1592 SmallVector<unsigned, 8> Args;
1593 SmallVector<MVT, 8> ArgVTs;
1594 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1595 unsigned arg_size = CS.arg_size();
1596 Args.reserve(arg_size);
1597 ArgVals.reserve(arg_size);
1598 ArgVTs.reserve(arg_size);
1599 ArgFlags.reserve(arg_size);
1600 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1602 // If we're lowering a mem intrinsic instead of a regular call, skip the
1603 // last two arguments, which should not passed to the underlying functions.
1604 if (MemIntName && e-i <= 2)
1607 ISD::ArgFlagsTy Flags;
1608 unsigned AttrInd = i - CS.arg_begin() + 1;
1609 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1611 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1614 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1615 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1616 Type *ElementTy = Ty->getElementType();
1617 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1618 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1620 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1622 Flags.setByValSize(FrameSize);
1623 Flags.setByValAlign(FrameAlign);
1624 if (!IsMemcpySmall(FrameSize))
1628 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1630 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1633 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1634 // instruction. This is safe because it is common to all fastisel supported
1635 // calling conventions on x86.
1636 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1637 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1638 CI->getBitWidth() == 16) {
1640 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1642 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1648 // Passing bools around ends up doing a trunc to i1 and passing it.
1649 // Codegen this as an argument + "and 1".
1650 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1651 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1652 ArgVal->hasOneUse()) {
1653 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1654 ArgReg = getRegForValue(ArgVal);
1655 if (ArgReg == 0) return false;
1658 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1660 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1661 ArgVal->hasOneUse(), 1);
1663 ArgReg = getRegForValue(ArgVal);
1666 if (ArgReg == 0) return false;
1668 Type *ArgTy = ArgVal->getType();
1670 if (!isTypeLegal(ArgTy, ArgVT))
1672 if (ArgVT == MVT::x86mmx)
1674 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1675 Flags.setOrigAlign(OriginalAlignment);
1677 Args.push_back(ArgReg);
1678 ArgVals.push_back(ArgVal);
1679 ArgVTs.push_back(ArgVT);
1680 ArgFlags.push_back(Flags);
1683 // Analyze operands of the call, assigning locations to each operand.
1684 SmallVector<CCValAssign, 16> ArgLocs;
1685 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1686 I->getParent()->getContext());
1688 // Allocate shadow area for Win64
1689 if (Subtarget->isTargetWin64())
1690 CCInfo.AllocateStack(32, 8);
1692 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1694 // Get a count of how many bytes are to be pushed on the stack.
1695 unsigned NumBytes = CCInfo.getNextStackOffset();
1697 // Issue CALLSEQ_START
1698 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1699 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1702 // Process argument: walk the register/memloc assignments, inserting
1704 SmallVector<unsigned, 4> RegArgs;
1705 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1706 CCValAssign &VA = ArgLocs[i];
1707 unsigned Arg = Args[VA.getValNo()];
1708 EVT ArgVT = ArgVTs[VA.getValNo()];
1710 // Promote the value if needed.
1711 switch (VA.getLocInfo()) {
1712 case CCValAssign::Full: break;
1713 case CCValAssign::SExt: {
1714 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1715 "Unexpected extend");
1716 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1718 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1719 ArgVT = VA.getLocVT();
1722 case CCValAssign::ZExt: {
1723 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1724 "Unexpected extend");
1725 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1727 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1728 ArgVT = VA.getLocVT();
1731 case CCValAssign::AExt: {
1732 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1733 "Unexpected extend");
1734 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1737 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1740 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1743 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1744 ArgVT = VA.getLocVT();
1747 case CCValAssign::BCvt: {
1748 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1749 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1750 assert(BC != 0 && "Failed to emit a bitcast!");
1752 ArgVT = VA.getLocVT();
1755 case CCValAssign::VExt:
1756 // VExt has not been implemented, so this should be impossible to reach
1757 // for now. However, fallback to Selection DAG isel once implemented.
1759 case CCValAssign::Indirect:
1760 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
1765 if (VA.isRegLoc()) {
1766 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1767 VA.getLocReg()).addReg(Arg);
1768 RegArgs.push_back(VA.getLocReg());
1770 unsigned LocMemOffset = VA.getLocMemOffset();
1772 AM.Base.Reg = StackPtr;
1773 AM.Disp = LocMemOffset;
1774 const Value *ArgVal = ArgVals[VA.getValNo()];
1775 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1777 if (Flags.isByVal()) {
1778 X86AddressMode SrcAM;
1779 SrcAM.Base.Reg = Arg;
1780 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
1781 assert(Res && "memcpy length already checked!"); (void)Res;
1782 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
1783 // If this is a really simple value, emit this with the Value* version
1784 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
1785 // as it can cause us to reevaluate the argument.
1786 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
1789 if (!X86FastEmitStore(ArgVT, Arg, AM))
1795 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1797 if (Subtarget->isPICStyleGOT()) {
1798 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1800 X86::EBX).addReg(Base);
1803 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1804 // Count the number of XMM registers allocated.
1805 static const uint16_t XMMArgRegs[] = {
1806 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1807 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1809 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1810 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1811 X86::AL).addImm(NumXMMRegs);
1815 MachineInstrBuilder MIB;
1817 // Register-indirect call.
1819 if (Subtarget->is64Bit())
1820 CallOpc = X86::CALL64r;
1822 CallOpc = X86::CALL32r;
1823 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1828 assert(GV && "Not a direct call");
1830 if (Subtarget->is64Bit())
1831 CallOpc = X86::CALL64pcrel32;
1833 CallOpc = X86::CALLpcrel32;
1835 // See if we need any target-specific flags on the GV operand.
1836 unsigned char OpFlags = 0;
1838 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1839 // external symbols most go through the PLT in PIC mode. If the symbol
1840 // has hidden or protected visibility, or if it is static or local, then
1841 // we don't need to use the PLT - we can directly call it.
1842 if (Subtarget->isTargetELF() &&
1843 TM.getRelocationModel() == Reloc::PIC_ &&
1844 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1845 OpFlags = X86II::MO_PLT;
1846 } else if (Subtarget->isPICStyleStubAny() &&
1847 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1848 (!Subtarget->getTargetTriple().isMacOSX() ||
1849 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1850 // PC-relative references to external symbols should go through $stub,
1851 // unless we're building with the leopard linker or later, which
1852 // automatically synthesizes these stubs.
1853 OpFlags = X86II::MO_DARWIN_STUB;
1857 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
1859 MIB.addExternalSymbol(MemIntName, OpFlags);
1861 MIB.addGlobalAddress(GV, 0, OpFlags);
1864 // Add a register mask with the call-preserved registers.
1865 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1866 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
1868 // Add an implicit use GOT pointer in EBX.
1869 if (Subtarget->isPICStyleGOT())
1870 MIB.addReg(X86::EBX, RegState::Implicit);
1872 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1873 MIB.addReg(X86::AL, RegState::Implicit);
1875 // Add implicit physical register uses to the call.
1876 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1877 MIB.addReg(RegArgs[i], RegState::Implicit);
1879 // Issue CALLSEQ_END
1880 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1881 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
1882 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1883 .addImm(NumBytes).addImm(NumBytesCallee);
1885 // Build info for return calling conv lowering code.
1886 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
1887 SmallVector<ISD::InputArg, 32> Ins;
1888 SmallVector<EVT, 4> RetTys;
1889 ComputeValueVTs(TLI, I->getType(), RetTys);
1890 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
1892 EVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
1893 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
1894 for (unsigned j = 0; j != NumRegs; ++j) {
1895 ISD::InputArg MyFlags;
1896 MyFlags.VT = RegisterVT.getSimpleVT();
1897 MyFlags.Used = !CS.getInstruction()->use_empty();
1898 if (CS.paramHasAttr(0, Attribute::SExt))
1899 MyFlags.Flags.setSExt();
1900 if (CS.paramHasAttr(0, Attribute::ZExt))
1901 MyFlags.Flags.setZExt();
1902 if (CS.paramHasAttr(0, Attribute::InReg))
1903 MyFlags.Flags.setInReg();
1904 Ins.push_back(MyFlags);
1908 // Now handle call return values.
1909 SmallVector<unsigned, 4> UsedRegs;
1910 SmallVector<CCValAssign, 16> RVLocs;
1911 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
1912 I->getParent()->getContext());
1913 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
1914 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
1915 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1916 EVT CopyVT = RVLocs[i].getValVT();
1917 unsigned CopyReg = ResultReg + i;
1919 // If this is a call to a function that returns an fp value on the x87 fp
1920 // stack, but where we prefer to use the value in xmm registers, copy it
1921 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1922 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1923 RVLocs[i].getLocReg() == X86::ST1)) {
1924 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1926 CopyReg = createResultReg(&X86::RFP80RegClass);
1928 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
1931 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1932 CopyReg).addReg(RVLocs[i].getLocReg());
1933 UsedRegs.push_back(RVLocs[i].getLocReg());
1936 if (CopyVT != RVLocs[i].getValVT()) {
1937 // Round the F80 the right size, which also moves to the appropriate xmm
1938 // register. This is accomplished by storing the F80 value in memory and
1939 // then loading it back. Ewww...
1940 EVT ResVT = RVLocs[i].getValVT();
1941 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1942 unsigned MemSize = ResVT.getSizeInBits()/8;
1943 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1944 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1947 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1948 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1949 TII.get(Opc), ResultReg + i), FI);
1954 UpdateValueMap(I, ResultReg, RVLocs.size());
1956 // Set all unused physreg defs as dead.
1957 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1964 X86FastISel::TargetSelectInstruction(const Instruction *I) {
1965 switch (I->getOpcode()) {
1967 case Instruction::Load:
1968 return X86SelectLoad(I);
1969 case Instruction::Store:
1970 return X86SelectStore(I);
1971 case Instruction::Ret:
1972 return X86SelectRet(I);
1973 case Instruction::ICmp:
1974 case Instruction::FCmp:
1975 return X86SelectCmp(I);
1976 case Instruction::ZExt:
1977 return X86SelectZExt(I);
1978 case Instruction::Br:
1979 return X86SelectBranch(I);
1980 case Instruction::Call:
1981 return X86SelectCall(I);
1982 case Instruction::LShr:
1983 case Instruction::AShr:
1984 case Instruction::Shl:
1985 return X86SelectShift(I);
1986 case Instruction::Select:
1987 return X86SelectSelect(I);
1988 case Instruction::Trunc:
1989 return X86SelectTrunc(I);
1990 case Instruction::FPExt:
1991 return X86SelectFPExt(I);
1992 case Instruction::FPTrunc:
1993 return X86SelectFPTrunc(I);
1994 case Instruction::IntToPtr: // Deliberate fall-through.
1995 case Instruction::PtrToInt: {
1996 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1997 EVT DstVT = TLI.getValueType(I->getType());
1998 if (DstVT.bitsGT(SrcVT))
1999 return X86SelectZExt(I);
2000 if (DstVT.bitsLT(SrcVT))
2001 return X86SelectTrunc(I);
2002 unsigned Reg = getRegForValue(I->getOperand(0));
2003 if (Reg == 0) return false;
2004 UpdateValueMap(I, Reg);
2012 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2014 if (!isTypeLegal(C->getType(), VT))
2017 // Get opcode and regclass of the output for the given load instruction.
2019 const TargetRegisterClass *RC = NULL;
2020 switch (VT.SimpleTy) {
2021 default: return false;
2024 RC = &X86::GR8RegClass;
2028 RC = &X86::GR16RegClass;
2032 RC = &X86::GR32RegClass;
2035 // Must be in x86-64 mode.
2037 RC = &X86::GR64RegClass;
2040 if (X86ScalarSSEf32) {
2041 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2042 RC = &X86::FR32RegClass;
2044 Opc = X86::LD_Fp32m;
2045 RC = &X86::RFP32RegClass;
2049 if (X86ScalarSSEf64) {
2050 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2051 RC = &X86::FR64RegClass;
2053 Opc = X86::LD_Fp64m;
2054 RC = &X86::RFP64RegClass;
2058 // No f80 support yet.
2062 // Materialize addresses with LEA instructions.
2063 if (isa<GlobalValue>(C)) {
2065 if (X86SelectAddress(C, AM)) {
2066 // If the expression is just a basereg, then we're done, otherwise we need
2068 if (AM.BaseType == X86AddressMode::RegBase &&
2069 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2072 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2073 unsigned ResultReg = createResultReg(RC);
2074 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2075 TII.get(Opc), ResultReg), AM);
2081 // MachineConstantPool wants an explicit alignment.
2082 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2084 // Alignment of vector types. FIXME!
2085 Align = TD.getTypeAllocSize(C->getType());
2088 // x86-32 PIC requires a PIC base register for constant pools.
2089 unsigned PICBase = 0;
2090 unsigned char OpFlag = 0;
2091 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2092 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2093 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2094 } else if (Subtarget->isPICStyleGOT()) {
2095 OpFlag = X86II::MO_GOTOFF;
2096 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2097 } else if (Subtarget->isPICStyleRIPRel() &&
2098 TM.getCodeModel() == CodeModel::Small) {
2102 // Create the load from the constant pool.
2103 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2104 unsigned ResultReg = createResultReg(RC);
2105 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2106 TII.get(Opc), ResultReg),
2107 MCPOffset, PICBase, OpFlag);
2112 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2113 // Fail on dynamic allocas. At this point, getRegForValue has already
2114 // checked its CSE maps, so if we're here trying to handle a dynamic
2115 // alloca, we're not going to succeed. X86SelectAddress has a
2116 // check for dynamic allocas, because it's called directly from
2117 // various places, but TargetMaterializeAlloca also needs a check
2118 // in order to avoid recursion between getRegForValue,
2119 // X86SelectAddrss, and TargetMaterializeAlloca.
2120 if (!FuncInfo.StaticAllocaMap.count(C))
2124 if (!X86SelectAddress(C, AM))
2126 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2127 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2128 unsigned ResultReg = createResultReg(RC);
2129 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2130 TII.get(Opc), ResultReg), AM);
2134 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2136 if (!isTypeLegal(CF->getType(), VT))
2139 // Get opcode and regclass for the given zero.
2141 const TargetRegisterClass *RC = NULL;
2142 switch (VT.SimpleTy) {
2143 default: return false;
2145 if (X86ScalarSSEf32) {
2146 Opc = X86::FsFLD0SS;
2147 RC = &X86::FR32RegClass;
2149 Opc = X86::LD_Fp032;
2150 RC = &X86::RFP32RegClass;
2154 if (X86ScalarSSEf64) {
2155 Opc = X86::FsFLD0SD;
2156 RC = &X86::FR64RegClass;
2158 Opc = X86::LD_Fp064;
2159 RC = &X86::RFP64RegClass;
2163 // No f80 support yet.
2167 unsigned ResultReg = createResultReg(RC);
2168 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2173 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2174 /// vreg is being provided by the specified load instruction. If possible,
2175 /// try to fold the load as an operand to the instruction, returning true if
2177 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2178 const LoadInst *LI) {
2180 if (!X86SelectAddress(LI->getOperand(0), AM))
2183 X86InstrInfo &XII = (X86InstrInfo&)TII;
2185 unsigned Size = TD.getTypeAllocSize(LI->getType());
2186 unsigned Alignment = LI->getAlignment();
2188 SmallVector<MachineOperand, 8> AddrOps;
2189 AM.getFullAddress(AddrOps);
2191 MachineInstr *Result =
2192 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2193 if (Result == 0) return false;
2195 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2196 MI->eraseFromParent();
2202 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
2203 return new X86FastISel(funcInfo);