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/CallingConv.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/GlobalAlias.h"
31 #include "llvm/GlobalVariable.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/IntrinsicInst.h"
34 #include "llvm/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 /// RegInfo - X86 register info.
50 const X86RegisterInfo *RegInfo;
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,
61 const TargetLibraryInfo *libInfo)
62 : FastISel(funcInfo, libInfo) {
63 Subtarget = &TM.getSubtarget<X86Subtarget>();
64 X86ScalarSSEf64 = Subtarget->hasSSE2();
65 X86ScalarSSEf32 = Subtarget->hasSSE1();
66 RegInfo = static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
69 virtual bool TargetSelectInstruction(const Instruction *I);
71 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
75 virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
78 #include "X86GenFastISel.inc"
81 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
83 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
85 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
86 bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
88 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
91 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
92 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
94 bool X86SelectLoad(const Instruction *I);
96 bool X86SelectStore(const Instruction *I);
98 bool X86SelectRet(const Instruction *I);
100 bool X86SelectCmp(const Instruction *I);
102 bool X86SelectZExt(const Instruction *I);
104 bool X86SelectBranch(const Instruction *I);
106 bool X86SelectShift(const Instruction *I);
108 bool X86SelectSelect(const Instruction *I);
110 bool X86SelectTrunc(const Instruction *I);
112 bool X86SelectFPExt(const Instruction *I);
113 bool X86SelectFPTrunc(const Instruction *I);
115 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
116 bool X86SelectCall(const Instruction *I);
118 bool DoSelectCall(const Instruction *I, const char *MemIntName);
120 const X86InstrInfo *getInstrInfo() const {
121 return getTargetMachine()->getInstrInfo();
123 const X86TargetMachine *getTargetMachine() const {
124 return static_cast<const X86TargetMachine *>(&TM);
127 unsigned TargetMaterializeConstant(const Constant *C);
129 unsigned TargetMaterializeAlloca(const AllocaInst *C);
131 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
133 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
134 /// computed in an SSE register, not on the X87 floating point stack.
135 bool isScalarFPTypeInSSEReg(EVT VT) const {
136 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
137 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
140 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
142 bool IsMemcpySmall(uint64_t Len);
144 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
145 X86AddressMode SrcAM, uint64_t Len);
148 } // end anonymous namespace.
150 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
151 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
152 if (evt == MVT::Other || !evt.isSimple())
153 // Unhandled type. Halt "fast" selection and bail.
156 VT = evt.getSimpleVT();
157 // For now, require SSE/SSE2 for performing floating-point operations,
158 // since x87 requires additional work.
159 if (VT == MVT::f64 && !X86ScalarSSEf64)
161 if (VT == MVT::f32 && !X86ScalarSSEf32)
163 // Similarly, no f80 support yet.
166 // We only handle legal types. For example, on x86-32 the instruction
167 // selector contains all of the 64-bit instructions from x86-64,
168 // under the assumption that i64 won't be used if the target doesn't
170 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
173 #include "X86GenCallingConv.inc"
175 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
176 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
177 /// Return true and the result register by reference if it is possible.
178 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
179 unsigned &ResultReg) {
180 // Get opcode and regclass of the output for the given load instruction.
182 const TargetRegisterClass *RC = NULL;
183 switch (VT.getSimpleVT().SimpleTy) {
184 default: return false;
188 RC = &X86::GR8RegClass;
192 RC = &X86::GR16RegClass;
196 RC = &X86::GR32RegClass;
199 // Must be in x86-64 mode.
201 RC = &X86::GR64RegClass;
204 if (X86ScalarSSEf32) {
205 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
206 RC = &X86::FR32RegClass;
209 RC = &X86::RFP32RegClass;
213 if (X86ScalarSSEf64) {
214 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
215 RC = &X86::FR64RegClass;
218 RC = &X86::RFP64RegClass;
222 // No f80 support yet.
226 ResultReg = createResultReg(RC);
227 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
228 DL, TII.get(Opc), ResultReg), AM);
232 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
233 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
234 /// and a displacement offset, or a GlobalAddress,
235 /// i.e. V. Return true if it is possible.
237 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
238 // Get opcode and regclass of the output for the given store instruction.
240 switch (VT.getSimpleVT().SimpleTy) {
241 case MVT::f80: // No f80 support yet.
242 default: return false;
244 // Mask out all but lowest bit.
245 unsigned AndResult = createResultReg(&X86::GR8RegClass);
246 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
247 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
250 // FALLTHROUGH, handling i1 as i8.
251 case MVT::i8: Opc = X86::MOV8mr; break;
252 case MVT::i16: Opc = X86::MOV16mr; break;
253 case MVT::i32: Opc = X86::MOV32mr; break;
254 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
256 Opc = X86ScalarSSEf32 ?
257 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
260 Opc = X86ScalarSSEf64 ?
261 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
277 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
278 DL, TII.get(Opc)), AM).addReg(Val);
282 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
283 const X86AddressMode &AM) {
284 // Handle 'null' like i32/i64 0.
285 if (isa<ConstantPointerNull>(Val))
286 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
288 // If this is a store of a simple constant, fold the constant into the store.
289 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
292 switch (VT.getSimpleVT().SimpleTy) {
294 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
295 case MVT::i8: Opc = X86::MOV8mi; break;
296 case MVT::i16: Opc = X86::MOV16mi; break;
297 case MVT::i32: Opc = X86::MOV32mi; break;
299 // Must be a 32-bit sign extended value.
300 if (isInt<32>(CI->getSExtValue()))
301 Opc = X86::MOV64mi32;
306 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
307 DL, TII.get(Opc)), AM)
308 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
314 unsigned ValReg = getRegForValue(Val);
318 return X86FastEmitStore(VT, ValReg, AM);
321 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
322 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
323 /// ISD::SIGN_EXTEND).
324 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
325 unsigned Src, EVT SrcVT,
326 unsigned &ResultReg) {
327 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
328 Src, /*TODO: Kill=*/false);
337 /// X86SelectAddress - Attempt to fill in an address from the given value.
339 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
340 const User *U = NULL;
341 unsigned Opcode = Instruction::UserOp1;
342 if (const Instruction *I = dyn_cast<Instruction>(V)) {
343 // Don't walk into other basic blocks; it's possible we haven't
344 // visited them yet, so the instructions may not yet be assigned
345 // virtual registers.
346 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
347 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
348 Opcode = I->getOpcode();
351 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
352 Opcode = C->getOpcode();
356 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
357 if (Ty->getAddressSpace() > 255)
358 // Fast instruction selection doesn't support the special
364 case Instruction::BitCast:
365 // Look past bitcasts.
366 return X86SelectAddress(U->getOperand(0), AM);
368 case Instruction::IntToPtr:
369 // Look past no-op inttoptrs.
370 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
371 return X86SelectAddress(U->getOperand(0), AM);
374 case Instruction::PtrToInt:
375 // Look past no-op ptrtoints.
376 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
377 return X86SelectAddress(U->getOperand(0), AM);
380 case Instruction::Alloca: {
381 // Do static allocas.
382 const AllocaInst *A = cast<AllocaInst>(V);
383 DenseMap<const AllocaInst*, int>::iterator SI =
384 FuncInfo.StaticAllocaMap.find(A);
385 if (SI != FuncInfo.StaticAllocaMap.end()) {
386 AM.BaseType = X86AddressMode::FrameIndexBase;
387 AM.Base.FrameIndex = SI->second;
393 case Instruction::Add: {
394 // Adds of constants are common and easy enough.
395 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
396 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
397 // They have to fit in the 32-bit signed displacement field though.
398 if (isInt<32>(Disp)) {
399 AM.Disp = (uint32_t)Disp;
400 return X86SelectAddress(U->getOperand(0), AM);
406 case Instruction::GetElementPtr: {
407 X86AddressMode SavedAM = AM;
409 // Pattern-match simple GEPs.
410 uint64_t Disp = (int32_t)AM.Disp;
411 unsigned IndexReg = AM.IndexReg;
412 unsigned Scale = AM.Scale;
413 gep_type_iterator GTI = gep_type_begin(U);
414 // Iterate through the indices, folding what we can. Constants can be
415 // folded, and one dynamic index can be handled, if the scale is supported.
416 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
417 i != e; ++i, ++GTI) {
418 const Value *Op = *i;
419 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
420 const StructLayout *SL = TD.getStructLayout(STy);
421 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
425 // A array/variable index is always of the form i*S where S is the
426 // constant scale size. See if we can push the scale into immediates.
427 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
429 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
430 // Constant-offset addressing.
431 Disp += CI->getSExtValue() * S;
434 if (isa<AddOperator>(Op) &&
435 (!isa<Instruction>(Op) ||
436 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
438 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
439 // An add (in the same block) with a constant operand. Fold the
442 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
443 Disp += CI->getSExtValue() * S;
444 // Iterate on the other operand.
445 Op = cast<AddOperator>(Op)->getOperand(0);
449 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
450 (S == 1 || S == 2 || S == 4 || S == 8)) {
451 // Scaled-index addressing.
453 IndexReg = getRegForGEPIndex(Op).first;
459 goto unsupported_gep;
462 // Check for displacement overflow.
463 if (!isInt<32>(Disp))
465 // Ok, the GEP indices were covered by constant-offset and scaled-index
466 // addressing. Update the address state and move on to examining the base.
467 AM.IndexReg = IndexReg;
469 AM.Disp = (uint32_t)Disp;
470 if (X86SelectAddress(U->getOperand(0), AM))
473 // If we couldn't merge the gep value into this addr mode, revert back to
474 // our address and just match the value instead of completely failing.
478 // Ok, the GEP indices weren't all covered.
483 // Handle constant address.
484 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
485 // Can't handle alternate code models yet.
486 if (TM.getCodeModel() != CodeModel::Small)
489 // Can't handle TLS yet.
490 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
491 if (GVar->isThreadLocal())
494 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
496 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
497 if (const GlobalVariable *GVar =
498 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
499 if (GVar->isThreadLocal())
502 // RIP-relative addresses can't have additional register operands, so if
503 // we've already folded stuff into the addressing mode, just force the
504 // global value into its own register, which we can use as the basereg.
505 if (!Subtarget->isPICStyleRIPRel() ||
506 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
507 // Okay, we've committed to selecting this global. Set up the address.
510 // Allow the subtarget to classify the global.
511 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
513 // If this reference is relative to the pic base, set it now.
514 if (isGlobalRelativeToPICBase(GVFlags)) {
515 // FIXME: How do we know Base.Reg is free??
516 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
519 // Unless the ABI requires an extra load, return a direct reference to
521 if (!isGlobalStubReference(GVFlags)) {
522 if (Subtarget->isPICStyleRIPRel()) {
523 // Use rip-relative addressing if we can. Above we verified that the
524 // base and index registers are unused.
525 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
526 AM.Base.Reg = X86::RIP;
528 AM.GVOpFlags = GVFlags;
532 // Ok, we need to do a load from a stub. If we've already loaded from
533 // this stub, reuse the loaded pointer, otherwise emit the load now.
534 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
536 if (I != LocalValueMap.end() && I->second != 0) {
539 // Issue load from stub.
541 const TargetRegisterClass *RC = NULL;
542 X86AddressMode StubAM;
543 StubAM.Base.Reg = AM.Base.Reg;
545 StubAM.GVOpFlags = GVFlags;
547 // Prepare for inserting code in the local-value area.
548 SavePoint SaveInsertPt = enterLocalValueArea();
550 if (TLI.getPointerTy() == MVT::i64) {
552 RC = &X86::GR64RegClass;
554 if (Subtarget->isPICStyleRIPRel())
555 StubAM.Base.Reg = X86::RIP;
558 RC = &X86::GR32RegClass;
561 LoadReg = createResultReg(RC);
562 MachineInstrBuilder LoadMI =
563 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
564 addFullAddress(LoadMI, StubAM);
566 // Ok, back to normal mode.
567 leaveLocalValueArea(SaveInsertPt);
569 // Prevent loading GV stub multiple times in same MBB.
570 LocalValueMap[V] = LoadReg;
573 // Now construct the final address. Note that the Disp, Scale,
574 // and Index values may already be set here.
575 AM.Base.Reg = LoadReg;
581 // If all else fails, try to materialize the value in a register.
582 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
583 if (AM.Base.Reg == 0) {
584 AM.Base.Reg = getRegForValue(V);
585 return AM.Base.Reg != 0;
587 if (AM.IndexReg == 0) {
588 assert(AM.Scale == 1 && "Scale with no index!");
589 AM.IndexReg = getRegForValue(V);
590 return AM.IndexReg != 0;
597 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
599 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
600 const User *U = NULL;
601 unsigned Opcode = Instruction::UserOp1;
602 if (const Instruction *I = dyn_cast<Instruction>(V)) {
603 Opcode = I->getOpcode();
605 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
606 Opcode = C->getOpcode();
612 case Instruction::BitCast:
613 // Look past bitcasts.
614 return X86SelectCallAddress(U->getOperand(0), AM);
616 case Instruction::IntToPtr:
617 // Look past no-op inttoptrs.
618 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
619 return X86SelectCallAddress(U->getOperand(0), AM);
622 case Instruction::PtrToInt:
623 // Look past no-op ptrtoints.
624 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
625 return X86SelectCallAddress(U->getOperand(0), AM);
629 // Handle constant address.
630 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
631 // Can't handle alternate code models yet.
632 if (TM.getCodeModel() != CodeModel::Small)
635 // RIP-relative addresses can't have additional register operands.
636 if (Subtarget->isPICStyleRIPRel() &&
637 (AM.Base.Reg != 0 || AM.IndexReg != 0))
640 // Can't handle DLLImport.
641 if (GV->hasDLLImportLinkage())
645 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
646 if (GVar->isThreadLocal())
649 // Okay, we've committed to selecting this global. Set up the basic address.
652 // No ABI requires an extra load for anything other than DLLImport, which
653 // we rejected above. Return a direct reference to the global.
654 if (Subtarget->isPICStyleRIPRel()) {
655 // Use rip-relative addressing if we can. Above we verified that the
656 // base and index registers are unused.
657 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
658 AM.Base.Reg = X86::RIP;
659 } else if (Subtarget->isPICStyleStubPIC()) {
660 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
661 } else if (Subtarget->isPICStyleGOT()) {
662 AM.GVOpFlags = X86II::MO_GOTOFF;
668 // If all else fails, try to materialize the value in a register.
669 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
670 if (AM.Base.Reg == 0) {
671 AM.Base.Reg = getRegForValue(V);
672 return AM.Base.Reg != 0;
674 if (AM.IndexReg == 0) {
675 assert(AM.Scale == 1 && "Scale with no index!");
676 AM.IndexReg = getRegForValue(V);
677 return AM.IndexReg != 0;
685 /// X86SelectStore - Select and emit code to implement store instructions.
686 bool X86FastISel::X86SelectStore(const Instruction *I) {
687 // Atomic stores need special handling.
688 const StoreInst *S = cast<StoreInst>(I);
693 unsigned SABIAlignment =
694 TD.getABITypeAlignment(S->getValueOperand()->getType());
695 if (S->getAlignment() != 0 && S->getAlignment() < SABIAlignment)
699 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
703 if (!X86SelectAddress(I->getOperand(1), AM))
706 return X86FastEmitStore(VT, I->getOperand(0), AM);
709 /// X86SelectRet - Select and emit code to implement ret instructions.
710 bool X86FastISel::X86SelectRet(const Instruction *I) {
711 const ReturnInst *Ret = cast<ReturnInst>(I);
712 const Function &F = *I->getParent()->getParent();
713 const X86MachineFunctionInfo *X86MFInfo =
714 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
716 if (!FuncInfo.CanLowerReturn)
719 CallingConv::ID CC = F.getCallingConv();
720 if (CC != CallingConv::C &&
721 CC != CallingConv::Fast &&
722 CC != CallingConv::X86_FastCall)
725 if (Subtarget->isTargetWin64())
728 // Don't handle popping bytes on return for now.
729 if (X86MFInfo->getBytesToPopOnReturn() != 0)
732 // fastcc with -tailcallopt is intended to provide a guaranteed
733 // tail call optimization. Fastisel doesn't know how to do that.
734 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
737 // Let SDISel handle vararg functions.
741 if (Ret->getNumOperands() > 0) {
742 SmallVector<ISD::OutputArg, 4> Outs;
743 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
745 // Analyze operands of the call, assigning locations to each operand.
746 SmallVector<CCValAssign, 16> ValLocs;
747 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
749 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
751 const Value *RV = Ret->getOperand(0);
752 unsigned Reg = getRegForValue(RV);
756 // Only handle a single return value for now.
757 if (ValLocs.size() != 1)
760 CCValAssign &VA = ValLocs[0];
762 // Don't bother handling odd stuff for now.
763 if (VA.getLocInfo() != CCValAssign::Full)
765 // Only handle register returns for now.
769 // The calling-convention tables for x87 returns don't tell
771 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
774 unsigned SrcReg = Reg + VA.getValNo();
775 EVT SrcVT = TLI.getValueType(RV->getType());
776 EVT DstVT = VA.getValVT();
777 // Special handling for extended integers.
778 if (SrcVT != DstVT) {
779 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
782 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
785 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
787 if (SrcVT == MVT::i1) {
788 if (Outs[0].Flags.isSExt())
790 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
793 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
795 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
796 SrcReg, /*TODO: Kill=*/false);
800 unsigned DstReg = VA.getLocReg();
801 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
802 // Avoid a cross-class copy. This is very unlikely.
803 if (!SrcRC->contains(DstReg))
805 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
806 DstReg).addReg(SrcReg);
808 // Mark the register as live out of the function.
809 MRI.addLiveOut(VA.getLocReg());
812 // The x86-64 ABI for returning structs by value requires that we copy
813 // the sret argument into %rax for the return. We saved the argument into
814 // a virtual register in the entry block, so now we copy the value out
816 if (Subtarget->is64Bit() && F.hasStructRetAttr()) {
817 unsigned Reg = X86MFInfo->getSRetReturnReg();
819 "SRetReturnReg should have been set in LowerFormalArguments()!");
820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
821 X86::RAX).addReg(Reg);
822 MRI.addLiveOut(X86::RAX);
826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
830 /// X86SelectLoad - Select and emit code to implement load instructions.
832 bool X86FastISel::X86SelectLoad(const Instruction *I) {
833 // Atomic loads need special handling.
834 if (cast<LoadInst>(I)->isAtomic())
838 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
842 if (!X86SelectAddress(I->getOperand(0), AM))
845 unsigned ResultReg = 0;
846 if (X86FastEmitLoad(VT, AM, ResultReg)) {
847 UpdateValueMap(I, ResultReg);
853 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
854 bool HasAVX = Subtarget->hasAVX();
855 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
856 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
858 switch (VT.getSimpleVT().SimpleTy) {
860 case MVT::i8: return X86::CMP8rr;
861 case MVT::i16: return X86::CMP16rr;
862 case MVT::i32: return X86::CMP32rr;
863 case MVT::i64: return X86::CMP64rr;
865 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
867 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
871 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
872 /// of the comparison, return an opcode that works for the compare (e.g.
873 /// CMP32ri) otherwise return 0.
874 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
875 switch (VT.getSimpleVT().SimpleTy) {
876 // Otherwise, we can't fold the immediate into this comparison.
878 case MVT::i8: return X86::CMP8ri;
879 case MVT::i16: return X86::CMP16ri;
880 case MVT::i32: return X86::CMP32ri;
882 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
884 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
885 return X86::CMP64ri32;
890 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
892 unsigned Op0Reg = getRegForValue(Op0);
893 if (Op0Reg == 0) return false;
895 // Handle 'null' like i32/i64 0.
896 if (isa<ConstantPointerNull>(Op1))
897 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
899 // We have two options: compare with register or immediate. If the RHS of
900 // the compare is an immediate that we can fold into this compare, use
901 // CMPri, otherwise use CMPrr.
902 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
903 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
906 .addImm(Op1C->getSExtValue());
911 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
912 if (CompareOpc == 0) return false;
914 unsigned Op1Reg = getRegForValue(Op1);
915 if (Op1Reg == 0) return false;
916 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
923 bool X86FastISel::X86SelectCmp(const Instruction *I) {
924 const CmpInst *CI = cast<CmpInst>(I);
927 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
930 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
932 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
933 switch (CI->getPredicate()) {
934 case CmpInst::FCMP_OEQ: {
935 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
938 unsigned EReg = createResultReg(&X86::GR8RegClass);
939 unsigned NPReg = createResultReg(&X86::GR8RegClass);
940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
942 TII.get(X86::SETNPr), NPReg);
943 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
944 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
945 UpdateValueMap(I, ResultReg);
948 case CmpInst::FCMP_UNE: {
949 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
952 unsigned NEReg = createResultReg(&X86::GR8RegClass);
953 unsigned PReg = createResultReg(&X86::GR8RegClass);
954 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
955 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
957 .addReg(PReg).addReg(NEReg);
958 UpdateValueMap(I, ResultReg);
961 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
962 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
963 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
964 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
965 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
966 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
967 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
968 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
969 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
970 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
971 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
972 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
974 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
975 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
976 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
977 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
978 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
979 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
980 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
981 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
982 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
983 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
988 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
992 // Emit a compare of Op0/Op1.
993 if (!X86FastEmitCompare(Op0, Op1, VT))
996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
997 UpdateValueMap(I, ResultReg);
1001 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1002 // Handle zero-extension from i1 to i8, which is common.
1003 if (!I->getOperand(0)->getType()->isIntegerTy(1))
1006 EVT DstVT = TLI.getValueType(I->getType());
1007 if (!TLI.isTypeLegal(DstVT))
1010 unsigned ResultReg = getRegForValue(I->getOperand(0));
1014 // Set the high bits to zero.
1015 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1019 if (DstVT != MVT::i8) {
1020 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1021 ResultReg, /*Kill=*/true);
1026 UpdateValueMap(I, ResultReg);
1031 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1032 // Unconditional branches are selected by tablegen-generated code.
1033 // Handle a conditional branch.
1034 const BranchInst *BI = cast<BranchInst>(I);
1035 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1036 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1038 // Fold the common case of a conditional branch with a comparison
1039 // in the same block (values defined on other blocks may not have
1040 // initialized registers).
1041 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1042 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1043 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1045 // Try to take advantage of fallthrough opportunities.
1046 CmpInst::Predicate Predicate = CI->getPredicate();
1047 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1048 std::swap(TrueMBB, FalseMBB);
1049 Predicate = CmpInst::getInversePredicate(Predicate);
1052 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1053 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1055 switch (Predicate) {
1056 case CmpInst::FCMP_OEQ:
1057 std::swap(TrueMBB, FalseMBB);
1058 Predicate = CmpInst::FCMP_UNE;
1060 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1061 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1062 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1063 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1064 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1065 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1066 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1067 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1068 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1069 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1070 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1071 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1072 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1074 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1075 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1076 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1077 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1078 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1079 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1080 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1081 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1082 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1083 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1088 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1090 std::swap(Op0, Op1);
1092 // Emit a compare of the LHS and RHS, setting the flags.
1093 if (!X86FastEmitCompare(Op0, Op1, VT))
1096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1099 if (Predicate == CmpInst::FCMP_UNE) {
1100 // X86 requires a second branch to handle UNE (and OEQ,
1101 // which is mapped to UNE above).
1102 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1106 FastEmitBranch(FalseMBB, DL);
1107 FuncInfo.MBB->addSuccessor(TrueMBB);
1110 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1111 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1112 // typically happen for _Bool and C++ bools.
1114 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1115 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1116 unsigned TestOpc = 0;
1117 switch (SourceVT.SimpleTy) {
1119 case MVT::i8: TestOpc = X86::TEST8ri; break;
1120 case MVT::i16: TestOpc = X86::TEST16ri; break;
1121 case MVT::i32: TestOpc = X86::TEST32ri; break;
1122 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1125 unsigned OpReg = getRegForValue(TI->getOperand(0));
1126 if (OpReg == 0) return false;
1127 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1128 .addReg(OpReg).addImm(1);
1130 unsigned JmpOpc = X86::JNE_4;
1131 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1132 std::swap(TrueMBB, FalseMBB);
1136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1138 FastEmitBranch(FalseMBB, DL);
1139 FuncInfo.MBB->addSuccessor(TrueMBB);
1145 // Otherwise do a clumsy setcc and re-test it.
1146 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1147 // in an explicit cast, so make sure to handle that correctly.
1148 unsigned OpReg = getRegForValue(BI->getCondition());
1149 if (OpReg == 0) return false;
1151 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1152 .addReg(OpReg).addImm(1);
1153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1155 FastEmitBranch(FalseMBB, DL);
1156 FuncInfo.MBB->addSuccessor(TrueMBB);
1160 bool X86FastISel::X86SelectShift(const Instruction *I) {
1161 unsigned CReg = 0, OpReg = 0;
1162 const TargetRegisterClass *RC = NULL;
1163 if (I->getType()->isIntegerTy(8)) {
1165 RC = &X86::GR8RegClass;
1166 switch (I->getOpcode()) {
1167 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1168 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1169 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1170 default: return false;
1172 } else if (I->getType()->isIntegerTy(16)) {
1174 RC = &X86::GR16RegClass;
1175 switch (I->getOpcode()) {
1176 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1177 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1178 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1179 default: return false;
1181 } else if (I->getType()->isIntegerTy(32)) {
1183 RC = &X86::GR32RegClass;
1184 switch (I->getOpcode()) {
1185 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1186 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1187 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1188 default: return false;
1190 } else if (I->getType()->isIntegerTy(64)) {
1192 RC = &X86::GR64RegClass;
1193 switch (I->getOpcode()) {
1194 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1195 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1196 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1197 default: return false;
1204 if (!isTypeLegal(I->getType(), VT))
1207 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1208 if (Op0Reg == 0) return false;
1210 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1211 if (Op1Reg == 0) return false;
1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1213 CReg).addReg(Op1Reg);
1215 // The shift instruction uses X86::CL. If we defined a super-register
1216 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1217 if (CReg != X86::CL)
1218 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1219 TII.get(TargetOpcode::KILL), X86::CL)
1220 .addReg(CReg, RegState::Kill);
1222 unsigned ResultReg = createResultReg(RC);
1223 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1225 UpdateValueMap(I, ResultReg);
1229 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1231 if (!isTypeLegal(I->getType(), VT))
1234 // We only use cmov here, if we don't have a cmov instruction bail.
1235 if (!Subtarget->hasCMov()) return false;
1238 const TargetRegisterClass *RC = NULL;
1239 if (VT == MVT::i16) {
1240 Opc = X86::CMOVE16rr;
1241 RC = &X86::GR16RegClass;
1242 } else if (VT == MVT::i32) {
1243 Opc = X86::CMOVE32rr;
1244 RC = &X86::GR32RegClass;
1245 } else if (VT == MVT::i64) {
1246 Opc = X86::CMOVE64rr;
1247 RC = &X86::GR64RegClass;
1252 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1253 if (Op0Reg == 0) return false;
1254 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1255 if (Op1Reg == 0) return false;
1256 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1257 if (Op2Reg == 0) return false;
1259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1260 .addReg(Op0Reg).addReg(Op0Reg);
1261 unsigned ResultReg = createResultReg(RC);
1262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1263 .addReg(Op1Reg).addReg(Op2Reg);
1264 UpdateValueMap(I, ResultReg);
1268 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1269 // fpext from float to double.
1270 if (X86ScalarSSEf64 &&
1271 I->getType()->isDoubleTy()) {
1272 const Value *V = I->getOperand(0);
1273 if (V->getType()->isFloatTy()) {
1274 unsigned OpReg = getRegForValue(V);
1275 if (OpReg == 0) return false;
1276 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1278 TII.get(X86::CVTSS2SDrr), ResultReg)
1280 UpdateValueMap(I, ResultReg);
1288 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1289 if (X86ScalarSSEf64) {
1290 if (I->getType()->isFloatTy()) {
1291 const Value *V = I->getOperand(0);
1292 if (V->getType()->isDoubleTy()) {
1293 unsigned OpReg = getRegForValue(V);
1294 if (OpReg == 0) return false;
1295 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1297 TII.get(X86::CVTSD2SSrr), ResultReg)
1299 UpdateValueMap(I, ResultReg);
1308 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1309 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1310 EVT DstVT = TLI.getValueType(I->getType());
1312 // This code only handles truncation to byte.
1313 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1315 if (!TLI.isTypeLegal(SrcVT))
1318 unsigned InputReg = getRegForValue(I->getOperand(0));
1320 // Unhandled operand. Halt "fast" selection and bail.
1323 if (SrcVT == MVT::i8) {
1324 // Truncate from i8 to i1; no code needed.
1325 UpdateValueMap(I, InputReg);
1329 if (!Subtarget->is64Bit()) {
1330 // If we're on x86-32; we can't extract an i8 from a general register.
1331 // First issue a copy to GR16_ABCD or GR32_ABCD.
1332 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1333 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1334 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1335 unsigned CopyReg = createResultReg(CopyRC);
1336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1337 CopyReg).addReg(InputReg);
1341 // Issue an extract_subreg.
1342 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1343 InputReg, /*Kill=*/true,
1348 UpdateValueMap(I, ResultReg);
1352 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1353 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1356 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1357 X86AddressMode SrcAM, uint64_t Len) {
1359 // Make sure we don't bloat code by inlining very large memcpy's.
1360 if (!IsMemcpySmall(Len))
1363 bool i64Legal = Subtarget->is64Bit();
1365 // We don't care about alignment here since we just emit integer accesses.
1368 if (Len >= 8 && i64Legal)
1380 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1381 RV &= X86FastEmitStore(VT, Reg, DestAM);
1382 assert(RV && "Failed to emit load or store??");
1384 unsigned Size = VT.getSizeInBits()/8;
1386 DestAM.Disp += Size;
1393 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1394 // FIXME: Handle more intrinsics.
1395 switch (I.getIntrinsicID()) {
1396 default: return false;
1397 case Intrinsic::memcpy: {
1398 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1399 // Don't handle volatile or variable length memcpys.
1400 if (MCI.isVolatile())
1403 if (isa<ConstantInt>(MCI.getLength())) {
1404 // Small memcpy's are common enough that we want to do them
1405 // without a call if possible.
1406 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1407 if (IsMemcpySmall(Len)) {
1408 X86AddressMode DestAM, SrcAM;
1409 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1410 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1412 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1417 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1418 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1421 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1424 return DoSelectCall(&I, "memcpy");
1426 case Intrinsic::memset: {
1427 const MemSetInst &MSI = cast<MemSetInst>(I);
1429 if (MSI.isVolatile())
1432 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1433 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1436 if (MSI.getDestAddressSpace() > 255)
1439 return DoSelectCall(&I, "memset");
1441 case Intrinsic::stackprotector: {
1442 // Emit code to store the stack guard onto the stack.
1443 EVT PtrTy = TLI.getPointerTy();
1445 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1446 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1448 // Grab the frame index.
1450 if (!X86SelectAddress(Slot, AM)) return false;
1451 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1454 case Intrinsic::dbg_declare: {
1455 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1457 assert(DI->getAddress() && "Null address should be checked earlier!");
1458 if (!X86SelectAddress(DI->getAddress(), AM))
1460 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1461 // FIXME may need to add RegState::Debug to any registers produced,
1462 // although ESP/EBP should be the only ones at the moment.
1463 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1464 addImm(0).addMetadata(DI->getVariable());
1467 case Intrinsic::trap: {
1468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1471 case Intrinsic::sadd_with_overflow:
1472 case Intrinsic::uadd_with_overflow: {
1473 // FIXME: Should fold immediates.
1475 // Replace "add with overflow" intrinsics with an "add" instruction followed
1476 // by a seto/setc instruction.
1477 const Function *Callee = I.getCalledFunction();
1479 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1482 if (!isTypeLegal(RetTy, VT))
1485 const Value *Op1 = I.getArgOperand(0);
1486 const Value *Op2 = I.getArgOperand(1);
1487 unsigned Reg1 = getRegForValue(Op1);
1488 unsigned Reg2 = getRegForValue(Op2);
1490 if (Reg1 == 0 || Reg2 == 0)
1491 // FIXME: Handle values *not* in registers.
1497 else if (VT == MVT::i64)
1502 // The call to CreateRegs builds two sequential registers, to store the
1503 // both the returned values.
1504 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1505 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1506 .addReg(Reg1).addReg(Reg2);
1508 unsigned Opc = X86::SETBr;
1509 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1513 UpdateValueMap(&I, ResultReg, 2);
1519 bool X86FastISel::X86SelectCall(const Instruction *I) {
1520 const CallInst *CI = cast<CallInst>(I);
1521 const Value *Callee = CI->getCalledValue();
1523 // Can't handle inline asm yet.
1524 if (isa<InlineAsm>(Callee))
1527 // Handle intrinsic calls.
1528 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1529 return X86VisitIntrinsicCall(*II);
1531 // Allow SelectionDAG isel to handle tail calls.
1532 if (cast<CallInst>(I)->isTailCall())
1535 return DoSelectCall(I, 0);
1538 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1539 const ImmutableCallSite &CS) {
1540 if (Subtarget.is64Bit())
1542 if (Subtarget.isTargetWindows())
1544 CallingConv::ID CC = CS.getCallingConv();
1545 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1547 if (!CS.paramHasAttr(1, Attribute::StructRet))
1549 if (CS.paramHasAttr(1, Attribute::InReg))
1554 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1555 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1556 const CallInst *CI = cast<CallInst>(I);
1557 const Value *Callee = CI->getCalledValue();
1559 // Handle only C and fastcc calling conventions for now.
1560 ImmutableCallSite CS(CI);
1561 CallingConv::ID CC = CS.getCallingConv();
1562 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1563 CC != CallingConv::X86_FastCall)
1566 // fastcc with -tailcallopt is intended to provide a guaranteed
1567 // tail call optimization. Fastisel doesn't know how to do that.
1568 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1571 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1572 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1573 bool isVarArg = FTy->isVarArg();
1575 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1576 // x86-32. Special handling for x86-64 is implemented.
1577 if (isVarArg && Subtarget->isTargetWin64())
1580 // Fast-isel doesn't know about callee-pop yet.
1581 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1582 TM.Options.GuaranteedTailCallOpt))
1585 // Check whether the function can return without sret-demotion.
1586 SmallVector<ISD::OutputArg, 4> Outs;
1587 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1588 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1589 *FuncInfo.MF, FTy->isVarArg(),
1590 Outs, FTy->getContext());
1591 if (!CanLowerReturn)
1594 // Materialize callee address in a register. FIXME: GV address can be
1595 // handled with a CALLpcrel32 instead.
1596 X86AddressMode CalleeAM;
1597 if (!X86SelectCallAddress(Callee, CalleeAM))
1599 unsigned CalleeOp = 0;
1600 const GlobalValue *GV = 0;
1601 if (CalleeAM.GV != 0) {
1603 } else if (CalleeAM.Base.Reg != 0) {
1604 CalleeOp = CalleeAM.Base.Reg;
1608 // Deal with call operands first.
1609 SmallVector<const Value *, 8> ArgVals;
1610 SmallVector<unsigned, 8> Args;
1611 SmallVector<MVT, 8> ArgVTs;
1612 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1613 unsigned arg_size = CS.arg_size();
1614 Args.reserve(arg_size);
1615 ArgVals.reserve(arg_size);
1616 ArgVTs.reserve(arg_size);
1617 ArgFlags.reserve(arg_size);
1618 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1620 // If we're lowering a mem intrinsic instead of a regular call, skip the
1621 // last two arguments, which should not passed to the underlying functions.
1622 if (MemIntName && e-i <= 2)
1625 ISD::ArgFlagsTy Flags;
1626 unsigned AttrInd = i - CS.arg_begin() + 1;
1627 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1629 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1632 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1633 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1634 Type *ElementTy = Ty->getElementType();
1635 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1636 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1638 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1640 Flags.setByValSize(FrameSize);
1641 Flags.setByValAlign(FrameAlign);
1642 if (!IsMemcpySmall(FrameSize))
1646 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1648 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1651 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1652 // instruction. This is safe because it is common to all fastisel supported
1653 // calling conventions on x86.
1654 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1655 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1656 CI->getBitWidth() == 16) {
1658 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1660 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1666 // Passing bools around ends up doing a trunc to i1 and passing it.
1667 // Codegen this as an argument + "and 1".
1668 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1669 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1670 ArgVal->hasOneUse()) {
1671 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1672 ArgReg = getRegForValue(ArgVal);
1673 if (ArgReg == 0) return false;
1676 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1678 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1679 ArgVal->hasOneUse(), 1);
1681 ArgReg = getRegForValue(ArgVal);
1684 if (ArgReg == 0) return false;
1686 Type *ArgTy = ArgVal->getType();
1688 if (!isTypeLegal(ArgTy, ArgVT))
1690 if (ArgVT == MVT::x86mmx)
1692 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1693 Flags.setOrigAlign(OriginalAlignment);
1695 Args.push_back(ArgReg);
1696 ArgVals.push_back(ArgVal);
1697 ArgVTs.push_back(ArgVT);
1698 ArgFlags.push_back(Flags);
1701 // Analyze operands of the call, assigning locations to each operand.
1702 SmallVector<CCValAssign, 16> ArgLocs;
1703 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1704 I->getParent()->getContext());
1706 // Allocate shadow area for Win64
1707 if (Subtarget->isTargetWin64())
1708 CCInfo.AllocateStack(32, 8);
1710 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1712 // Get a count of how many bytes are to be pushed on the stack.
1713 unsigned NumBytes = CCInfo.getNextStackOffset();
1715 // Issue CALLSEQ_START
1716 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1717 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1720 // Process argument: walk the register/memloc assignments, inserting
1722 SmallVector<unsigned, 4> RegArgs;
1723 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1724 CCValAssign &VA = ArgLocs[i];
1725 unsigned Arg = Args[VA.getValNo()];
1726 EVT ArgVT = ArgVTs[VA.getValNo()];
1728 // Promote the value if needed.
1729 switch (VA.getLocInfo()) {
1730 case CCValAssign::Full: break;
1731 case CCValAssign::SExt: {
1732 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1733 "Unexpected extend");
1734 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1736 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1737 ArgVT = VA.getLocVT();
1740 case CCValAssign::ZExt: {
1741 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1742 "Unexpected extend");
1743 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1745 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1746 ArgVT = VA.getLocVT();
1749 case CCValAssign::AExt: {
1750 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1751 "Unexpected extend");
1752 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1755 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1758 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1761 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1762 ArgVT = VA.getLocVT();
1765 case CCValAssign::BCvt: {
1766 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1767 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1768 assert(BC != 0 && "Failed to emit a bitcast!");
1770 ArgVT = VA.getLocVT();
1773 case CCValAssign::VExt:
1774 // VExt has not been implemented, so this should be impossible to reach
1775 // for now. However, fallback to Selection DAG isel once implemented.
1777 case CCValAssign::Indirect:
1778 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
1783 if (VA.isRegLoc()) {
1784 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1785 VA.getLocReg()).addReg(Arg);
1786 RegArgs.push_back(VA.getLocReg());
1788 unsigned LocMemOffset = VA.getLocMemOffset();
1790 AM.Base.Reg = RegInfo->getStackRegister();
1791 AM.Disp = LocMemOffset;
1792 const Value *ArgVal = ArgVals[VA.getValNo()];
1793 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1795 if (Flags.isByVal()) {
1796 X86AddressMode SrcAM;
1797 SrcAM.Base.Reg = Arg;
1798 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
1799 assert(Res && "memcpy length already checked!"); (void)Res;
1800 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
1801 // If this is a really simple value, emit this with the Value* version
1802 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
1803 // as it can cause us to reevaluate the argument.
1804 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
1807 if (!X86FastEmitStore(ArgVT, Arg, AM))
1813 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1815 if (Subtarget->isPICStyleGOT()) {
1816 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1818 X86::EBX).addReg(Base);
1821 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1822 // Count the number of XMM registers allocated.
1823 static const uint16_t XMMArgRegs[] = {
1824 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1825 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1827 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1829 X86::AL).addImm(NumXMMRegs);
1833 MachineInstrBuilder MIB;
1835 // Register-indirect call.
1837 if (Subtarget->is64Bit())
1838 CallOpc = X86::CALL64r;
1840 CallOpc = X86::CALL32r;
1841 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1846 assert(GV && "Not a direct call");
1848 if (Subtarget->is64Bit())
1849 CallOpc = X86::CALL64pcrel32;
1851 CallOpc = X86::CALLpcrel32;
1853 // See if we need any target-specific flags on the GV operand.
1854 unsigned char OpFlags = 0;
1856 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1857 // external symbols most go through the PLT in PIC mode. If the symbol
1858 // has hidden or protected visibility, or if it is static or local, then
1859 // we don't need to use the PLT - we can directly call it.
1860 if (Subtarget->isTargetELF() &&
1861 TM.getRelocationModel() == Reloc::PIC_ &&
1862 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1863 OpFlags = X86II::MO_PLT;
1864 } else if (Subtarget->isPICStyleStubAny() &&
1865 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1866 (!Subtarget->getTargetTriple().isMacOSX() ||
1867 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1868 // PC-relative references to external symbols should go through $stub,
1869 // unless we're building with the leopard linker or later, which
1870 // automatically synthesizes these stubs.
1871 OpFlags = X86II::MO_DARWIN_STUB;
1875 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
1877 MIB.addExternalSymbol(MemIntName, OpFlags);
1879 MIB.addGlobalAddress(GV, 0, OpFlags);
1882 // Add a register mask with the call-preserved registers.
1883 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1884 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
1886 // Add an implicit use GOT pointer in EBX.
1887 if (Subtarget->isPICStyleGOT())
1888 MIB.addReg(X86::EBX, RegState::Implicit);
1890 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1891 MIB.addReg(X86::AL, RegState::Implicit);
1893 // Add implicit physical register uses to the call.
1894 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1895 MIB.addReg(RegArgs[i], RegState::Implicit);
1897 // Issue CALLSEQ_END
1898 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1899 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
1900 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1901 .addImm(NumBytes).addImm(NumBytesCallee);
1903 // Build info for return calling conv lowering code.
1904 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
1905 SmallVector<ISD::InputArg, 32> Ins;
1906 SmallVector<EVT, 4> RetTys;
1907 ComputeValueVTs(TLI, I->getType(), RetTys);
1908 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
1910 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
1911 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
1912 for (unsigned j = 0; j != NumRegs; ++j) {
1913 ISD::InputArg MyFlags;
1914 MyFlags.VT = RegisterVT;
1915 MyFlags.Used = !CS.getInstruction()->use_empty();
1916 if (CS.paramHasAttr(0, Attribute::SExt))
1917 MyFlags.Flags.setSExt();
1918 if (CS.paramHasAttr(0, Attribute::ZExt))
1919 MyFlags.Flags.setZExt();
1920 if (CS.paramHasAttr(0, Attribute::InReg))
1921 MyFlags.Flags.setInReg();
1922 Ins.push_back(MyFlags);
1926 // Now handle call return values.
1927 SmallVector<unsigned, 4> UsedRegs;
1928 SmallVector<CCValAssign, 16> RVLocs;
1929 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
1930 I->getParent()->getContext());
1931 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
1932 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
1933 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1934 EVT CopyVT = RVLocs[i].getValVT();
1935 unsigned CopyReg = ResultReg + i;
1937 // If this is a call to a function that returns an fp value on the x87 fp
1938 // stack, but where we prefer to use the value in xmm registers, copy it
1939 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1940 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1941 RVLocs[i].getLocReg() == X86::ST1)) {
1942 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1944 CopyReg = createResultReg(&X86::RFP80RegClass);
1946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
1949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1950 CopyReg).addReg(RVLocs[i].getLocReg());
1951 UsedRegs.push_back(RVLocs[i].getLocReg());
1954 if (CopyVT != RVLocs[i].getValVT()) {
1955 // Round the F80 the right size, which also moves to the appropriate xmm
1956 // register. This is accomplished by storing the F80 value in memory and
1957 // then loading it back. Ewww...
1958 EVT ResVT = RVLocs[i].getValVT();
1959 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1960 unsigned MemSize = ResVT.getSizeInBits()/8;
1961 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1962 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1965 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1966 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1967 TII.get(Opc), ResultReg + i), FI);
1972 UpdateValueMap(I, ResultReg, RVLocs.size());
1974 // Set all unused physreg defs as dead.
1975 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1982 X86FastISel::TargetSelectInstruction(const Instruction *I) {
1983 switch (I->getOpcode()) {
1985 case Instruction::Load:
1986 return X86SelectLoad(I);
1987 case Instruction::Store:
1988 return X86SelectStore(I);
1989 case Instruction::Ret:
1990 return X86SelectRet(I);
1991 case Instruction::ICmp:
1992 case Instruction::FCmp:
1993 return X86SelectCmp(I);
1994 case Instruction::ZExt:
1995 return X86SelectZExt(I);
1996 case Instruction::Br:
1997 return X86SelectBranch(I);
1998 case Instruction::Call:
1999 return X86SelectCall(I);
2000 case Instruction::LShr:
2001 case Instruction::AShr:
2002 case Instruction::Shl:
2003 return X86SelectShift(I);
2004 case Instruction::Select:
2005 return X86SelectSelect(I);
2006 case Instruction::Trunc:
2007 return X86SelectTrunc(I);
2008 case Instruction::FPExt:
2009 return X86SelectFPExt(I);
2010 case Instruction::FPTrunc:
2011 return X86SelectFPTrunc(I);
2012 case Instruction::IntToPtr: // Deliberate fall-through.
2013 case Instruction::PtrToInt: {
2014 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2015 EVT DstVT = TLI.getValueType(I->getType());
2016 if (DstVT.bitsGT(SrcVT))
2017 return X86SelectZExt(I);
2018 if (DstVT.bitsLT(SrcVT))
2019 return X86SelectTrunc(I);
2020 unsigned Reg = getRegForValue(I->getOperand(0));
2021 if (Reg == 0) return false;
2022 UpdateValueMap(I, Reg);
2030 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2032 if (!isTypeLegal(C->getType(), VT))
2035 // Can't handle alternate code models yet.
2036 if (TM.getCodeModel() != CodeModel::Small)
2039 // Get opcode and regclass of the output for the given load instruction.
2041 const TargetRegisterClass *RC = NULL;
2042 switch (VT.SimpleTy) {
2046 RC = &X86::GR8RegClass;
2050 RC = &X86::GR16RegClass;
2054 RC = &X86::GR32RegClass;
2057 // Must be in x86-64 mode.
2059 RC = &X86::GR64RegClass;
2062 if (X86ScalarSSEf32) {
2063 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2064 RC = &X86::FR32RegClass;
2066 Opc = X86::LD_Fp32m;
2067 RC = &X86::RFP32RegClass;
2071 if (X86ScalarSSEf64) {
2072 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2073 RC = &X86::FR64RegClass;
2075 Opc = X86::LD_Fp64m;
2076 RC = &X86::RFP64RegClass;
2080 // No f80 support yet.
2084 // Materialize addresses with LEA instructions.
2085 if (isa<GlobalValue>(C)) {
2087 if (X86SelectAddress(C, AM)) {
2088 // If the expression is just a basereg, then we're done, otherwise we need
2090 if (AM.BaseType == X86AddressMode::RegBase &&
2091 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2094 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2095 unsigned ResultReg = createResultReg(RC);
2096 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2097 TII.get(Opc), ResultReg), AM);
2103 // MachineConstantPool wants an explicit alignment.
2104 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2106 // Alignment of vector types. FIXME!
2107 Align = TD.getTypeAllocSize(C->getType());
2110 // x86-32 PIC requires a PIC base register for constant pools.
2111 unsigned PICBase = 0;
2112 unsigned char OpFlag = 0;
2113 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2114 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2115 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2116 } else if (Subtarget->isPICStyleGOT()) {
2117 OpFlag = X86II::MO_GOTOFF;
2118 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2119 } else if (Subtarget->isPICStyleRIPRel() &&
2120 TM.getCodeModel() == CodeModel::Small) {
2124 // Create the load from the constant pool.
2125 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2126 unsigned ResultReg = createResultReg(RC);
2127 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2128 TII.get(Opc), ResultReg),
2129 MCPOffset, PICBase, OpFlag);
2134 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2135 // Fail on dynamic allocas. At this point, getRegForValue has already
2136 // checked its CSE maps, so if we're here trying to handle a dynamic
2137 // alloca, we're not going to succeed. X86SelectAddress has a
2138 // check for dynamic allocas, because it's called directly from
2139 // various places, but TargetMaterializeAlloca also needs a check
2140 // in order to avoid recursion between getRegForValue,
2141 // X86SelectAddrss, and TargetMaterializeAlloca.
2142 if (!FuncInfo.StaticAllocaMap.count(C))
2146 if (!X86SelectAddress(C, AM))
2148 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2149 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2150 unsigned ResultReg = createResultReg(RC);
2151 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2152 TII.get(Opc), ResultReg), AM);
2156 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2158 if (!isTypeLegal(CF->getType(), VT))
2161 // Get opcode and regclass for the given zero.
2163 const TargetRegisterClass *RC = NULL;
2164 switch (VT.SimpleTy) {
2167 if (X86ScalarSSEf32) {
2168 Opc = X86::FsFLD0SS;
2169 RC = &X86::FR32RegClass;
2171 Opc = X86::LD_Fp032;
2172 RC = &X86::RFP32RegClass;
2176 if (X86ScalarSSEf64) {
2177 Opc = X86::FsFLD0SD;
2178 RC = &X86::FR64RegClass;
2180 Opc = X86::LD_Fp064;
2181 RC = &X86::RFP64RegClass;
2185 // No f80 support yet.
2189 unsigned ResultReg = createResultReg(RC);
2190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2195 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2196 /// vreg is being provided by the specified load instruction. If possible,
2197 /// try to fold the load as an operand to the instruction, returning true if
2199 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2200 const LoadInst *LI) {
2202 if (!X86SelectAddress(LI->getOperand(0), AM))
2205 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2207 unsigned Size = TD.getTypeAllocSize(LI->getType());
2208 unsigned Alignment = LI->getAlignment();
2210 SmallVector<MachineOperand, 8> AddrOps;
2211 AM.getFullAddress(AddrOps);
2213 MachineInstr *Result =
2214 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2215 if (Result == 0) return false;
2217 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2218 MI->eraseFromParent();
2224 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2225 const TargetLibraryInfo *libInfo) {
2226 return new X86FastISel(funcInfo, libInfo);