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/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetOptions.h"
42 class X86FastISel : public FastISel {
43 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
44 /// make the right decision when generating code for different targets.
45 const X86Subtarget *Subtarget;
47 /// StackPtr - Register used as the stack pointer.
51 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52 /// floating point ops.
53 /// When SSE is available, use it for f32 operations.
54 /// When SSE2 is available, use it for f64 operations.
59 explicit X86FastISel(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo) {
60 Subtarget = &TM.getSubtarget<X86Subtarget>();
61 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
62 X86ScalarSSEf64 = Subtarget->hasSSE2() || Subtarget->hasAVX();
63 X86ScalarSSEf32 = Subtarget->hasSSE1() || Subtarget->hasAVX();
66 virtual bool TargetSelectInstruction(const Instruction *I);
68 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
69 /// vreg is being provided by the specified load instruction. If possible,
70 /// try to fold the load as an operand to the instruction, returning true if
72 virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
75 #include "X86GenFastISel.inc"
78 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
80 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
82 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
83 bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
85 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
88 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
89 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
91 bool X86SelectLoad(const Instruction *I);
93 bool X86SelectStore(const Instruction *I);
95 bool X86SelectRet(const Instruction *I);
97 bool X86SelectCmp(const Instruction *I);
99 bool X86SelectZExt(const Instruction *I);
101 bool X86SelectBranch(const Instruction *I);
103 bool X86SelectShift(const Instruction *I);
105 bool X86SelectSelect(const Instruction *I);
107 bool X86SelectTrunc(const Instruction *I);
109 bool X86SelectFPExt(const Instruction *I);
110 bool X86SelectFPTrunc(const Instruction *I);
112 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
113 bool X86SelectCall(const Instruction *I);
115 bool DoSelectCall(const Instruction *I, const char *MemIntName);
117 const X86InstrInfo *getInstrInfo() const {
118 return getTargetMachine()->getInstrInfo();
120 const X86TargetMachine *getTargetMachine() const {
121 return static_cast<const X86TargetMachine *>(&TM);
124 unsigned TargetMaterializeConstant(const Constant *C);
126 unsigned TargetMaterializeAlloca(const AllocaInst *C);
128 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
130 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
131 /// computed in an SSE register, not on the X87 floating point stack.
132 bool isScalarFPTypeInSSEReg(EVT VT) const {
133 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
134 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
137 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
139 bool IsMemcpySmall(uint64_t Len);
141 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
142 X86AddressMode SrcAM, uint64_t Len);
145 } // end anonymous namespace.
147 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
148 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
149 if (evt == MVT::Other || !evt.isSimple())
150 // Unhandled type. Halt "fast" selection and bail.
153 VT = evt.getSimpleVT();
154 // For now, require SSE/SSE2 for performing floating-point operations,
155 // since x87 requires additional work.
156 if (VT == MVT::f64 && !X86ScalarSSEf64)
158 if (VT == MVT::f32 && !X86ScalarSSEf32)
160 // Similarly, no f80 support yet.
163 // We only handle legal types. For example, on x86-32 the instruction
164 // selector contains all of the 64-bit instructions from x86-64,
165 // under the assumption that i64 won't be used if the target doesn't
167 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
170 #include "X86GenCallingConv.inc"
172 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
173 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
174 /// Return true and the result register by reference if it is possible.
175 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
176 unsigned &ResultReg) {
177 // Get opcode and regclass of the output for the given load instruction.
179 const TargetRegisterClass *RC = NULL;
180 switch (VT.getSimpleVT().SimpleTy) {
181 default: return false;
185 RC = X86::GR8RegisterClass;
189 RC = X86::GR16RegisterClass;
193 RC = X86::GR32RegisterClass;
196 // Must be in x86-64 mode.
198 RC = X86::GR64RegisterClass;
201 if (X86ScalarSSEf32) {
202 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
203 RC = X86::FR32RegisterClass;
206 RC = X86::RFP32RegisterClass;
210 if (X86ScalarSSEf64) {
211 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
212 RC = X86::FR64RegisterClass;
215 RC = X86::RFP64RegisterClass;
219 // No f80 support yet.
223 ResultReg = createResultReg(RC);
224 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
225 DL, TII.get(Opc), ResultReg), AM);
229 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
230 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
231 /// and a displacement offset, or a GlobalAddress,
232 /// i.e. V. Return true if it is possible.
234 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
235 // Get opcode and regclass of the output for the given store instruction.
237 switch (VT.getSimpleVT().SimpleTy) {
238 case MVT::f80: // No f80 support yet.
239 default: return false;
241 // Mask out all but lowest bit.
242 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
244 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
247 // FALLTHROUGH, handling i1 as i8.
248 case MVT::i8: Opc = X86::MOV8mr; break;
249 case MVT::i16: Opc = X86::MOV16mr; break;
250 case MVT::i32: Opc = X86::MOV32mr; break;
251 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
253 Opc = X86ScalarSSEf32 ?
254 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
257 Opc = X86ScalarSSEf64 ?
258 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
262 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
263 DL, TII.get(Opc)), AM).addReg(Val);
267 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
268 const X86AddressMode &AM) {
269 // Handle 'null' like i32/i64 0.
270 if (isa<ConstantPointerNull>(Val))
271 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
273 // If this is a store of a simple constant, fold the constant into the store.
274 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
277 switch (VT.getSimpleVT().SimpleTy) {
279 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
280 case MVT::i8: Opc = X86::MOV8mi; break;
281 case MVT::i16: Opc = X86::MOV16mi; break;
282 case MVT::i32: Opc = X86::MOV32mi; break;
284 // Must be a 32-bit sign extended value.
285 if ((int)CI->getSExtValue() == CI->getSExtValue())
286 Opc = X86::MOV64mi32;
291 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
292 DL, TII.get(Opc)), AM)
293 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
299 unsigned ValReg = getRegForValue(Val);
303 return X86FastEmitStore(VT, ValReg, AM);
306 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
307 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
308 /// ISD::SIGN_EXTEND).
309 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
310 unsigned Src, EVT SrcVT,
311 unsigned &ResultReg) {
312 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
313 Src, /*TODO: Kill=*/false);
322 /// X86SelectAddress - Attempt to fill in an address from the given value.
324 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
325 const User *U = NULL;
326 unsigned Opcode = Instruction::UserOp1;
327 if (const Instruction *I = dyn_cast<Instruction>(V)) {
328 // Don't walk into other basic blocks; it's possible we haven't
329 // visited them yet, so the instructions may not yet be assigned
330 // virtual registers.
331 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
332 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
333 Opcode = I->getOpcode();
336 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
337 Opcode = C->getOpcode();
341 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
342 if (Ty->getAddressSpace() > 255)
343 // Fast instruction selection doesn't support the special
349 case Instruction::BitCast:
350 // Look past bitcasts.
351 return X86SelectAddress(U->getOperand(0), AM);
353 case Instruction::IntToPtr:
354 // Look past no-op inttoptrs.
355 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
356 return X86SelectAddress(U->getOperand(0), AM);
359 case Instruction::PtrToInt:
360 // Look past no-op ptrtoints.
361 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
362 return X86SelectAddress(U->getOperand(0), AM);
365 case Instruction::Alloca: {
366 // Do static allocas.
367 const AllocaInst *A = cast<AllocaInst>(V);
368 DenseMap<const AllocaInst*, int>::iterator SI =
369 FuncInfo.StaticAllocaMap.find(A);
370 if (SI != FuncInfo.StaticAllocaMap.end()) {
371 AM.BaseType = X86AddressMode::FrameIndexBase;
372 AM.Base.FrameIndex = SI->second;
378 case Instruction::Add: {
379 // Adds of constants are common and easy enough.
380 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
381 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
382 // They have to fit in the 32-bit signed displacement field though.
383 if (isInt<32>(Disp)) {
384 AM.Disp = (uint32_t)Disp;
385 return X86SelectAddress(U->getOperand(0), AM);
391 case Instruction::GetElementPtr: {
392 X86AddressMode SavedAM = AM;
394 // Pattern-match simple GEPs.
395 uint64_t Disp = (int32_t)AM.Disp;
396 unsigned IndexReg = AM.IndexReg;
397 unsigned Scale = AM.Scale;
398 gep_type_iterator GTI = gep_type_begin(U);
399 // Iterate through the indices, folding what we can. Constants can be
400 // folded, and one dynamic index can be handled, if the scale is supported.
401 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
402 i != e; ++i, ++GTI) {
403 const Value *Op = *i;
404 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
405 const StructLayout *SL = TD.getStructLayout(STy);
406 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
410 // A array/variable index is always of the form i*S where S is the
411 // constant scale size. See if we can push the scale into immediates.
412 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
414 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
415 // Constant-offset addressing.
416 Disp += CI->getSExtValue() * S;
419 if (isa<AddOperator>(Op) &&
420 (!isa<Instruction>(Op) ||
421 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
423 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
424 // An add (in the same block) with a constant operand. Fold the
427 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
428 Disp += CI->getSExtValue() * S;
429 // Iterate on the other operand.
430 Op = cast<AddOperator>(Op)->getOperand(0);
434 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
435 (S == 1 || S == 2 || S == 4 || S == 8)) {
436 // Scaled-index addressing.
438 IndexReg = getRegForGEPIndex(Op).first;
444 goto unsupported_gep;
447 // Check for displacement overflow.
448 if (!isInt<32>(Disp))
450 // Ok, the GEP indices were covered by constant-offset and scaled-index
451 // addressing. Update the address state and move on to examining the base.
452 AM.IndexReg = IndexReg;
454 AM.Disp = (uint32_t)Disp;
455 if (X86SelectAddress(U->getOperand(0), AM))
458 // If we couldn't merge the gep value into this addr mode, revert back to
459 // our address and just match the value instead of completely failing.
463 // Ok, the GEP indices weren't all covered.
468 // Handle constant address.
469 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
470 // Can't handle alternate code models or TLS yet.
471 if (TM.getCodeModel() != CodeModel::Small)
474 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
475 if (GVar->isThreadLocal())
478 // RIP-relative addresses can't have additional register operands, so if
479 // we've already folded stuff into the addressing mode, just force the
480 // global value into its own register, which we can use as the basereg.
481 if (!Subtarget->isPICStyleRIPRel() ||
482 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
483 // Okay, we've committed to selecting this global. Set up the address.
486 // Allow the subtarget to classify the global.
487 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
489 // If this reference is relative to the pic base, set it now.
490 if (isGlobalRelativeToPICBase(GVFlags)) {
491 // FIXME: How do we know Base.Reg is free??
492 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
495 // Unless the ABI requires an extra load, return a direct reference to
497 if (!isGlobalStubReference(GVFlags)) {
498 if (Subtarget->isPICStyleRIPRel()) {
499 // Use rip-relative addressing if we can. Above we verified that the
500 // base and index registers are unused.
501 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
502 AM.Base.Reg = X86::RIP;
504 AM.GVOpFlags = GVFlags;
508 // Ok, we need to do a load from a stub. If we've already loaded from
509 // this stub, reuse the loaded pointer, otherwise emit the load now.
510 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
512 if (I != LocalValueMap.end() && I->second != 0) {
515 // Issue load from stub.
517 const TargetRegisterClass *RC = NULL;
518 X86AddressMode StubAM;
519 StubAM.Base.Reg = AM.Base.Reg;
521 StubAM.GVOpFlags = GVFlags;
523 // Prepare for inserting code in the local-value area.
524 SavePoint SaveInsertPt = enterLocalValueArea();
526 if (TLI.getPointerTy() == MVT::i64) {
528 RC = X86::GR64RegisterClass;
530 if (Subtarget->isPICStyleRIPRel())
531 StubAM.Base.Reg = X86::RIP;
534 RC = X86::GR32RegisterClass;
537 LoadReg = createResultReg(RC);
538 MachineInstrBuilder LoadMI =
539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
540 addFullAddress(LoadMI, StubAM);
542 // Ok, back to normal mode.
543 leaveLocalValueArea(SaveInsertPt);
545 // Prevent loading GV stub multiple times in same MBB.
546 LocalValueMap[V] = LoadReg;
549 // Now construct the final address. Note that the Disp, Scale,
550 // and Index values may already be set here.
551 AM.Base.Reg = LoadReg;
557 // If all else fails, try to materialize the value in a register.
558 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
559 if (AM.Base.Reg == 0) {
560 AM.Base.Reg = getRegForValue(V);
561 return AM.Base.Reg != 0;
563 if (AM.IndexReg == 0) {
564 assert(AM.Scale == 1 && "Scale with no index!");
565 AM.IndexReg = getRegForValue(V);
566 return AM.IndexReg != 0;
573 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
575 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
576 const User *U = NULL;
577 unsigned Opcode = Instruction::UserOp1;
578 if (const Instruction *I = dyn_cast<Instruction>(V)) {
579 Opcode = I->getOpcode();
581 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
582 Opcode = C->getOpcode();
588 case Instruction::BitCast:
589 // Look past bitcasts.
590 return X86SelectCallAddress(U->getOperand(0), AM);
592 case Instruction::IntToPtr:
593 // Look past no-op inttoptrs.
594 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
595 return X86SelectCallAddress(U->getOperand(0), AM);
598 case Instruction::PtrToInt:
599 // Look past no-op ptrtoints.
600 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
601 return X86SelectCallAddress(U->getOperand(0), AM);
605 // Handle constant address.
606 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
607 // Can't handle alternate code models yet.
608 if (TM.getCodeModel() != CodeModel::Small)
611 // RIP-relative addresses can't have additional register operands.
612 if (Subtarget->isPICStyleRIPRel() &&
613 (AM.Base.Reg != 0 || AM.IndexReg != 0))
616 // Can't handle DLLImport.
617 if (GV->hasDLLImportLinkage())
621 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
622 if (GVar->isThreadLocal())
625 // Okay, we've committed to selecting this global. Set up the basic address.
628 // No ABI requires an extra load for anything other than DLLImport, which
629 // we rejected above. Return a direct reference to the global.
630 if (Subtarget->isPICStyleRIPRel()) {
631 // Use rip-relative addressing if we can. Above we verified that the
632 // base and index registers are unused.
633 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
634 AM.Base.Reg = X86::RIP;
635 } else if (Subtarget->isPICStyleStubPIC()) {
636 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
637 } else if (Subtarget->isPICStyleGOT()) {
638 AM.GVOpFlags = X86II::MO_GOTOFF;
644 // If all else fails, try to materialize the value in a register.
645 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
646 if (AM.Base.Reg == 0) {
647 AM.Base.Reg = getRegForValue(V);
648 return AM.Base.Reg != 0;
650 if (AM.IndexReg == 0) {
651 assert(AM.Scale == 1 && "Scale with no index!");
652 AM.IndexReg = getRegForValue(V);
653 return AM.IndexReg != 0;
661 /// X86SelectStore - Select and emit code to implement store instructions.
662 bool X86FastISel::X86SelectStore(const Instruction *I) {
663 // Atomic stores need special handling.
664 if (cast<StoreInst>(I)->isAtomic())
668 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
672 if (!X86SelectAddress(I->getOperand(1), AM))
675 return X86FastEmitStore(VT, I->getOperand(0), AM);
678 /// X86SelectRet - Select and emit code to implement ret instructions.
679 bool X86FastISel::X86SelectRet(const Instruction *I) {
680 const ReturnInst *Ret = cast<ReturnInst>(I);
681 const Function &F = *I->getParent()->getParent();
683 if (!FuncInfo.CanLowerReturn)
686 CallingConv::ID CC = F.getCallingConv();
687 if (CC != CallingConv::C &&
688 CC != CallingConv::Fast &&
689 CC != CallingConv::X86_FastCall)
692 if (Subtarget->isTargetWin64())
695 // Don't handle popping bytes on return for now.
696 if (FuncInfo.MF->getInfo<X86MachineFunctionInfo>()
697 ->getBytesToPopOnReturn() != 0)
700 // fastcc with -tailcallopt is intended to provide a guaranteed
701 // tail call optimization. Fastisel doesn't know how to do that.
702 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
705 // Let SDISel handle vararg functions.
709 if (Ret->getNumOperands() > 0) {
710 SmallVector<ISD::OutputArg, 4> Outs;
711 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
714 // Analyze operands of the call, assigning locations to each operand.
715 SmallVector<CCValAssign, 16> ValLocs;
716 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
718 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
720 const Value *RV = Ret->getOperand(0);
721 unsigned Reg = getRegForValue(RV);
725 // Only handle a single return value for now.
726 if (ValLocs.size() != 1)
729 CCValAssign &VA = ValLocs[0];
731 // Don't bother handling odd stuff for now.
732 if (VA.getLocInfo() != CCValAssign::Full)
734 // Only handle register returns for now.
738 // The calling-convention tables for x87 returns don't tell
740 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
743 unsigned SrcReg = Reg + VA.getValNo();
744 EVT SrcVT = TLI.getValueType(RV->getType());
745 EVT DstVT = VA.getValVT();
746 // Special handling for extended integers.
747 if (SrcVT != DstVT) {
748 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
751 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
754 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
756 if (SrcVT == MVT::i1) {
757 if (Outs[0].Flags.isSExt())
759 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
762 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
764 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
765 SrcReg, /*TODO: Kill=*/false);
769 unsigned DstReg = VA.getLocReg();
770 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
771 // Avoid a cross-class copy. This is very unlikely.
772 if (!SrcRC->contains(DstReg))
774 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
775 DstReg).addReg(SrcReg);
777 // Mark the register as live out of the function.
778 MRI.addLiveOut(VA.getLocReg());
782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
786 /// X86SelectLoad - Select and emit code to implement load instructions.
788 bool X86FastISel::X86SelectLoad(const Instruction *I) {
789 // Atomic loads need special handling.
790 if (cast<LoadInst>(I)->isAtomic())
794 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
798 if (!X86SelectAddress(I->getOperand(0), AM))
801 unsigned ResultReg = 0;
802 if (X86FastEmitLoad(VT, AM, ResultReg)) {
803 UpdateValueMap(I, ResultReg);
809 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
810 bool HasAVX = Subtarget->hasAVX();
811 bool X86ScalarSSEf32 = HasAVX || Subtarget->hasSSE1();
812 bool X86ScalarSSEf64 = HasAVX || Subtarget->hasSSE2();
814 switch (VT.getSimpleVT().SimpleTy) {
816 case MVT::i8: return X86::CMP8rr;
817 case MVT::i16: return X86::CMP16rr;
818 case MVT::i32: return X86::CMP32rr;
819 case MVT::i64: return X86::CMP64rr;
821 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
823 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
827 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
828 /// of the comparison, return an opcode that works for the compare (e.g.
829 /// CMP32ri) otherwise return 0.
830 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
831 switch (VT.getSimpleVT().SimpleTy) {
832 // Otherwise, we can't fold the immediate into this comparison.
834 case MVT::i8: return X86::CMP8ri;
835 case MVT::i16: return X86::CMP16ri;
836 case MVT::i32: return X86::CMP32ri;
838 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
840 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
841 return X86::CMP64ri32;
846 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
848 unsigned Op0Reg = getRegForValue(Op0);
849 if (Op0Reg == 0) return false;
851 // Handle 'null' like i32/i64 0.
852 if (isa<ConstantPointerNull>(Op1))
853 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
855 // We have two options: compare with register or immediate. If the RHS of
856 // the compare is an immediate that we can fold into this compare, use
857 // CMPri, otherwise use CMPrr.
858 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
859 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
860 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
862 .addImm(Op1C->getSExtValue());
867 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
868 if (CompareOpc == 0) return false;
870 unsigned Op1Reg = getRegForValue(Op1);
871 if (Op1Reg == 0) return false;
872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
879 bool X86FastISel::X86SelectCmp(const Instruction *I) {
880 const CmpInst *CI = cast<CmpInst>(I);
883 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
886 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
888 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
889 switch (CI->getPredicate()) {
890 case CmpInst::FCMP_OEQ: {
891 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
894 unsigned EReg = createResultReg(&X86::GR8RegClass);
895 unsigned NPReg = createResultReg(&X86::GR8RegClass);
896 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
897 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
898 TII.get(X86::SETNPr), NPReg);
899 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
900 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
901 UpdateValueMap(I, ResultReg);
904 case CmpInst::FCMP_UNE: {
905 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
908 unsigned NEReg = createResultReg(&X86::GR8RegClass);
909 unsigned PReg = createResultReg(&X86::GR8RegClass);
910 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
911 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
912 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
913 .addReg(PReg).addReg(NEReg);
914 UpdateValueMap(I, ResultReg);
917 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
918 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
919 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
920 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
921 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
922 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
923 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
924 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
925 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
926 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
927 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
928 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
930 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
931 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
932 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
933 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
934 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
935 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
936 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
937 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
938 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
939 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
944 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
948 // Emit a compare of Op0/Op1.
949 if (!X86FastEmitCompare(Op0, Op1, VT))
952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
953 UpdateValueMap(I, ResultReg);
957 bool X86FastISel::X86SelectZExt(const Instruction *I) {
958 // Handle zero-extension from i1 to i8, which is common.
959 if (!I->getOperand(0)->getType()->isIntegerTy(1))
962 EVT DstVT = TLI.getValueType(I->getType());
963 if (!TLI.isTypeLegal(DstVT))
966 unsigned ResultReg = getRegForValue(I->getOperand(0));
970 // Set the high bits to zero.
971 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
975 if (DstVT != MVT::i8) {
976 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
977 ResultReg, /*Kill=*/true);
982 UpdateValueMap(I, ResultReg);
987 bool X86FastISel::X86SelectBranch(const Instruction *I) {
988 // Unconditional branches are selected by tablegen-generated code.
989 // Handle a conditional branch.
990 const BranchInst *BI = cast<BranchInst>(I);
991 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
992 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
994 // Fold the common case of a conditional branch with a comparison
995 // in the same block (values defined on other blocks may not have
996 // initialized registers).
997 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
998 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
999 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1001 // Try to take advantage of fallthrough opportunities.
1002 CmpInst::Predicate Predicate = CI->getPredicate();
1003 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1004 std::swap(TrueMBB, FalseMBB);
1005 Predicate = CmpInst::getInversePredicate(Predicate);
1008 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1009 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1011 switch (Predicate) {
1012 case CmpInst::FCMP_OEQ:
1013 std::swap(TrueMBB, FalseMBB);
1014 Predicate = CmpInst::FCMP_UNE;
1016 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1017 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1018 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1019 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1020 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1021 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1022 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1023 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1024 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1025 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1026 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1027 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1028 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1030 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1031 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1032 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1033 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1034 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1035 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1036 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1037 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1038 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1039 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1044 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1046 std::swap(Op0, Op1);
1048 // Emit a compare of the LHS and RHS, setting the flags.
1049 if (!X86FastEmitCompare(Op0, Op1, VT))
1052 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1055 if (Predicate == CmpInst::FCMP_UNE) {
1056 // X86 requires a second branch to handle UNE (and OEQ,
1057 // which is mapped to UNE above).
1058 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1062 FastEmitBranch(FalseMBB, DL);
1063 FuncInfo.MBB->addSuccessor(TrueMBB);
1066 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1067 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1068 // typically happen for _Bool and C++ bools.
1070 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1071 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1072 unsigned TestOpc = 0;
1073 switch (SourceVT.SimpleTy) {
1075 case MVT::i8: TestOpc = X86::TEST8ri; break;
1076 case MVT::i16: TestOpc = X86::TEST16ri; break;
1077 case MVT::i32: TestOpc = X86::TEST32ri; break;
1078 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1081 unsigned OpReg = getRegForValue(TI->getOperand(0));
1082 if (OpReg == 0) return false;
1083 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1084 .addReg(OpReg).addImm(1);
1086 unsigned JmpOpc = X86::JNE_4;
1087 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1088 std::swap(TrueMBB, FalseMBB);
1092 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1094 FastEmitBranch(FalseMBB, DL);
1095 FuncInfo.MBB->addSuccessor(TrueMBB);
1101 // Otherwise do a clumsy setcc and re-test it.
1102 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1103 // in an explicit cast, so make sure to handle that correctly.
1104 unsigned OpReg = getRegForValue(BI->getCondition());
1105 if (OpReg == 0) return false;
1107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1108 .addReg(OpReg).addImm(1);
1109 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1111 FastEmitBranch(FalseMBB, DL);
1112 FuncInfo.MBB->addSuccessor(TrueMBB);
1116 bool X86FastISel::X86SelectShift(const Instruction *I) {
1117 unsigned CReg = 0, OpReg = 0;
1118 const TargetRegisterClass *RC = NULL;
1119 if (I->getType()->isIntegerTy(8)) {
1121 RC = &X86::GR8RegClass;
1122 switch (I->getOpcode()) {
1123 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1124 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1125 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1126 default: return false;
1128 } else if (I->getType()->isIntegerTy(16)) {
1130 RC = &X86::GR16RegClass;
1131 switch (I->getOpcode()) {
1132 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1133 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1134 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1135 default: return false;
1137 } else if (I->getType()->isIntegerTy(32)) {
1139 RC = &X86::GR32RegClass;
1140 switch (I->getOpcode()) {
1141 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1142 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1143 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1144 default: return false;
1146 } else if (I->getType()->isIntegerTy(64)) {
1148 RC = &X86::GR64RegClass;
1149 switch (I->getOpcode()) {
1150 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1151 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1152 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1153 default: return false;
1160 if (!isTypeLegal(I->getType(), VT))
1163 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1164 if (Op0Reg == 0) return false;
1166 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1167 if (Op1Reg == 0) return false;
1168 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1169 CReg).addReg(Op1Reg);
1171 // The shift instruction uses X86::CL. If we defined a super-register
1172 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1173 if (CReg != X86::CL)
1174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1175 TII.get(TargetOpcode::KILL), X86::CL)
1176 .addReg(CReg, RegState::Kill);
1178 unsigned ResultReg = createResultReg(RC);
1179 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1181 UpdateValueMap(I, ResultReg);
1185 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1187 if (!isTypeLegal(I->getType(), VT))
1190 // We only use cmov here, if we don't have a cmov instruction bail.
1191 if (!Subtarget->hasCMov()) return false;
1194 const TargetRegisterClass *RC = NULL;
1195 if (VT == MVT::i16) {
1196 Opc = X86::CMOVE16rr;
1197 RC = &X86::GR16RegClass;
1198 } else if (VT == MVT::i32) {
1199 Opc = X86::CMOVE32rr;
1200 RC = &X86::GR32RegClass;
1201 } else if (VT == MVT::i64) {
1202 Opc = X86::CMOVE64rr;
1203 RC = &X86::GR64RegClass;
1208 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1209 if (Op0Reg == 0) return false;
1210 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1211 if (Op1Reg == 0) return false;
1212 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1213 if (Op2Reg == 0) return false;
1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1216 .addReg(Op0Reg).addReg(Op0Reg);
1217 unsigned ResultReg = createResultReg(RC);
1218 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1219 .addReg(Op1Reg).addReg(Op2Reg);
1220 UpdateValueMap(I, ResultReg);
1224 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1225 // fpext from float to double.
1226 if (X86ScalarSSEf64 &&
1227 I->getType()->isDoubleTy()) {
1228 const Value *V = I->getOperand(0);
1229 if (V->getType()->isFloatTy()) {
1230 unsigned OpReg = getRegForValue(V);
1231 if (OpReg == 0) return false;
1232 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1234 TII.get(X86::CVTSS2SDrr), ResultReg)
1236 UpdateValueMap(I, ResultReg);
1244 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1245 if (X86ScalarSSEf64) {
1246 if (I->getType()->isFloatTy()) {
1247 const Value *V = I->getOperand(0);
1248 if (V->getType()->isDoubleTy()) {
1249 unsigned OpReg = getRegForValue(V);
1250 if (OpReg == 0) return false;
1251 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1252 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1253 TII.get(X86::CVTSD2SSrr), ResultReg)
1255 UpdateValueMap(I, ResultReg);
1264 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1265 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1266 EVT DstVT = TLI.getValueType(I->getType());
1268 // This code only handles truncation to byte.
1269 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1271 if (!TLI.isTypeLegal(SrcVT))
1274 unsigned InputReg = getRegForValue(I->getOperand(0));
1276 // Unhandled operand. Halt "fast" selection and bail.
1279 if (SrcVT == MVT::i8) {
1280 // Truncate from i8 to i1; no code needed.
1281 UpdateValueMap(I, InputReg);
1285 if (!Subtarget->is64Bit()) {
1286 // If we're on x86-32; we can't extract an i8 from a general register.
1287 // First issue a copy to GR16_ABCD or GR32_ABCD.
1288 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1289 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1290 unsigned CopyReg = createResultReg(CopyRC);
1291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1292 CopyReg).addReg(InputReg);
1296 // Issue an extract_subreg.
1297 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1298 InputReg, /*Kill=*/true,
1303 UpdateValueMap(I, ResultReg);
1307 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1308 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1311 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1312 X86AddressMode SrcAM, uint64_t Len) {
1314 // Make sure we don't bloat code by inlining very large memcpy's.
1315 if (!IsMemcpySmall(Len))
1318 bool i64Legal = Subtarget->is64Bit();
1320 // We don't care about alignment here since we just emit integer accesses.
1323 if (Len >= 8 && i64Legal)
1335 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1336 RV &= X86FastEmitStore(VT, Reg, DestAM);
1337 assert(RV && "Failed to emit load or store??");
1339 unsigned Size = VT.getSizeInBits()/8;
1341 DestAM.Disp += Size;
1348 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1349 // FIXME: Handle more intrinsics.
1350 switch (I.getIntrinsicID()) {
1351 default: return false;
1352 case Intrinsic::memcpy: {
1353 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1354 // Don't handle volatile or variable length memcpys.
1355 if (MCI.isVolatile())
1358 if (isa<ConstantInt>(MCI.getLength())) {
1359 // Small memcpy's are common enough that we want to do them
1360 // without a call if possible.
1361 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1362 if (IsMemcpySmall(Len)) {
1363 X86AddressMode DestAM, SrcAM;
1364 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1365 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1367 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1372 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1373 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1376 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1379 return DoSelectCall(&I, "memcpy");
1381 case Intrinsic::memset: {
1382 const MemSetInst &MSI = cast<MemSetInst>(I);
1384 if (MSI.isVolatile())
1387 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1388 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1391 if (MSI.getDestAddressSpace() > 255)
1394 return DoSelectCall(&I, "memset");
1396 case Intrinsic::stackprotector: {
1397 // Emit code inline code to store the stack guard onto the stack.
1398 EVT PtrTy = TLI.getPointerTy();
1400 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1401 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1403 // Grab the frame index.
1405 if (!X86SelectAddress(Slot, AM)) return false;
1406 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1409 case Intrinsic::dbg_declare: {
1410 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1412 assert(DI->getAddress() && "Null address should be checked earlier!");
1413 if (!X86SelectAddress(DI->getAddress(), AM))
1415 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1416 // FIXME may need to add RegState::Debug to any registers produced,
1417 // although ESP/EBP should be the only ones at the moment.
1418 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1419 addImm(0).addMetadata(DI->getVariable());
1422 case Intrinsic::trap: {
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1426 case Intrinsic::sadd_with_overflow:
1427 case Intrinsic::uadd_with_overflow: {
1428 // FIXME: Should fold immediates.
1430 // Replace "add with overflow" intrinsics with an "add" instruction followed
1431 // by a seto/setc instruction.
1432 const Function *Callee = I.getCalledFunction();
1434 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1437 if (!isTypeLegal(RetTy, VT))
1440 const Value *Op1 = I.getArgOperand(0);
1441 const Value *Op2 = I.getArgOperand(1);
1442 unsigned Reg1 = getRegForValue(Op1);
1443 unsigned Reg2 = getRegForValue(Op2);
1445 if (Reg1 == 0 || Reg2 == 0)
1446 // FIXME: Handle values *not* in registers.
1452 else if (VT == MVT::i64)
1457 // The call to CreateRegs builds two sequential registers, to store the
1458 // both the the returned values.
1459 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1460 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1461 .addReg(Reg1).addReg(Reg2);
1463 unsigned Opc = X86::SETBr;
1464 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1466 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1468 UpdateValueMap(&I, ResultReg, 2);
1474 bool X86FastISel::X86SelectCall(const Instruction *I) {
1475 const CallInst *CI = cast<CallInst>(I);
1476 const Value *Callee = CI->getCalledValue();
1478 // Can't handle inline asm yet.
1479 if (isa<InlineAsm>(Callee))
1482 // Handle intrinsic calls.
1483 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1484 return X86VisitIntrinsicCall(*II);
1486 return DoSelectCall(I, 0);
1489 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1490 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1491 const CallInst *CI = cast<CallInst>(I);
1492 const Value *Callee = CI->getCalledValue();
1494 // Handle only C and fastcc calling conventions for now.
1495 ImmutableCallSite CS(CI);
1496 CallingConv::ID CC = CS.getCallingConv();
1497 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1498 CC != CallingConv::X86_FastCall)
1501 // fastcc with -tailcallopt is intended to provide a guaranteed
1502 // tail call optimization. Fastisel doesn't know how to do that.
1503 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1506 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1507 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1508 bool isVarArg = FTy->isVarArg();
1510 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1511 // x86-32. Special handling for x86-64 is implemented.
1512 if (isVarArg && Subtarget->isTargetWin64())
1515 // Fast-isel doesn't know about callee-pop yet.
1516 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1517 GuaranteedTailCallOpt))
1520 // Check whether the function can return without sret-demotion.
1521 SmallVector<ISD::OutputArg, 4> Outs;
1522 SmallVector<uint64_t, 4> Offsets;
1523 GetReturnInfo(I->getType(), CS.getAttributes().getRetAttributes(),
1524 Outs, TLI, &Offsets);
1525 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1526 *FuncInfo.MF, FTy->isVarArg(),
1527 Outs, FTy->getContext());
1528 if (!CanLowerReturn)
1531 // Materialize callee address in a register. FIXME: GV address can be
1532 // handled with a CALLpcrel32 instead.
1533 X86AddressMode CalleeAM;
1534 if (!X86SelectCallAddress(Callee, CalleeAM))
1536 unsigned CalleeOp = 0;
1537 const GlobalValue *GV = 0;
1538 if (CalleeAM.GV != 0) {
1540 } else if (CalleeAM.Base.Reg != 0) {
1541 CalleeOp = CalleeAM.Base.Reg;
1545 // Deal with call operands first.
1546 SmallVector<const Value *, 8> ArgVals;
1547 SmallVector<unsigned, 8> Args;
1548 SmallVector<MVT, 8> ArgVTs;
1549 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1550 Args.reserve(CS.arg_size());
1551 ArgVals.reserve(CS.arg_size());
1552 ArgVTs.reserve(CS.arg_size());
1553 ArgFlags.reserve(CS.arg_size());
1554 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1556 // If we're lowering a mem intrinsic instead of a regular call, skip the
1557 // last two arguments, which should not passed to the underlying functions.
1558 if (MemIntName && e-i <= 2)
1561 ISD::ArgFlagsTy Flags;
1562 unsigned AttrInd = i - CS.arg_begin() + 1;
1563 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1565 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1568 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1569 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1570 Type *ElementTy = Ty->getElementType();
1571 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1572 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1574 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1576 Flags.setByValSize(FrameSize);
1577 Flags.setByValAlign(FrameAlign);
1578 if (!IsMemcpySmall(FrameSize))
1582 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1584 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1587 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1588 // instruction. This is safe because it is common to all fastisel supported
1589 // calling conventions on x86.
1590 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1591 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1592 CI->getBitWidth() == 16) {
1594 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1596 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1602 // Passing bools around ends up doing a trunc to i1 and passing it.
1603 // Codegen this as an argument + "and 1".
1604 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1605 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1606 ArgVal->hasOneUse()) {
1607 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1608 ArgReg = getRegForValue(ArgVal);
1609 if (ArgReg == 0) return false;
1612 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1614 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1615 ArgVal->hasOneUse(), 1);
1617 ArgReg = getRegForValue(ArgVal);
1620 if (ArgReg == 0) return false;
1622 Type *ArgTy = ArgVal->getType();
1624 if (!isTypeLegal(ArgTy, ArgVT))
1626 if (ArgVT == MVT::x86mmx)
1628 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1629 Flags.setOrigAlign(OriginalAlignment);
1631 Args.push_back(ArgReg);
1632 ArgVals.push_back(ArgVal);
1633 ArgVTs.push_back(ArgVT);
1634 ArgFlags.push_back(Flags);
1637 // Analyze operands of the call, assigning locations to each operand.
1638 SmallVector<CCValAssign, 16> ArgLocs;
1639 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1640 I->getParent()->getContext());
1642 // Allocate shadow area for Win64
1643 if (Subtarget->isTargetWin64())
1644 CCInfo.AllocateStack(32, 8);
1646 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1648 // Get a count of how many bytes are to be pushed on the stack.
1649 unsigned NumBytes = CCInfo.getNextStackOffset();
1651 // Issue CALLSEQ_START
1652 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1653 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1656 // Process argument: walk the register/memloc assignments, inserting
1658 SmallVector<unsigned, 4> RegArgs;
1659 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1660 CCValAssign &VA = ArgLocs[i];
1661 unsigned Arg = Args[VA.getValNo()];
1662 EVT ArgVT = ArgVTs[VA.getValNo()];
1664 // Promote the value if needed.
1665 switch (VA.getLocInfo()) {
1666 default: llvm_unreachable("Unknown loc info!");
1667 case CCValAssign::Full: break;
1668 case CCValAssign::SExt: {
1669 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1670 "Unexpected extend");
1671 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1673 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1674 ArgVT = VA.getLocVT();
1677 case CCValAssign::ZExt: {
1678 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1679 "Unexpected extend");
1680 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1682 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1683 ArgVT = VA.getLocVT();
1686 case CCValAssign::AExt: {
1687 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1688 "Unexpected extend");
1689 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1692 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1695 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1698 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1699 ArgVT = VA.getLocVT();
1702 case CCValAssign::BCvt: {
1703 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1704 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1705 assert(BC != 0 && "Failed to emit a bitcast!");
1707 ArgVT = VA.getLocVT();
1712 if (VA.isRegLoc()) {
1713 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1714 VA.getLocReg()).addReg(Arg);
1715 RegArgs.push_back(VA.getLocReg());
1717 unsigned LocMemOffset = VA.getLocMemOffset();
1719 AM.Base.Reg = StackPtr;
1720 AM.Disp = LocMemOffset;
1721 const Value *ArgVal = ArgVals[VA.getValNo()];
1722 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1724 if (Flags.isByVal()) {
1725 X86AddressMode SrcAM;
1726 SrcAM.Base.Reg = Arg;
1727 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
1728 assert(Res && "memcpy length already checked!"); (void)Res;
1729 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
1730 // If this is a really simple value, emit this with the Value* version
1731 //of X86FastEmitStore. If it isn't simple, we don't want to do this,
1732 // as it can cause us to reevaluate the argument.
1733 X86FastEmitStore(ArgVT, ArgVal, AM);
1735 X86FastEmitStore(ArgVT, Arg, AM);
1740 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1742 if (Subtarget->isPICStyleGOT()) {
1743 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1744 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1745 X86::EBX).addReg(Base);
1748 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1749 // Count the number of XMM registers allocated.
1750 static const unsigned XMMArgRegs[] = {
1751 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1752 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1754 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1755 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1756 X86::AL).addImm(NumXMMRegs);
1760 MachineInstrBuilder MIB;
1762 // Register-indirect call.
1764 if (Subtarget->isTargetWin64())
1765 CallOpc = X86::WINCALL64r;
1766 else if (Subtarget->is64Bit())
1767 CallOpc = X86::CALL64r;
1769 CallOpc = X86::CALL32r;
1770 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1775 assert(GV && "Not a direct call");
1777 if (Subtarget->isTargetWin64())
1778 CallOpc = X86::WINCALL64pcrel32;
1779 else if (Subtarget->is64Bit())
1780 CallOpc = X86::CALL64pcrel32;
1782 CallOpc = X86::CALLpcrel32;
1784 // See if we need any target-specific flags on the GV operand.
1785 unsigned char OpFlags = 0;
1787 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1788 // external symbols most go through the PLT in PIC mode. If the symbol
1789 // has hidden or protected visibility, or if it is static or local, then
1790 // we don't need to use the PLT - we can directly call it.
1791 if (Subtarget->isTargetELF() &&
1792 TM.getRelocationModel() == Reloc::PIC_ &&
1793 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1794 OpFlags = X86II::MO_PLT;
1795 } else if (Subtarget->isPICStyleStubAny() &&
1796 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1797 (!Subtarget->getTargetTriple().isMacOSX() ||
1798 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1799 // PC-relative references to external symbols should go through $stub,
1800 // unless we're building with the leopard linker or later, which
1801 // automatically synthesizes these stubs.
1802 OpFlags = X86II::MO_DARWIN_STUB;
1806 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
1808 MIB.addExternalSymbol(MemIntName, OpFlags);
1810 MIB.addGlobalAddress(GV, 0, OpFlags);
1813 // Add an implicit use GOT pointer in EBX.
1814 if (Subtarget->isPICStyleGOT())
1815 MIB.addReg(X86::EBX);
1817 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1818 MIB.addReg(X86::AL);
1820 // Add implicit physical register uses to the call.
1821 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1822 MIB.addReg(RegArgs[i]);
1824 // Issue CALLSEQ_END
1825 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1826 unsigned NumBytesCallee = 0;
1827 if (!Subtarget->is64Bit() && CS.paramHasAttr(1, Attribute::StructRet))
1829 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1830 .addImm(NumBytes).addImm(NumBytesCallee);
1832 // Build info for return calling conv lowering code.
1833 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
1834 SmallVector<ISD::InputArg, 32> Ins;
1835 SmallVector<EVT, 4> RetTys;
1836 ComputeValueVTs(TLI, I->getType(), RetTys);
1837 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
1839 EVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
1840 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
1841 for (unsigned j = 0; j != NumRegs; ++j) {
1842 ISD::InputArg MyFlags;
1843 MyFlags.VT = RegisterVT.getSimpleVT();
1844 MyFlags.Used = !CS.getInstruction()->use_empty();
1845 if (CS.paramHasAttr(0, Attribute::SExt))
1846 MyFlags.Flags.setSExt();
1847 if (CS.paramHasAttr(0, Attribute::ZExt))
1848 MyFlags.Flags.setZExt();
1849 if (CS.paramHasAttr(0, Attribute::InReg))
1850 MyFlags.Flags.setInReg();
1851 Ins.push_back(MyFlags);
1855 // Now handle call return values.
1856 SmallVector<unsigned, 4> UsedRegs;
1857 SmallVector<CCValAssign, 16> RVLocs;
1858 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
1859 I->getParent()->getContext());
1860 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
1861 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
1862 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1863 EVT CopyVT = RVLocs[i].getValVT();
1864 unsigned CopyReg = ResultReg + i;
1866 // If this is a call to a function that returns an fp value on the x87 fp
1867 // stack, but where we prefer to use the value in xmm registers, copy it
1868 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1869 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1870 RVLocs[i].getLocReg() == X86::ST1)) {
1871 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1873 CopyReg = createResultReg(X86::RFP80RegisterClass);
1875 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
1878 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1879 CopyReg).addReg(RVLocs[i].getLocReg());
1880 UsedRegs.push_back(RVLocs[i].getLocReg());
1883 if (CopyVT != RVLocs[i].getValVT()) {
1884 // Round the F80 the right size, which also moves to the appropriate xmm
1885 // register. This is accomplished by storing the F80 value in memory and
1886 // then loading it back. Ewww...
1887 EVT ResVT = RVLocs[i].getValVT();
1888 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1889 unsigned MemSize = ResVT.getSizeInBits()/8;
1890 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1891 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1894 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1895 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1896 TII.get(Opc), ResultReg + i), FI);
1901 UpdateValueMap(I, ResultReg, RVLocs.size());
1903 // Set all unused physreg defs as dead.
1904 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1911 X86FastISel::TargetSelectInstruction(const Instruction *I) {
1912 switch (I->getOpcode()) {
1914 case Instruction::Load:
1915 return X86SelectLoad(I);
1916 case Instruction::Store:
1917 return X86SelectStore(I);
1918 case Instruction::Ret:
1919 return X86SelectRet(I);
1920 case Instruction::ICmp:
1921 case Instruction::FCmp:
1922 return X86SelectCmp(I);
1923 case Instruction::ZExt:
1924 return X86SelectZExt(I);
1925 case Instruction::Br:
1926 return X86SelectBranch(I);
1927 case Instruction::Call:
1928 return X86SelectCall(I);
1929 case Instruction::LShr:
1930 case Instruction::AShr:
1931 case Instruction::Shl:
1932 return X86SelectShift(I);
1933 case Instruction::Select:
1934 return X86SelectSelect(I);
1935 case Instruction::Trunc:
1936 return X86SelectTrunc(I);
1937 case Instruction::FPExt:
1938 return X86SelectFPExt(I);
1939 case Instruction::FPTrunc:
1940 return X86SelectFPTrunc(I);
1941 case Instruction::IntToPtr: // Deliberate fall-through.
1942 case Instruction::PtrToInt: {
1943 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1944 EVT DstVT = TLI.getValueType(I->getType());
1945 if (DstVT.bitsGT(SrcVT))
1946 return X86SelectZExt(I);
1947 if (DstVT.bitsLT(SrcVT))
1948 return X86SelectTrunc(I);
1949 unsigned Reg = getRegForValue(I->getOperand(0));
1950 if (Reg == 0) return false;
1951 UpdateValueMap(I, Reg);
1959 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
1961 if (!isTypeLegal(C->getType(), VT))
1964 // Get opcode and regclass of the output for the given load instruction.
1966 const TargetRegisterClass *RC = NULL;
1967 switch (VT.SimpleTy) {
1968 default: return false;
1971 RC = X86::GR8RegisterClass;
1975 RC = X86::GR16RegisterClass;
1979 RC = X86::GR32RegisterClass;
1982 // Must be in x86-64 mode.
1984 RC = X86::GR64RegisterClass;
1987 if (X86ScalarSSEf32) {
1988 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
1989 RC = X86::FR32RegisterClass;
1991 Opc = X86::LD_Fp32m;
1992 RC = X86::RFP32RegisterClass;
1996 if (X86ScalarSSEf64) {
1997 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
1998 RC = X86::FR64RegisterClass;
2000 Opc = X86::LD_Fp64m;
2001 RC = X86::RFP64RegisterClass;
2005 // No f80 support yet.
2009 // Materialize addresses with LEA instructions.
2010 if (isa<GlobalValue>(C)) {
2012 if (X86SelectAddress(C, AM)) {
2013 // If the expression is just a basereg, then we're done, otherwise we need
2015 if (AM.BaseType == X86AddressMode::RegBase &&
2016 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2019 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2020 unsigned ResultReg = createResultReg(RC);
2021 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2022 TII.get(Opc), ResultReg), AM);
2028 // MachineConstantPool wants an explicit alignment.
2029 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2031 // Alignment of vector types. FIXME!
2032 Align = TD.getTypeAllocSize(C->getType());
2035 // x86-32 PIC requires a PIC base register for constant pools.
2036 unsigned PICBase = 0;
2037 unsigned char OpFlag = 0;
2038 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2039 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2040 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2041 } else if (Subtarget->isPICStyleGOT()) {
2042 OpFlag = X86II::MO_GOTOFF;
2043 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2044 } else if (Subtarget->isPICStyleRIPRel() &&
2045 TM.getCodeModel() == CodeModel::Small) {
2049 // Create the load from the constant pool.
2050 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2051 unsigned ResultReg = createResultReg(RC);
2052 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2053 TII.get(Opc), ResultReg),
2054 MCPOffset, PICBase, OpFlag);
2059 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2060 // Fail on dynamic allocas. At this point, getRegForValue has already
2061 // checked its CSE maps, so if we're here trying to handle a dynamic
2062 // alloca, we're not going to succeed. X86SelectAddress has a
2063 // check for dynamic allocas, because it's called directly from
2064 // various places, but TargetMaterializeAlloca also needs a check
2065 // in order to avoid recursion between getRegForValue,
2066 // X86SelectAddrss, and TargetMaterializeAlloca.
2067 if (!FuncInfo.StaticAllocaMap.count(C))
2071 if (!X86SelectAddress(C, AM))
2073 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2074 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2075 unsigned ResultReg = createResultReg(RC);
2076 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2077 TII.get(Opc), ResultReg), AM);
2081 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2083 if (!isTypeLegal(CF->getType(), VT))
2086 // Get opcode and regclass for the given zero.
2088 const TargetRegisterClass *RC = NULL;
2089 switch (VT.SimpleTy) {
2090 default: return false;
2092 if (X86ScalarSSEf32) {
2093 Opc = Subtarget->hasAVX() ? X86::VFsFLD0SS : X86::FsFLD0SS;
2094 RC = X86::FR32RegisterClass;
2096 Opc = X86::LD_Fp032;
2097 RC = X86::RFP32RegisterClass;
2101 if (X86ScalarSSEf64) {
2102 Opc = Subtarget->hasAVX() ? X86::VFsFLD0SD : X86::FsFLD0SD;
2103 RC = X86::FR64RegisterClass;
2105 Opc = X86::LD_Fp064;
2106 RC = X86::RFP64RegisterClass;
2110 // No f80 support yet.
2114 unsigned ResultReg = createResultReg(RC);
2115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2120 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2121 /// vreg is being provided by the specified load instruction. If possible,
2122 /// try to fold the load as an operand to the instruction, returning true if
2124 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2125 const LoadInst *LI) {
2127 if (!X86SelectAddress(LI->getOperand(0), AM))
2130 X86InstrInfo &XII = (X86InstrInfo&)TII;
2132 unsigned Size = TD.getTypeAllocSize(LI->getType());
2133 unsigned Alignment = LI->getAlignment();
2135 SmallVector<MachineOperand, 8> AddrOps;
2136 AM.getFullAddress(AddrOps);
2138 MachineInstr *Result =
2139 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2140 if (Result == 0) return false;
2142 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2143 MI->eraseFromParent();
2149 llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
2150 return new X86FastISel(funcInfo);