1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "X86CallingConv.h"
18 #include "X86ISelLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.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/IR/CallingConv.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/Support/CallSite.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Target/TargetOptions.h"
44 class X86FastISel : public FastISel {
45 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
46 /// make the right decision when generating code for different targets.
47 const X86Subtarget *Subtarget;
49 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
50 /// floating point ops.
51 /// When SSE is available, use it for f32 operations.
52 /// When SSE2 is available, use it for f64 operations.
57 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
58 const TargetLibraryInfo *libInfo)
59 : FastISel(funcInfo, libInfo) {
60 Subtarget = &TM.getSubtarget<X86Subtarget>();
61 X86ScalarSSEf64 = Subtarget->hasSSE2();
62 X86ScalarSSEf32 = Subtarget->hasSSE1();
65 virtual bool TargetSelectInstruction(const Instruction *I);
67 /// \brief The specified machine instr operand is a vreg, and that
68 /// vreg is being provided by the specified load instruction. If possible,
69 /// try to fold the load as an operand to the instruction, returning true if
71 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
74 virtual bool FastLowerArguments();
76 #include "X86GenFastISel.inc"
79 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
81 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
83 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
84 bool Aligned = false);
85 bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM,
86 bool Aligned = false);
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 X86SelectDivRem(const Instruction *I);
110 bool X86SelectSelect(const Instruction *I);
112 bool X86SelectTrunc(const Instruction *I);
114 bool X86SelectFPExt(const Instruction *I);
115 bool X86SelectFPTrunc(const Instruction *I);
117 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
118 bool X86SelectCall(const Instruction *I);
120 bool DoSelectCall(const Instruction *I, const char *MemIntName);
122 const X86InstrInfo *getInstrInfo() const {
123 return getTargetMachine()->getInstrInfo();
125 const X86TargetMachine *getTargetMachine() const {
126 return static_cast<const X86TargetMachine *>(&TM);
129 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
131 unsigned TargetMaterializeConstant(const Constant *C);
133 unsigned TargetMaterializeAlloca(const AllocaInst *C);
135 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
137 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
138 /// computed in an SSE register, not on the X87 floating point stack.
139 bool isScalarFPTypeInSSEReg(EVT VT) const {
140 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
141 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
144 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
146 bool IsMemcpySmall(uint64_t Len);
148 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
149 X86AddressMode SrcAM, uint64_t Len);
152 } // end anonymous namespace.
154 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
155 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
156 if (evt == MVT::Other || !evt.isSimple())
157 // Unhandled type. Halt "fast" selection and bail.
160 VT = evt.getSimpleVT();
161 // For now, require SSE/SSE2 for performing floating-point operations,
162 // since x87 requires additional work.
163 if (VT == MVT::f64 && !X86ScalarSSEf64)
165 if (VT == MVT::f32 && !X86ScalarSSEf32)
167 // Similarly, no f80 support yet.
170 // We only handle legal types. For example, on x86-32 the instruction
171 // selector contains all of the 64-bit instructions from x86-64,
172 // under the assumption that i64 won't be used if the target doesn't
174 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
177 #include "X86GenCallingConv.inc"
179 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
180 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
181 /// Return true and the result register by reference if it is possible.
182 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
183 unsigned &ResultReg) {
184 // Get opcode and regclass of the output for the given load instruction.
186 const TargetRegisterClass *RC = NULL;
187 switch (VT.getSimpleVT().SimpleTy) {
188 default: return false;
192 RC = &X86::GR8RegClass;
196 RC = &X86::GR16RegClass;
200 RC = &X86::GR32RegClass;
203 // Must be in x86-64 mode.
205 RC = &X86::GR64RegClass;
208 if (X86ScalarSSEf32) {
209 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
210 RC = &X86::FR32RegClass;
213 RC = &X86::RFP32RegClass;
217 if (X86ScalarSSEf64) {
218 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
219 RC = &X86::FR64RegClass;
222 RC = &X86::RFP64RegClass;
226 // No f80 support yet.
230 ResultReg = createResultReg(RC);
231 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
232 DL, TII.get(Opc), ResultReg), AM);
236 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
237 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
238 /// and a displacement offset, or a GlobalAddress,
239 /// i.e. V. Return true if it is possible.
241 X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg,
242 const X86AddressMode &AM, bool Aligned) {
243 // Get opcode and regclass of the output for the given store instruction.
245 switch (VT.getSimpleVT().SimpleTy) {
246 case MVT::f80: // No f80 support yet.
247 default: return false;
249 // Mask out all but lowest bit.
250 unsigned AndResult = createResultReg(&X86::GR8RegClass);
251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
252 TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1);
255 // FALLTHROUGH, handling i1 as i8.
256 case MVT::i8: Opc = X86::MOV8mr; break;
257 case MVT::i16: Opc = X86::MOV16mr; break;
258 case MVT::i32: Opc = X86::MOV32mr; break;
259 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
261 Opc = X86ScalarSSEf32 ?
262 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
265 Opc = X86ScalarSSEf64 ?
266 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
270 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
272 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
276 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
278 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
285 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
287 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
291 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
292 DL, TII.get(Opc)), AM).addReg(ValReg);
296 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
297 const X86AddressMode &AM, bool Aligned) {
298 // Handle 'null' like i32/i64 0.
299 if (isa<ConstantPointerNull>(Val))
300 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
302 // If this is a store of a simple constant, fold the constant into the store.
303 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
306 switch (VT.getSimpleVT().SimpleTy) {
308 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
309 case MVT::i8: Opc = X86::MOV8mi; break;
310 case MVT::i16: Opc = X86::MOV16mi; break;
311 case MVT::i32: Opc = X86::MOV32mi; break;
313 // Must be a 32-bit sign extended value.
314 if (isInt<32>(CI->getSExtValue()))
315 Opc = X86::MOV64mi32;
320 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
321 DL, TII.get(Opc)), AM)
322 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
328 unsigned ValReg = getRegForValue(Val);
332 return X86FastEmitStore(VT, ValReg, AM, Aligned);
335 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
336 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
337 /// ISD::SIGN_EXTEND).
338 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
339 unsigned Src, EVT SrcVT,
340 unsigned &ResultReg) {
341 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
342 Src, /*TODO: Kill=*/false);
350 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
351 // Handle constant address.
352 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
353 // Can't handle alternate code models yet.
354 if (TM.getCodeModel() != CodeModel::Small)
357 // Can't handle TLS yet.
358 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
359 if (GVar->isThreadLocal())
362 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
364 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
365 if (const GlobalVariable *GVar =
366 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
367 if (GVar->isThreadLocal())
370 // RIP-relative addresses can't have additional register operands, so if
371 // we've already folded stuff into the addressing mode, just force the
372 // global value into its own register, which we can use as the basereg.
373 if (!Subtarget->isPICStyleRIPRel() ||
374 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
375 // Okay, we've committed to selecting this global. Set up the address.
378 // Allow the subtarget to classify the global.
379 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
381 // If this reference is relative to the pic base, set it now.
382 if (isGlobalRelativeToPICBase(GVFlags)) {
383 // FIXME: How do we know Base.Reg is free??
384 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
387 // Unless the ABI requires an extra load, return a direct reference to
389 if (!isGlobalStubReference(GVFlags)) {
390 if (Subtarget->isPICStyleRIPRel()) {
391 // Use rip-relative addressing if we can. Above we verified that the
392 // base and index registers are unused.
393 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
394 AM.Base.Reg = X86::RIP;
396 AM.GVOpFlags = GVFlags;
400 // Ok, we need to do a load from a stub. If we've already loaded from
401 // this stub, reuse the loaded pointer, otherwise emit the load now.
402 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
404 if (I != LocalValueMap.end() && I->second != 0) {
407 // Issue load from stub.
409 const TargetRegisterClass *RC = NULL;
410 X86AddressMode StubAM;
411 StubAM.Base.Reg = AM.Base.Reg;
413 StubAM.GVOpFlags = GVFlags;
415 // Prepare for inserting code in the local-value area.
416 SavePoint SaveInsertPt = enterLocalValueArea();
418 if (TLI.getPointerTy() == MVT::i64) {
420 RC = &X86::GR64RegClass;
422 if (Subtarget->isPICStyleRIPRel())
423 StubAM.Base.Reg = X86::RIP;
426 RC = &X86::GR32RegClass;
429 LoadReg = createResultReg(RC);
430 MachineInstrBuilder LoadMI =
431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
432 addFullAddress(LoadMI, StubAM);
434 // Ok, back to normal mode.
435 leaveLocalValueArea(SaveInsertPt);
437 // Prevent loading GV stub multiple times in same MBB.
438 LocalValueMap[V] = LoadReg;
441 // Now construct the final address. Note that the Disp, Scale,
442 // and Index values may already be set here.
443 AM.Base.Reg = LoadReg;
449 // If all else fails, try to materialize the value in a register.
450 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
451 if (AM.Base.Reg == 0) {
452 AM.Base.Reg = getRegForValue(V);
453 return AM.Base.Reg != 0;
455 if (AM.IndexReg == 0) {
456 assert(AM.Scale == 1 && "Scale with no index!");
457 AM.IndexReg = getRegForValue(V);
458 return AM.IndexReg != 0;
465 /// X86SelectAddress - Attempt to fill in an address from the given value.
467 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
468 SmallVector<const Value *, 32> GEPs;
470 const User *U = NULL;
471 unsigned Opcode = Instruction::UserOp1;
472 if (const Instruction *I = dyn_cast<Instruction>(V)) {
473 // Don't walk into other basic blocks; it's possible we haven't
474 // visited them yet, so the instructions may not yet be assigned
475 // virtual registers.
476 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
477 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
478 Opcode = I->getOpcode();
481 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
482 Opcode = C->getOpcode();
486 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
487 if (Ty->getAddressSpace() > 255)
488 // Fast instruction selection doesn't support the special
494 case Instruction::BitCast:
495 // Look past bitcasts.
496 return X86SelectAddress(U->getOperand(0), AM);
498 case Instruction::IntToPtr:
499 // Look past no-op inttoptrs.
500 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
501 return X86SelectAddress(U->getOperand(0), AM);
504 case Instruction::PtrToInt:
505 // Look past no-op ptrtoints.
506 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
507 return X86SelectAddress(U->getOperand(0), AM);
510 case Instruction::Alloca: {
511 // Do static allocas.
512 const AllocaInst *A = cast<AllocaInst>(V);
513 DenseMap<const AllocaInst*, int>::iterator SI =
514 FuncInfo.StaticAllocaMap.find(A);
515 if (SI != FuncInfo.StaticAllocaMap.end()) {
516 AM.BaseType = X86AddressMode::FrameIndexBase;
517 AM.Base.FrameIndex = SI->second;
523 case Instruction::Add: {
524 // Adds of constants are common and easy enough.
525 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
526 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
527 // They have to fit in the 32-bit signed displacement field though.
528 if (isInt<32>(Disp)) {
529 AM.Disp = (uint32_t)Disp;
530 return X86SelectAddress(U->getOperand(0), AM);
536 case Instruction::GetElementPtr: {
537 X86AddressMode SavedAM = AM;
539 // Pattern-match simple GEPs.
540 uint64_t Disp = (int32_t)AM.Disp;
541 unsigned IndexReg = AM.IndexReg;
542 unsigned Scale = AM.Scale;
543 gep_type_iterator GTI = gep_type_begin(U);
544 // Iterate through the indices, folding what we can. Constants can be
545 // folded, and one dynamic index can be handled, if the scale is supported.
546 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
547 i != e; ++i, ++GTI) {
548 const Value *Op = *i;
549 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
550 const StructLayout *SL = TD.getStructLayout(STy);
551 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
555 // A array/variable index is always of the form i*S where S is the
556 // constant scale size. See if we can push the scale into immediates.
557 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
559 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
560 // Constant-offset addressing.
561 Disp += CI->getSExtValue() * S;
564 if (isa<AddOperator>(Op) &&
565 (!isa<Instruction>(Op) ||
566 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
568 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
569 // An add (in the same block) with a constant operand. Fold the
572 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
573 Disp += CI->getSExtValue() * S;
574 // Iterate on the other operand.
575 Op = cast<AddOperator>(Op)->getOperand(0);
579 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
580 (S == 1 || S == 2 || S == 4 || S == 8)) {
581 // Scaled-index addressing.
583 IndexReg = getRegForGEPIndex(Op).first;
589 goto unsupported_gep;
593 // Check for displacement overflow.
594 if (!isInt<32>(Disp))
597 AM.IndexReg = IndexReg;
599 AM.Disp = (uint32_t)Disp;
602 if (const GetElementPtrInst *GEP =
603 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
604 // Ok, the GEP indices were covered by constant-offset and scaled-index
605 // addressing. Update the address state and move on to examining the base.
608 } else if (X86SelectAddress(U->getOperand(0), AM)) {
612 // If we couldn't merge the gep value into this addr mode, revert back to
613 // our address and just match the value instead of completely failing.
616 for (SmallVectorImpl<const Value *>::reverse_iterator
617 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
618 if (handleConstantAddresses(*I, AM))
623 // Ok, the GEP indices weren't all covered.
628 return handleConstantAddresses(V, AM);
631 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
633 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
634 const User *U = NULL;
635 unsigned Opcode = Instruction::UserOp1;
636 const Instruction *I = dyn_cast<Instruction>(V);
637 // Record if the value is defined in the same basic block.
639 // This information is crucial to know whether or not folding an
641 // Indeed, FastISel generates or reuses a virtual register for all
642 // operands of all instructions it selects. Obviously, the definition and
643 // its uses must use the same virtual register otherwise the produced
644 // code is incorrect.
645 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
646 // registers for values that are alive across basic blocks. This ensures
647 // that the values are consistently set between across basic block, even
648 // if different instruction selection mechanisms are used (e.g., a mix of
649 // SDISel and FastISel).
650 // For values local to a basic block, the instruction selection process
651 // generates these virtual registers with whatever method is appropriate
652 // for its needs. In particular, FastISel and SDISel do not share the way
653 // local virtual registers are set.
654 // Therefore, this is impossible (or at least unsafe) to share values
655 // between basic blocks unless they use the same instruction selection
656 // method, which is not guarantee for X86.
657 // Moreover, things like hasOneUse could not be used accurately, if we
658 // allow to reference values across basic blocks whereas they are not
659 // alive across basic blocks initially.
662 Opcode = I->getOpcode();
664 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
665 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
666 Opcode = C->getOpcode();
672 case Instruction::BitCast:
673 // Look past bitcasts if its operand is in the same BB.
675 return X86SelectCallAddress(U->getOperand(0), AM);
678 case Instruction::IntToPtr:
679 // Look past no-op inttoptrs if its operand is in the same BB.
681 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
682 return X86SelectCallAddress(U->getOperand(0), AM);
685 case Instruction::PtrToInt:
686 // Look past no-op ptrtoints if its operand is in the same BB.
688 TLI.getValueType(U->getType()) == TLI.getPointerTy())
689 return X86SelectCallAddress(U->getOperand(0), AM);
693 // Handle constant address.
694 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
695 // Can't handle alternate code models yet.
696 if (TM.getCodeModel() != CodeModel::Small)
699 // RIP-relative addresses can't have additional register operands.
700 if (Subtarget->isPICStyleRIPRel() &&
701 (AM.Base.Reg != 0 || AM.IndexReg != 0))
704 // Can't handle DLLImport.
705 if (GV->hasDLLImportLinkage())
709 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
710 if (GVar->isThreadLocal())
713 // Okay, we've committed to selecting this global. Set up the basic address.
716 // No ABI requires an extra load for anything other than DLLImport, which
717 // we rejected above. Return a direct reference to the global.
718 if (Subtarget->isPICStyleRIPRel()) {
719 // Use rip-relative addressing if we can. Above we verified that the
720 // base and index registers are unused.
721 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
722 AM.Base.Reg = X86::RIP;
723 } else if (Subtarget->isPICStyleStubPIC()) {
724 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
725 } else if (Subtarget->isPICStyleGOT()) {
726 AM.GVOpFlags = X86II::MO_GOTOFF;
732 // If all else fails, try to materialize the value in a register.
733 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
734 if (AM.Base.Reg == 0) {
735 AM.Base.Reg = getRegForValue(V);
736 return AM.Base.Reg != 0;
738 if (AM.IndexReg == 0) {
739 assert(AM.Scale == 1 && "Scale with no index!");
740 AM.IndexReg = getRegForValue(V);
741 return AM.IndexReg != 0;
749 /// X86SelectStore - Select and emit code to implement store instructions.
750 bool X86FastISel::X86SelectStore(const Instruction *I) {
751 // Atomic stores need special handling.
752 const StoreInst *S = cast<StoreInst>(I);
757 unsigned SABIAlignment =
758 TD.getABITypeAlignment(S->getValueOperand()->getType());
759 bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment;
762 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
766 if (!X86SelectAddress(I->getOperand(1), AM))
769 return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned);
772 /// X86SelectRet - Select and emit code to implement ret instructions.
773 bool X86FastISel::X86SelectRet(const Instruction *I) {
774 const ReturnInst *Ret = cast<ReturnInst>(I);
775 const Function &F = *I->getParent()->getParent();
776 const X86MachineFunctionInfo *X86MFInfo =
777 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
779 if (!FuncInfo.CanLowerReturn)
782 CallingConv::ID CC = F.getCallingConv();
783 if (CC != CallingConv::C &&
784 CC != CallingConv::Fast &&
785 CC != CallingConv::X86_FastCall &&
786 CC != CallingConv::X86_64_SysV)
789 if (Subtarget->isCallingConvWin64(CC))
792 // Don't handle popping bytes on return for now.
793 if (X86MFInfo->getBytesToPopOnReturn() != 0)
796 // fastcc with -tailcallopt is intended to provide a guaranteed
797 // tail call optimization. Fastisel doesn't know how to do that.
798 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
801 // Let SDISel handle vararg functions.
805 // Build a list of return value registers.
806 SmallVector<unsigned, 4> RetRegs;
808 if (Ret->getNumOperands() > 0) {
809 SmallVector<ISD::OutputArg, 4> Outs;
810 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
812 // Analyze operands of the call, assigning locations to each operand.
813 SmallVector<CCValAssign, 16> ValLocs;
814 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
816 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
818 const Value *RV = Ret->getOperand(0);
819 unsigned Reg = getRegForValue(RV);
823 // Only handle a single return value for now.
824 if (ValLocs.size() != 1)
827 CCValAssign &VA = ValLocs[0];
829 // Don't bother handling odd stuff for now.
830 if (VA.getLocInfo() != CCValAssign::Full)
832 // Only handle register returns for now.
836 // The calling-convention tables for x87 returns don't tell
838 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
841 unsigned SrcReg = Reg + VA.getValNo();
842 EVT SrcVT = TLI.getValueType(RV->getType());
843 EVT DstVT = VA.getValVT();
844 // Special handling for extended integers.
845 if (SrcVT != DstVT) {
846 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
849 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
852 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
854 if (SrcVT == MVT::i1) {
855 if (Outs[0].Flags.isSExt())
857 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
860 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
862 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
863 SrcReg, /*TODO: Kill=*/false);
867 unsigned DstReg = VA.getLocReg();
868 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
869 // Avoid a cross-class copy. This is very unlikely.
870 if (!SrcRC->contains(DstReg))
872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
873 DstReg).addReg(SrcReg);
875 // Add register to return instruction.
876 RetRegs.push_back(VA.getLocReg());
879 // The x86-64 ABI for returning structs by value requires that we copy
880 // the sret argument into %rax for the return. We saved the argument into
881 // a virtual register in the entry block, so now we copy the value out
882 // and into %rax. We also do the same with %eax for Win32.
883 if (F.hasStructRetAttr() &&
884 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
885 unsigned Reg = X86MFInfo->getSRetReturnReg();
887 "SRetReturnReg should have been set in LowerFormalArguments()!");
888 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
889 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
891 RetRegs.push_back(RetReg);
895 MachineInstrBuilder MIB =
896 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
897 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
898 MIB.addReg(RetRegs[i], RegState::Implicit);
902 /// X86SelectLoad - Select and emit code to implement load instructions.
904 bool X86FastISel::X86SelectLoad(const Instruction *I) {
905 // Atomic loads need special handling.
906 if (cast<LoadInst>(I)->isAtomic())
910 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
914 if (!X86SelectAddress(I->getOperand(0), AM))
917 unsigned ResultReg = 0;
918 if (X86FastEmitLoad(VT, AM, ResultReg)) {
919 UpdateValueMap(I, ResultReg);
925 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
926 bool HasAVX = Subtarget->hasAVX();
927 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
928 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
930 switch (VT.getSimpleVT().SimpleTy) {
932 case MVT::i8: return X86::CMP8rr;
933 case MVT::i16: return X86::CMP16rr;
934 case MVT::i32: return X86::CMP32rr;
935 case MVT::i64: return X86::CMP64rr;
937 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
939 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
943 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
944 /// of the comparison, return an opcode that works for the compare (e.g.
945 /// CMP32ri) otherwise return 0.
946 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
947 switch (VT.getSimpleVT().SimpleTy) {
948 // Otherwise, we can't fold the immediate into this comparison.
950 case MVT::i8: return X86::CMP8ri;
951 case MVT::i16: return X86::CMP16ri;
952 case MVT::i32: return X86::CMP32ri;
954 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
956 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
957 return X86::CMP64ri32;
962 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
964 unsigned Op0Reg = getRegForValue(Op0);
965 if (Op0Reg == 0) return false;
967 // Handle 'null' like i32/i64 0.
968 if (isa<ConstantPointerNull>(Op1))
969 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
971 // We have two options: compare with register or immediate. If the RHS of
972 // the compare is an immediate that we can fold into this compare, use
973 // CMPri, otherwise use CMPrr.
974 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
975 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
978 .addImm(Op1C->getSExtValue());
983 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
984 if (CompareOpc == 0) return false;
986 unsigned Op1Reg = getRegForValue(Op1);
987 if (Op1Reg == 0) return false;
988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
995 bool X86FastISel::X86SelectCmp(const Instruction *I) {
996 const CmpInst *CI = cast<CmpInst>(I);
999 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1002 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
1004 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1005 switch (CI->getPredicate()) {
1006 case CmpInst::FCMP_OEQ: {
1007 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1010 unsigned EReg = createResultReg(&X86::GR8RegClass);
1011 unsigned NPReg = createResultReg(&X86::GR8RegClass);
1012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
1013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1014 TII.get(X86::SETNPr), NPReg);
1015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1016 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
1017 UpdateValueMap(I, ResultReg);
1020 case CmpInst::FCMP_UNE: {
1021 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1024 unsigned NEReg = createResultReg(&X86::GR8RegClass);
1025 unsigned PReg = createResultReg(&X86::GR8RegClass);
1026 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
1027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
1028 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
1029 .addReg(PReg).addReg(NEReg);
1030 UpdateValueMap(I, ResultReg);
1033 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1034 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1035 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
1036 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
1037 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1038 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
1039 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
1040 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1041 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
1042 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
1043 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1044 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1046 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1047 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1048 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1049 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1050 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1051 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1052 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
1053 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
1054 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
1055 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
1060 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1062 std::swap(Op0, Op1);
1064 // Emit a compare of Op0/Op1.
1065 if (!X86FastEmitCompare(Op0, Op1, VT))
1068 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
1069 UpdateValueMap(I, ResultReg);
1073 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1074 EVT DstVT = TLI.getValueType(I->getType());
1075 if (!TLI.isTypeLegal(DstVT))
1078 unsigned ResultReg = getRegForValue(I->getOperand(0));
1082 // Handle zero-extension from i1 to i8, which is common.
1083 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1084 if (SrcVT.SimpleTy == MVT::i1) {
1085 // Set the high bits to zero.
1086 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1093 if (DstVT == MVT::i64) {
1094 // Handle extension to 64-bits via sub-register shenanigans.
1097 switch (SrcVT.SimpleTy) {
1098 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1099 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1100 case MVT::i32: MovInst = X86::MOV32rr; break;
1101 default: llvm_unreachable("Unexpected zext to i64 source type");
1104 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1105 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32)
1108 ResultReg = createResultReg(&X86::GR64RegClass);
1109 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG),
1111 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1112 } else if (DstVT != MVT::i8) {
1113 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1114 ResultReg, /*Kill=*/true);
1119 UpdateValueMap(I, ResultReg);
1124 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1125 // Unconditional branches are selected by tablegen-generated code.
1126 // Handle a conditional branch.
1127 const BranchInst *BI = cast<BranchInst>(I);
1128 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1129 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1131 // Fold the common case of a conditional branch with a comparison
1132 // in the same block (values defined on other blocks may not have
1133 // initialized registers).
1134 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1135 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1136 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1138 // Try to take advantage of fallthrough opportunities.
1139 CmpInst::Predicate Predicate = CI->getPredicate();
1140 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1141 std::swap(TrueMBB, FalseMBB);
1142 Predicate = CmpInst::getInversePredicate(Predicate);
1145 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1146 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1148 switch (Predicate) {
1149 case CmpInst::FCMP_OEQ:
1150 std::swap(TrueMBB, FalseMBB);
1151 Predicate = CmpInst::FCMP_UNE;
1153 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1154 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1155 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1156 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1157 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1158 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1159 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1160 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1161 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1162 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1163 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1164 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1165 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1167 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1168 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1169 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1170 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1171 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1172 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1173 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1174 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1175 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1176 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1181 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1183 std::swap(Op0, Op1);
1185 // Emit a compare of the LHS and RHS, setting the flags.
1186 if (!X86FastEmitCompare(Op0, Op1, VT))
1189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1192 if (Predicate == CmpInst::FCMP_UNE) {
1193 // X86 requires a second branch to handle UNE (and OEQ,
1194 // which is mapped to UNE above).
1195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1199 FastEmitBranch(FalseMBB, DL);
1200 FuncInfo.MBB->addSuccessor(TrueMBB);
1203 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1204 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1205 // typically happen for _Bool and C++ bools.
1207 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1208 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1209 unsigned TestOpc = 0;
1210 switch (SourceVT.SimpleTy) {
1212 case MVT::i8: TestOpc = X86::TEST8ri; break;
1213 case MVT::i16: TestOpc = X86::TEST16ri; break;
1214 case MVT::i32: TestOpc = X86::TEST32ri; break;
1215 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1218 unsigned OpReg = getRegForValue(TI->getOperand(0));
1219 if (OpReg == 0) return false;
1220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1221 .addReg(OpReg).addImm(1);
1223 unsigned JmpOpc = X86::JNE_4;
1224 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1225 std::swap(TrueMBB, FalseMBB);
1229 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1231 FastEmitBranch(FalseMBB, DL);
1232 FuncInfo.MBB->addSuccessor(TrueMBB);
1238 // Otherwise do a clumsy setcc and re-test it.
1239 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1240 // in an explicit cast, so make sure to handle that correctly.
1241 unsigned OpReg = getRegForValue(BI->getCondition());
1242 if (OpReg == 0) return false;
1244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1245 .addReg(OpReg).addImm(1);
1246 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1248 FastEmitBranch(FalseMBB, DL);
1249 FuncInfo.MBB->addSuccessor(TrueMBB);
1253 bool X86FastISel::X86SelectShift(const Instruction *I) {
1254 unsigned CReg = 0, OpReg = 0;
1255 const TargetRegisterClass *RC = NULL;
1256 if (I->getType()->isIntegerTy(8)) {
1258 RC = &X86::GR8RegClass;
1259 switch (I->getOpcode()) {
1260 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1261 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1262 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1263 default: return false;
1265 } else if (I->getType()->isIntegerTy(16)) {
1267 RC = &X86::GR16RegClass;
1268 switch (I->getOpcode()) {
1269 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1270 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1271 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1272 default: return false;
1274 } else if (I->getType()->isIntegerTy(32)) {
1276 RC = &X86::GR32RegClass;
1277 switch (I->getOpcode()) {
1278 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1279 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1280 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1281 default: return false;
1283 } else if (I->getType()->isIntegerTy(64)) {
1285 RC = &X86::GR64RegClass;
1286 switch (I->getOpcode()) {
1287 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1288 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1289 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1290 default: return false;
1297 if (!isTypeLegal(I->getType(), VT))
1300 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1301 if (Op0Reg == 0) return false;
1303 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1304 if (Op1Reg == 0) return false;
1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1306 CReg).addReg(Op1Reg);
1308 // The shift instruction uses X86::CL. If we defined a super-register
1309 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1310 if (CReg != X86::CL)
1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1312 TII.get(TargetOpcode::KILL), X86::CL)
1313 .addReg(CReg, RegState::Kill);
1315 unsigned ResultReg = createResultReg(RC);
1316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1318 UpdateValueMap(I, ResultReg);
1322 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1323 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1324 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1325 const static bool S = true; // IsSigned
1326 const static bool U = false; // !IsSigned
1327 const static unsigned Copy = TargetOpcode::COPY;
1328 // For the X86 DIV/IDIV instruction, in most cases the dividend
1329 // (numerator) must be in a specific register pair highreg:lowreg,
1330 // producing the quotient in lowreg and the remainder in highreg.
1331 // For most data types, to set up the instruction, the dividend is
1332 // copied into lowreg, and lowreg is sign-extended or zero-extended
1333 // into highreg. The exception is i8, where the dividend is defined
1334 // as a single register rather than a register pair, and we
1335 // therefore directly sign-extend or zero-extend the dividend into
1336 // lowreg, instead of copying, and ignore the highreg.
1337 const static struct DivRemEntry {
1338 // The following portion depends only on the data type.
1339 const TargetRegisterClass *RC;
1340 unsigned LowInReg; // low part of the register pair
1341 unsigned HighInReg; // high part of the register pair
1342 // The following portion depends on both the data type and the operation.
1343 struct DivRemResult {
1344 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1345 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1346 // highreg, or copying a zero into highreg.
1347 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1348 // zero/sign-extending into lowreg for i8.
1349 unsigned DivRemResultReg; // Register containing the desired result.
1350 bool IsOpSigned; // Whether to use signed or unsigned form.
1351 } ResultTable[NumOps];
1352 } OpTable[NumTypes] = {
1353 { &X86::GR8RegClass, X86::AX, 0, {
1354 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1355 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1356 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1357 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1360 { &X86::GR16RegClass, X86::AX, X86::DX, {
1361 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1362 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1363 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1364 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1367 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1368 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1369 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1370 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1371 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1374 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1375 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1376 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1377 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1378 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1384 if (!isTypeLegal(I->getType(), VT))
1387 unsigned TypeIndex, OpIndex;
1388 switch (VT.SimpleTy) {
1389 default: return false;
1390 case MVT::i8: TypeIndex = 0; break;
1391 case MVT::i16: TypeIndex = 1; break;
1392 case MVT::i32: TypeIndex = 2; break;
1393 case MVT::i64: TypeIndex = 3;
1394 if (!Subtarget->is64Bit())
1399 switch (I->getOpcode()) {
1400 default: llvm_unreachable("Unexpected div/rem opcode");
1401 case Instruction::SDiv: OpIndex = 0; break;
1402 case Instruction::SRem: OpIndex = 1; break;
1403 case Instruction::UDiv: OpIndex = 2; break;
1404 case Instruction::URem: OpIndex = 3; break;
1407 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1408 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1409 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1412 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1416 // Move op0 into low-order input register.
1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1418 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1419 // Zero-extend or sign-extend into high-order input register.
1420 if (OpEntry.OpSignExtend) {
1421 if (OpEntry.IsOpSigned)
1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1423 TII.get(OpEntry.OpSignExtend));
1425 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1427 TII.get(X86::MOV32r0), Zero32);
1429 // Copy the zero into the appropriate sub/super/identical physical
1430 // register. Unfortunately the operations needed are not uniform enough to
1431 // fit neatly into the table above.
1432 if (VT.SimpleTy == MVT::i16) {
1433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1434 TII.get(Copy), TypeEntry.HighInReg)
1435 .addReg(Zero32, 0, X86::sub_16bit);
1436 } else if (VT.SimpleTy == MVT::i32) {
1437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1438 TII.get(Copy), TypeEntry.HighInReg)
1440 } else if (VT.SimpleTy == MVT::i64) {
1441 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1442 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1443 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1447 // Generate the DIV/IDIV instruction.
1448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1449 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1450 // For i8 remainder, we can't reference AH directly, as we'll end
1451 // up with bogus copies like %R9B = COPY %AH. Reference AX
1452 // instead to prevent AH references in a REX instruction.
1454 // The current assumption of the fast register allocator is that isel
1455 // won't generate explicit references to the GPR8_NOREX registers. If
1456 // the allocator and/or the backend get enhanced to be more robust in
1457 // that regard, this can be, and should be, removed.
1458 unsigned ResultReg = 0;
1459 if ((I->getOpcode() == Instruction::SRem ||
1460 I->getOpcode() == Instruction::URem) &&
1461 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1462 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1463 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1465 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1467 // Shift AX right by 8 bits instead of using AH.
1468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SHR16ri),
1469 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1471 // Now reference the 8-bit subreg of the result.
1472 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1473 /*Kill=*/true, X86::sub_8bit);
1475 // Copy the result out of the physreg if we haven't already.
1477 ResultReg = createResultReg(TypeEntry.RC);
1478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Copy), ResultReg)
1479 .addReg(OpEntry.DivRemResultReg);
1481 UpdateValueMap(I, ResultReg);
1486 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1488 if (!isTypeLegal(I->getType(), VT))
1491 // We only use cmov here, if we don't have a cmov instruction bail.
1492 if (!Subtarget->hasCMov()) return false;
1495 const TargetRegisterClass *RC = NULL;
1496 if (VT == MVT::i16) {
1497 Opc = X86::CMOVE16rr;
1498 RC = &X86::GR16RegClass;
1499 } else if (VT == MVT::i32) {
1500 Opc = X86::CMOVE32rr;
1501 RC = &X86::GR32RegClass;
1502 } else if (VT == MVT::i64) {
1503 Opc = X86::CMOVE64rr;
1504 RC = &X86::GR64RegClass;
1509 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1510 if (Op0Reg == 0) return false;
1511 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1512 if (Op1Reg == 0) return false;
1513 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1514 if (Op2Reg == 0) return false;
1516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1517 .addReg(Op0Reg).addReg(Op0Reg);
1518 unsigned ResultReg = createResultReg(RC);
1519 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1520 .addReg(Op1Reg).addReg(Op2Reg);
1521 UpdateValueMap(I, ResultReg);
1525 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1526 // fpext from float to double.
1527 if (X86ScalarSSEf64 &&
1528 I->getType()->isDoubleTy()) {
1529 const Value *V = I->getOperand(0);
1530 if (V->getType()->isFloatTy()) {
1531 unsigned OpReg = getRegForValue(V);
1532 if (OpReg == 0) return false;
1533 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1534 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1535 TII.get(X86::CVTSS2SDrr), ResultReg)
1537 UpdateValueMap(I, ResultReg);
1545 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1546 if (X86ScalarSSEf64) {
1547 if (I->getType()->isFloatTy()) {
1548 const Value *V = I->getOperand(0);
1549 if (V->getType()->isDoubleTy()) {
1550 unsigned OpReg = getRegForValue(V);
1551 if (OpReg == 0) return false;
1552 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1553 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1554 TII.get(X86::CVTSD2SSrr), ResultReg)
1556 UpdateValueMap(I, ResultReg);
1565 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1566 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1567 EVT DstVT = TLI.getValueType(I->getType());
1569 // This code only handles truncation to byte.
1570 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1572 if (!TLI.isTypeLegal(SrcVT))
1575 unsigned InputReg = getRegForValue(I->getOperand(0));
1577 // Unhandled operand. Halt "fast" selection and bail.
1580 if (SrcVT == MVT::i8) {
1581 // Truncate from i8 to i1; no code needed.
1582 UpdateValueMap(I, InputReg);
1586 if (!Subtarget->is64Bit()) {
1587 // If we're on x86-32; we can't extract an i8 from a general register.
1588 // First issue a copy to GR16_ABCD or GR32_ABCD.
1589 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1590 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1591 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1592 unsigned CopyReg = createResultReg(CopyRC);
1593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1594 CopyReg).addReg(InputReg);
1598 // Issue an extract_subreg.
1599 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1600 InputReg, /*Kill=*/true,
1605 UpdateValueMap(I, ResultReg);
1609 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1610 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1613 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1614 X86AddressMode SrcAM, uint64_t Len) {
1616 // Make sure we don't bloat code by inlining very large memcpy's.
1617 if (!IsMemcpySmall(Len))
1620 bool i64Legal = Subtarget->is64Bit();
1622 // We don't care about alignment here since we just emit integer accesses.
1625 if (Len >= 8 && i64Legal)
1636 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1637 RV &= X86FastEmitStore(VT, Reg, DestAM);
1638 assert(RV && "Failed to emit load or store??");
1640 unsigned Size = VT.getSizeInBits()/8;
1642 DestAM.Disp += Size;
1649 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1650 // FIXME: Handle more intrinsics.
1651 switch (I.getIntrinsicID()) {
1652 default: return false;
1653 case Intrinsic::memcpy: {
1654 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1655 // Don't handle volatile or variable length memcpys.
1656 if (MCI.isVolatile())
1659 if (isa<ConstantInt>(MCI.getLength())) {
1660 // Small memcpy's are common enough that we want to do them
1661 // without a call if possible.
1662 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1663 if (IsMemcpySmall(Len)) {
1664 X86AddressMode DestAM, SrcAM;
1665 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1666 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1668 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1673 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1674 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1677 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1680 return DoSelectCall(&I, "memcpy");
1682 case Intrinsic::memset: {
1683 const MemSetInst &MSI = cast<MemSetInst>(I);
1685 if (MSI.isVolatile())
1688 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1689 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1692 if (MSI.getDestAddressSpace() > 255)
1695 return DoSelectCall(&I, "memset");
1697 case Intrinsic::stackprotector: {
1698 // Emit code to store the stack guard onto the stack.
1699 EVT PtrTy = TLI.getPointerTy();
1701 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1702 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1704 // Grab the frame index.
1706 if (!X86SelectAddress(Slot, AM)) return false;
1707 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1710 case Intrinsic::dbg_declare: {
1711 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1713 assert(DI->getAddress() && "Null address should be checked earlier!");
1714 if (!X86SelectAddress(DI->getAddress(), AM))
1716 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1717 // FIXME may need to add RegState::Debug to any registers produced,
1718 // although ESP/EBP should be the only ones at the moment.
1719 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1720 addImm(0).addMetadata(DI->getVariable());
1723 case Intrinsic::trap: {
1724 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1727 case Intrinsic::sadd_with_overflow:
1728 case Intrinsic::uadd_with_overflow: {
1729 // FIXME: Should fold immediates.
1731 // Replace "add with overflow" intrinsics with an "add" instruction followed
1732 // by a seto/setc instruction.
1733 const Function *Callee = I.getCalledFunction();
1735 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1738 if (!isTypeLegal(RetTy, VT))
1741 const Value *Op1 = I.getArgOperand(0);
1742 const Value *Op2 = I.getArgOperand(1);
1743 unsigned Reg1 = getRegForValue(Op1);
1744 unsigned Reg2 = getRegForValue(Op2);
1746 if (Reg1 == 0 || Reg2 == 0)
1747 // FIXME: Handle values *not* in registers.
1753 else if (VT == MVT::i64)
1758 // The call to CreateRegs builds two sequential registers, to store the
1759 // both the returned values.
1760 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1761 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1762 .addReg(Reg1).addReg(Reg2);
1764 unsigned Opc = X86::SETBr;
1765 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1767 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1769 UpdateValueMap(&I, ResultReg, 2);
1775 bool X86FastISel::FastLowerArguments() {
1776 if (!FuncInfo.CanLowerReturn)
1779 const Function *F = FuncInfo.Fn;
1783 CallingConv::ID CC = F->getCallingConv();
1784 if (CC != CallingConv::C)
1787 if (Subtarget->isCallingConvWin64(CC))
1790 if (!Subtarget->is64Bit())
1793 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1795 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1796 I != E; ++I, ++Idx) {
1800 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1801 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1802 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1803 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1806 Type *ArgTy = I->getType();
1807 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1810 EVT ArgVT = TLI.getValueType(ArgTy);
1811 if (!ArgVT.isSimple()) return false;
1812 switch (ArgVT.getSimpleVT().SimpleTy) {
1821 static const uint16_t GPR32ArgRegs[] = {
1822 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1824 static const uint16_t GPR64ArgRegs[] = {
1825 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1829 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1830 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1831 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1832 I != E; ++I, ++Idx) {
1833 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1834 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1835 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1836 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1837 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1838 // Without this, EmitLiveInCopies may eliminate the livein if its only
1839 // use is a bitcast (which isn't turned into an instruction).
1840 unsigned ResultReg = createResultReg(RC);
1841 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1842 ResultReg).addReg(DstReg, getKillRegState(true));
1843 UpdateValueMap(I, ResultReg);
1848 bool X86FastISel::X86SelectCall(const Instruction *I) {
1849 const CallInst *CI = cast<CallInst>(I);
1850 const Value *Callee = CI->getCalledValue();
1852 // Can't handle inline asm yet.
1853 if (isa<InlineAsm>(Callee))
1856 // Handle intrinsic calls.
1857 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1858 return X86VisitIntrinsicCall(*II);
1860 // Allow SelectionDAG isel to handle tail calls.
1861 if (cast<CallInst>(I)->isTailCall())
1864 return DoSelectCall(I, 0);
1867 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1868 const ImmutableCallSite &CS) {
1869 if (Subtarget.is64Bit())
1871 if (Subtarget.isTargetWindows())
1873 CallingConv::ID CC = CS.getCallingConv();
1874 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1876 if (!CS.paramHasAttr(1, Attribute::StructRet))
1878 if (CS.paramHasAttr(1, Attribute::InReg))
1883 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1884 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1885 const CallInst *CI = cast<CallInst>(I);
1886 const Value *Callee = CI->getCalledValue();
1888 // Handle only C and fastcc calling conventions for now.
1889 ImmutableCallSite CS(CI);
1890 CallingConv::ID CC = CS.getCallingConv();
1891 bool isWin64 = Subtarget->isCallingConvWin64(CC);
1892 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1893 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
1894 CC != CallingConv::X86_64_SysV)
1897 // fastcc with -tailcallopt is intended to provide a guaranteed
1898 // tail call optimization. Fastisel doesn't know how to do that.
1899 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1902 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1903 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1904 bool isVarArg = FTy->isVarArg();
1906 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1907 // x86-32. Special handling for x86-64 is implemented.
1908 if (isVarArg && isWin64)
1911 // Fast-isel doesn't know about callee-pop yet.
1912 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1913 TM.Options.GuaranteedTailCallOpt))
1916 // Check whether the function can return without sret-demotion.
1917 SmallVector<ISD::OutputArg, 4> Outs;
1918 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1919 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1920 *FuncInfo.MF, FTy->isVarArg(),
1921 Outs, FTy->getContext());
1922 if (!CanLowerReturn)
1925 // Materialize callee address in a register. FIXME: GV address can be
1926 // handled with a CALLpcrel32 instead.
1927 X86AddressMode CalleeAM;
1928 if (!X86SelectCallAddress(Callee, CalleeAM))
1930 unsigned CalleeOp = 0;
1931 const GlobalValue *GV = 0;
1932 if (CalleeAM.GV != 0) {
1934 } else if (CalleeAM.Base.Reg != 0) {
1935 CalleeOp = CalleeAM.Base.Reg;
1939 // Deal with call operands first.
1940 SmallVector<const Value *, 8> ArgVals;
1941 SmallVector<unsigned, 8> Args;
1942 SmallVector<MVT, 8> ArgVTs;
1943 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1944 unsigned arg_size = CS.arg_size();
1945 Args.reserve(arg_size);
1946 ArgVals.reserve(arg_size);
1947 ArgVTs.reserve(arg_size);
1948 ArgFlags.reserve(arg_size);
1949 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1951 // If we're lowering a mem intrinsic instead of a regular call, skip the
1952 // last two arguments, which should not passed to the underlying functions.
1953 if (MemIntName && e-i <= 2)
1956 ISD::ArgFlagsTy Flags;
1957 unsigned AttrInd = i - CS.arg_begin() + 1;
1958 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1960 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1963 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1964 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1965 Type *ElementTy = Ty->getElementType();
1966 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1967 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1969 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1971 Flags.setByValSize(FrameSize);
1972 Flags.setByValAlign(FrameAlign);
1973 if (!IsMemcpySmall(FrameSize))
1977 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1979 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1982 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1983 // instruction. This is safe because it is common to all fastisel supported
1984 // calling conventions on x86.
1985 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1986 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1987 CI->getBitWidth() == 16) {
1989 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1991 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1997 // Passing bools around ends up doing a trunc to i1 and passing it.
1998 // Codegen this as an argument + "and 1".
1999 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2000 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2001 ArgVal->hasOneUse()) {
2002 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2003 ArgReg = getRegForValue(ArgVal);
2004 if (ArgReg == 0) return false;
2007 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2009 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2010 ArgVal->hasOneUse(), 1);
2012 ArgReg = getRegForValue(ArgVal);
2015 if (ArgReg == 0) return false;
2017 Type *ArgTy = ArgVal->getType();
2019 if (!isTypeLegal(ArgTy, ArgVT))
2021 if (ArgVT == MVT::x86mmx)
2023 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2024 Flags.setOrigAlign(OriginalAlignment);
2026 Args.push_back(ArgReg);
2027 ArgVals.push_back(ArgVal);
2028 ArgVTs.push_back(ArgVT);
2029 ArgFlags.push_back(Flags);
2032 // Analyze operands of the call, assigning locations to each operand.
2033 SmallVector<CCValAssign, 16> ArgLocs;
2034 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2035 I->getParent()->getContext());
2037 // Allocate shadow area for Win64
2039 CCInfo.AllocateStack(32, 8);
2041 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2043 // Get a count of how many bytes are to be pushed on the stack.
2044 unsigned NumBytes = CCInfo.getNextStackOffset();
2046 // Issue CALLSEQ_START
2047 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
2051 // Process argument: walk the register/memloc assignments, inserting
2053 SmallVector<unsigned, 4> RegArgs;
2054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2055 CCValAssign &VA = ArgLocs[i];
2056 unsigned Arg = Args[VA.getValNo()];
2057 EVT ArgVT = ArgVTs[VA.getValNo()];
2059 // Promote the value if needed.
2060 switch (VA.getLocInfo()) {
2061 case CCValAssign::Full: break;
2062 case CCValAssign::SExt: {
2063 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2064 "Unexpected extend");
2065 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2067 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2068 ArgVT = VA.getLocVT();
2071 case CCValAssign::ZExt: {
2072 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2073 "Unexpected extend");
2074 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2076 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2077 ArgVT = VA.getLocVT();
2080 case CCValAssign::AExt: {
2081 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2082 "Unexpected extend");
2083 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2086 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2089 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2092 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2093 ArgVT = VA.getLocVT();
2096 case CCValAssign::BCvt: {
2097 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2098 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2099 assert(BC != 0 && "Failed to emit a bitcast!");
2101 ArgVT = VA.getLocVT();
2104 case CCValAssign::VExt:
2105 // VExt has not been implemented, so this should be impossible to reach
2106 // for now. However, fallback to Selection DAG isel once implemented.
2108 case CCValAssign::Indirect:
2109 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2114 if (VA.isRegLoc()) {
2115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2116 VA.getLocReg()).addReg(Arg);
2117 RegArgs.push_back(VA.getLocReg());
2119 unsigned LocMemOffset = VA.getLocMemOffset();
2121 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2122 getTargetMachine()->getRegisterInfo());
2123 AM.Base.Reg = RegInfo->getStackRegister();
2124 AM.Disp = LocMemOffset;
2125 const Value *ArgVal = ArgVals[VA.getValNo()];
2126 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2128 if (Flags.isByVal()) {
2129 X86AddressMode SrcAM;
2130 SrcAM.Base.Reg = Arg;
2131 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2132 assert(Res && "memcpy length already checked!"); (void)Res;
2133 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2134 // If this is a really simple value, emit this with the Value* version
2135 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2136 // as it can cause us to reevaluate the argument.
2137 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2140 if (!X86FastEmitStore(ArgVT, Arg, AM))
2146 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2148 if (Subtarget->isPICStyleGOT()) {
2149 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2150 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2151 X86::EBX).addReg(Base);
2154 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2155 // Count the number of XMM registers allocated.
2156 static const uint16_t XMMArgRegs[] = {
2157 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2158 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2160 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2161 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2162 X86::AL).addImm(NumXMMRegs);
2166 MachineInstrBuilder MIB;
2168 // Register-indirect call.
2170 if (Subtarget->is64Bit())
2171 CallOpc = X86::CALL64r;
2173 CallOpc = X86::CALL32r;
2174 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2179 assert(GV && "Not a direct call");
2181 if (Subtarget->is64Bit())
2182 CallOpc = X86::CALL64pcrel32;
2184 CallOpc = X86::CALLpcrel32;
2186 // See if we need any target-specific flags on the GV operand.
2187 unsigned char OpFlags = 0;
2189 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2190 // external symbols most go through the PLT in PIC mode. If the symbol
2191 // has hidden or protected visibility, or if it is static or local, then
2192 // we don't need to use the PLT - we can directly call it.
2193 if (Subtarget->isTargetELF() &&
2194 TM.getRelocationModel() == Reloc::PIC_ &&
2195 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2196 OpFlags = X86II::MO_PLT;
2197 } else if (Subtarget->isPICStyleStubAny() &&
2198 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2199 (!Subtarget->getTargetTriple().isMacOSX() ||
2200 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2201 // PC-relative references to external symbols should go through $stub,
2202 // unless we're building with the leopard linker or later, which
2203 // automatically synthesizes these stubs.
2204 OpFlags = X86II::MO_DARWIN_STUB;
2208 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2210 MIB.addExternalSymbol(MemIntName, OpFlags);
2212 MIB.addGlobalAddress(GV, 0, OpFlags);
2215 // Add a register mask with the call-preserved registers.
2216 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2217 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2219 // Add an implicit use GOT pointer in EBX.
2220 if (Subtarget->isPICStyleGOT())
2221 MIB.addReg(X86::EBX, RegState::Implicit);
2223 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2224 MIB.addReg(X86::AL, RegState::Implicit);
2226 // Add implicit physical register uses to the call.
2227 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2228 MIB.addReg(RegArgs[i], RegState::Implicit);
2230 // Issue CALLSEQ_END
2231 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2232 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2234 .addImm(NumBytes).addImm(NumBytesCallee);
2236 // Build info for return calling conv lowering code.
2237 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2238 SmallVector<ISD::InputArg, 32> Ins;
2239 SmallVector<EVT, 4> RetTys;
2240 ComputeValueVTs(TLI, I->getType(), RetTys);
2241 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2243 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2244 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2245 for (unsigned j = 0; j != NumRegs; ++j) {
2246 ISD::InputArg MyFlags;
2247 MyFlags.VT = RegisterVT;
2248 MyFlags.Used = !CS.getInstruction()->use_empty();
2249 if (CS.paramHasAttr(0, Attribute::SExt))
2250 MyFlags.Flags.setSExt();
2251 if (CS.paramHasAttr(0, Attribute::ZExt))
2252 MyFlags.Flags.setZExt();
2253 if (CS.paramHasAttr(0, Attribute::InReg))
2254 MyFlags.Flags.setInReg();
2255 Ins.push_back(MyFlags);
2259 // Now handle call return values.
2260 SmallVector<unsigned, 4> UsedRegs;
2261 SmallVector<CCValAssign, 16> RVLocs;
2262 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2263 I->getParent()->getContext());
2264 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2265 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2266 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2267 EVT CopyVT = RVLocs[i].getValVT();
2268 unsigned CopyReg = ResultReg + i;
2270 // If this is a call to a function that returns an fp value on the x87 fp
2271 // stack, but where we prefer to use the value in xmm registers, copy it
2272 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2273 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2274 RVLocs[i].getLocReg() == X86::ST1)) {
2275 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2277 CopyReg = createResultReg(&X86::RFP80RegClass);
2279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2282 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2283 CopyReg).addReg(RVLocs[i].getLocReg());
2284 UsedRegs.push_back(RVLocs[i].getLocReg());
2287 if (CopyVT != RVLocs[i].getValVT()) {
2288 // Round the F80 the right size, which also moves to the appropriate xmm
2289 // register. This is accomplished by storing the F80 value in memory and
2290 // then loading it back. Ewww...
2291 EVT ResVT = RVLocs[i].getValVT();
2292 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2293 unsigned MemSize = ResVT.getSizeInBits()/8;
2294 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2295 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2298 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2299 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2300 TII.get(Opc), ResultReg + i), FI);
2305 UpdateValueMap(I, ResultReg, RVLocs.size());
2307 // Set all unused physreg defs as dead.
2308 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2315 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2316 switch (I->getOpcode()) {
2318 case Instruction::Load:
2319 return X86SelectLoad(I);
2320 case Instruction::Store:
2321 return X86SelectStore(I);
2322 case Instruction::Ret:
2323 return X86SelectRet(I);
2324 case Instruction::ICmp:
2325 case Instruction::FCmp:
2326 return X86SelectCmp(I);
2327 case Instruction::ZExt:
2328 return X86SelectZExt(I);
2329 case Instruction::Br:
2330 return X86SelectBranch(I);
2331 case Instruction::Call:
2332 return X86SelectCall(I);
2333 case Instruction::LShr:
2334 case Instruction::AShr:
2335 case Instruction::Shl:
2336 return X86SelectShift(I);
2337 case Instruction::SDiv:
2338 case Instruction::UDiv:
2339 case Instruction::SRem:
2340 case Instruction::URem:
2341 return X86SelectDivRem(I);
2342 case Instruction::Select:
2343 return X86SelectSelect(I);
2344 case Instruction::Trunc:
2345 return X86SelectTrunc(I);
2346 case Instruction::FPExt:
2347 return X86SelectFPExt(I);
2348 case Instruction::FPTrunc:
2349 return X86SelectFPTrunc(I);
2350 case Instruction::IntToPtr: // Deliberate fall-through.
2351 case Instruction::PtrToInt: {
2352 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2353 EVT DstVT = TLI.getValueType(I->getType());
2354 if (DstVT.bitsGT(SrcVT))
2355 return X86SelectZExt(I);
2356 if (DstVT.bitsLT(SrcVT))
2357 return X86SelectTrunc(I);
2358 unsigned Reg = getRegForValue(I->getOperand(0));
2359 if (Reg == 0) return false;
2360 UpdateValueMap(I, Reg);
2368 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2370 if (!isTypeLegal(C->getType(), VT))
2373 // Can't handle alternate code models yet.
2374 if (TM.getCodeModel() != CodeModel::Small)
2377 // Get opcode and regclass of the output for the given load instruction.
2379 const TargetRegisterClass *RC = NULL;
2380 switch (VT.SimpleTy) {
2384 RC = &X86::GR8RegClass;
2388 RC = &X86::GR16RegClass;
2392 RC = &X86::GR32RegClass;
2395 // Must be in x86-64 mode.
2397 RC = &X86::GR64RegClass;
2400 if (X86ScalarSSEf32) {
2401 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2402 RC = &X86::FR32RegClass;
2404 Opc = X86::LD_Fp32m;
2405 RC = &X86::RFP32RegClass;
2409 if (X86ScalarSSEf64) {
2410 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2411 RC = &X86::FR64RegClass;
2413 Opc = X86::LD_Fp64m;
2414 RC = &X86::RFP64RegClass;
2418 // No f80 support yet.
2422 // Materialize addresses with LEA instructions.
2423 if (isa<GlobalValue>(C)) {
2425 if (X86SelectAddress(C, AM)) {
2426 // If the expression is just a basereg, then we're done, otherwise we need
2428 if (AM.BaseType == X86AddressMode::RegBase &&
2429 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2432 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2433 unsigned ResultReg = createResultReg(RC);
2434 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2435 TII.get(Opc), ResultReg), AM);
2441 // MachineConstantPool wants an explicit alignment.
2442 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2444 // Alignment of vector types. FIXME!
2445 Align = TD.getTypeAllocSize(C->getType());
2448 // x86-32 PIC requires a PIC base register for constant pools.
2449 unsigned PICBase = 0;
2450 unsigned char OpFlag = 0;
2451 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2452 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2453 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2454 } else if (Subtarget->isPICStyleGOT()) {
2455 OpFlag = X86II::MO_GOTOFF;
2456 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2457 } else if (Subtarget->isPICStyleRIPRel() &&
2458 TM.getCodeModel() == CodeModel::Small) {
2462 // Create the load from the constant pool.
2463 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2464 unsigned ResultReg = createResultReg(RC);
2465 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2466 TII.get(Opc), ResultReg),
2467 MCPOffset, PICBase, OpFlag);
2472 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2473 // Fail on dynamic allocas. At this point, getRegForValue has already
2474 // checked its CSE maps, so if we're here trying to handle a dynamic
2475 // alloca, we're not going to succeed. X86SelectAddress has a
2476 // check for dynamic allocas, because it's called directly from
2477 // various places, but TargetMaterializeAlloca also needs a check
2478 // in order to avoid recursion between getRegForValue,
2479 // X86SelectAddrss, and TargetMaterializeAlloca.
2480 if (!FuncInfo.StaticAllocaMap.count(C))
2484 if (!X86SelectAddress(C, AM))
2486 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2487 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2488 unsigned ResultReg = createResultReg(RC);
2489 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2490 TII.get(Opc), ResultReg), AM);
2494 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2496 if (!isTypeLegal(CF->getType(), VT))
2499 // Get opcode and regclass for the given zero.
2501 const TargetRegisterClass *RC = NULL;
2502 switch (VT.SimpleTy) {
2505 if (X86ScalarSSEf32) {
2506 Opc = X86::FsFLD0SS;
2507 RC = &X86::FR32RegClass;
2509 Opc = X86::LD_Fp032;
2510 RC = &X86::RFP32RegClass;
2514 if (X86ScalarSSEf64) {
2515 Opc = X86::FsFLD0SD;
2516 RC = &X86::FR64RegClass;
2518 Opc = X86::LD_Fp064;
2519 RC = &X86::RFP64RegClass;
2523 // No f80 support yet.
2527 unsigned ResultReg = createResultReg(RC);
2528 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2533 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2534 const LoadInst *LI) {
2536 if (!X86SelectAddress(LI->getOperand(0), AM))
2539 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2541 unsigned Size = TD.getTypeAllocSize(LI->getType());
2542 unsigned Alignment = LI->getAlignment();
2544 SmallVector<MachineOperand, 8> AddrOps;
2545 AM.getFullAddress(AddrOps);
2547 MachineInstr *Result =
2548 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2549 if (Result == 0) return false;
2551 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2552 MI->eraseFromParent();
2558 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2559 const TargetLibraryInfo *libInfo) {
2560 return new X86FastISel(funcInfo, libInfo);