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/CodeGen/FastISel.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Target/TargetOptions.h"
39 class X86FastISel : public FastISel {
40 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
41 /// make the right decision when generating code for different targets.
42 const X86Subtarget *Subtarget;
44 /// StackPtr - Register used as the stack pointer.
48 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
49 /// floating point ops.
50 /// When SSE is available, use it for f32 operations.
51 /// When SSE2 is available, use it for f64 operations.
56 explicit X86FastISel(MachineFunction &mf,
57 MachineModuleInfo *mmi,
58 DenseMap<const Value *, unsigned> &vm,
59 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
60 DenseMap<const AllocaInst *, int> &am
62 , SmallSet<Instruction*, 8> &cil
65 : FastISel(mf, mmi, vm, bm, am
70 Subtarget = &TM.getSubtarget<X86Subtarget>();
71 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
72 X86ScalarSSEf64 = Subtarget->hasSSE2();
73 X86ScalarSSEf32 = Subtarget->hasSSE1();
76 virtual bool TargetSelectInstruction(Instruction *I);
78 #include "X86GenFastISel.inc"
81 bool X86FastEmitCompare(Value *LHS, Value *RHS, EVT VT);
83 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
85 bool X86FastEmitStore(EVT VT, Value *Val,
86 const X86AddressMode &AM);
87 bool X86FastEmitStore(EVT VT, unsigned Val,
88 const X86AddressMode &AM);
90 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
93 bool X86SelectAddress(Value *V, X86AddressMode &AM);
94 bool X86SelectCallAddress(Value *V, X86AddressMode &AM);
96 bool X86SelectLoad(Instruction *I);
98 bool X86SelectStore(Instruction *I);
100 bool X86SelectCmp(Instruction *I);
102 bool X86SelectZExt(Instruction *I);
104 bool X86SelectBranch(Instruction *I);
106 bool X86SelectShift(Instruction *I);
108 bool X86SelectSelect(Instruction *I);
110 bool X86SelectTrunc(Instruction *I);
112 bool X86SelectFPExt(Instruction *I);
113 bool X86SelectFPTrunc(Instruction *I);
115 bool X86SelectExtractValue(Instruction *I);
117 bool X86VisitIntrinsicCall(IntrinsicInst &I);
118 bool X86SelectCall(Instruction *I);
120 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool isTailCall = false);
122 const X86InstrInfo *getInstrInfo() const {
123 return getTargetMachine()->getInstrInfo();
125 const X86TargetMachine *getTargetMachine() const {
126 return static_cast<const X86TargetMachine *>(&TM);
129 unsigned TargetMaterializeConstant(Constant *C);
131 unsigned TargetMaterializeAlloca(AllocaInst *C);
133 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
134 /// computed in an SSE register, not on the X87 floating point stack.
135 bool isScalarFPTypeInSSEReg(EVT VT) const {
136 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
137 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
140 bool isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1 = false);
143 } // end anonymous namespace.
145 bool X86FastISel::isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1) {
146 VT = TLI.getValueType(Ty, /*HandleUnknown=*/true);
147 if (VT == MVT::Other || !VT.isSimple())
148 // Unhandled type. Halt "fast" selection and bail.
151 // For now, require SSE/SSE2 for performing floating-point operations,
152 // since x87 requires additional work.
153 if (VT == MVT::f64 && !X86ScalarSSEf64)
155 if (VT == MVT::f32 && !X86ScalarSSEf32)
157 // Similarly, no f80 support yet.
160 // We only handle legal types. For example, on x86-32 the instruction
161 // selector contains all of the 64-bit instructions from x86-64,
162 // under the assumption that i64 won't be used if the target doesn't
164 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
167 #include "X86GenCallingConv.inc"
169 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
171 CCAssignFn *X86FastISel::CCAssignFnForCall(CallingConv::ID CC,
173 if (Subtarget->is64Bit()) {
174 if (CC == CallingConv::GHC)
175 return CC_X86_64_GHC;
176 else if (Subtarget->isTargetWin64())
177 return CC_X86_Win64_C;
182 if (CC == CallingConv::X86_FastCall)
183 return CC_X86_32_FastCall;
184 else if (CC == CallingConv::Fast)
185 return CC_X86_32_FastCC;
186 else if (CC == CallingConv::GHC)
187 return CC_X86_32_GHC;
192 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
193 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
194 /// Return true and the result register by reference if it is possible.
195 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
196 unsigned &ResultReg) {
197 // Get opcode and regclass of the output for the given load instruction.
199 const TargetRegisterClass *RC = NULL;
200 switch (VT.getSimpleVT().SimpleTy) {
201 default: return false;
205 RC = X86::GR8RegisterClass;
209 RC = X86::GR16RegisterClass;
213 RC = X86::GR32RegisterClass;
216 // Must be in x86-64 mode.
218 RC = X86::GR64RegisterClass;
221 if (Subtarget->hasSSE1()) {
223 RC = X86::FR32RegisterClass;
226 RC = X86::RFP32RegisterClass;
230 if (Subtarget->hasSSE2()) {
232 RC = X86::FR64RegisterClass;
235 RC = X86::RFP64RegisterClass;
239 // No f80 support yet.
243 ResultReg = createResultReg(RC);
244 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
248 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
249 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
250 /// and a displacement offset, or a GlobalAddress,
251 /// i.e. V. Return true if it is possible.
253 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val,
254 const X86AddressMode &AM) {
255 // Get opcode and regclass of the output for the given store instruction.
257 switch (VT.getSimpleVT().SimpleTy) {
258 case MVT::f80: // No f80 support yet.
259 default: return false;
261 // Mask out all but lowest bit.
262 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
264 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
267 // FALLTHROUGH, handling i1 as i8.
268 case MVT::i8: Opc = X86::MOV8mr; break;
269 case MVT::i16: Opc = X86::MOV16mr; break;
270 case MVT::i32: Opc = X86::MOV32mr; break;
271 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
273 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
276 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
280 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM).addReg(Val);
284 bool X86FastISel::X86FastEmitStore(EVT VT, Value *Val,
285 const X86AddressMode &AM) {
286 // Handle 'null' like i32/i64 0.
287 if (isa<ConstantPointerNull>(Val))
288 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
290 // If this is a store of a simple constant, fold the constant into the store.
291 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
294 switch (VT.getSimpleVT().SimpleTy) {
296 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
297 case MVT::i8: Opc = X86::MOV8mi; break;
298 case MVT::i16: Opc = X86::MOV16mi; break;
299 case MVT::i32: Opc = X86::MOV32mi; break;
301 // Must be a 32-bit sign extended value.
302 if ((int)CI->getSExtValue() == CI->getSExtValue())
303 Opc = X86::MOV64mi32;
308 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM)
309 .addImm(Signed ? CI->getSExtValue() :
315 unsigned ValReg = getRegForValue(Val);
319 return X86FastEmitStore(VT, ValReg, AM);
322 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
323 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
324 /// ISD::SIGN_EXTEND).
325 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
326 unsigned Src, EVT SrcVT,
327 unsigned &ResultReg) {
328 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
337 /// X86SelectAddress - Attempt to fill in an address from the given value.
339 bool X86FastISel::X86SelectAddress(Value *V, X86AddressMode &AM) {
341 unsigned Opcode = Instruction::UserOp1;
342 if (Instruction *I = dyn_cast<Instruction>(V)) {
343 Opcode = I->getOpcode();
345 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
346 Opcode = C->getOpcode();
352 case Instruction::BitCast:
353 // Look past bitcasts.
354 return X86SelectAddress(U->getOperand(0), AM);
356 case Instruction::IntToPtr:
357 // Look past no-op inttoptrs.
358 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
359 return X86SelectAddress(U->getOperand(0), AM);
362 case Instruction::PtrToInt:
363 // Look past no-op ptrtoints.
364 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
365 return X86SelectAddress(U->getOperand(0), AM);
368 case Instruction::Alloca: {
369 // Do static allocas.
370 const AllocaInst *A = cast<AllocaInst>(V);
371 DenseMap<const AllocaInst*, int>::iterator SI = StaticAllocaMap.find(A);
372 if (SI != StaticAllocaMap.end()) {
373 AM.BaseType = X86AddressMode::FrameIndexBase;
374 AM.Base.FrameIndex = SI->second;
380 case Instruction::Add: {
381 // Adds of constants are common and easy enough.
382 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
383 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
384 // They have to fit in the 32-bit signed displacement field though.
385 if (isInt<32>(Disp)) {
386 AM.Disp = (uint32_t)Disp;
387 return X86SelectAddress(U->getOperand(0), AM);
393 case Instruction::GetElementPtr: {
394 X86AddressMode SavedAM = AM;
396 // Pattern-match simple GEPs.
397 uint64_t Disp = (int32_t)AM.Disp;
398 unsigned IndexReg = AM.IndexReg;
399 unsigned Scale = AM.Scale;
400 gep_type_iterator GTI = gep_type_begin(U);
401 // Iterate through the indices, folding what we can. Constants can be
402 // folded, and one dynamic index can be handled, if the scale is supported.
403 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end();
404 i != e; ++i, ++GTI) {
406 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
407 const StructLayout *SL = TD.getStructLayout(STy);
408 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
409 Disp += SL->getElementOffset(Idx);
411 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
412 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
413 // Constant-offset addressing.
414 Disp += CI->getSExtValue() * S;
415 } else if (IndexReg == 0 &&
416 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
417 (S == 1 || S == 2 || S == 4 || S == 8)) {
418 // Scaled-index addressing.
420 IndexReg = getRegForGEPIndex(Op);
425 goto unsupported_gep;
428 // Check for displacement overflow.
429 if (!isInt<32>(Disp))
431 // Ok, the GEP indices were covered by constant-offset and scaled-index
432 // addressing. Update the address state and move on to examining the base.
433 AM.IndexReg = IndexReg;
435 AM.Disp = (uint32_t)Disp;
436 if (X86SelectAddress(U->getOperand(0), AM))
439 // If we couldn't merge the sub value into this addr mode, revert back to
440 // our address and just match the value instead of completely failing.
444 // Ok, the GEP indices weren't all covered.
449 // Handle constant address.
450 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
451 // Can't handle alternate code models yet.
452 if (TM.getCodeModel() != CodeModel::Small)
455 // RIP-relative addresses can't have additional register operands.
456 if (Subtarget->isPICStyleRIPRel() &&
457 (AM.Base.Reg != 0 || AM.IndexReg != 0))
460 // Can't handle TLS yet.
461 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
462 if (GVar->isThreadLocal())
465 // Okay, we've committed to selecting this global. Set up the basic address.
468 // Allow the subtarget to classify the global.
469 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
471 // If this reference is relative to the pic base, set it now.
472 if (isGlobalRelativeToPICBase(GVFlags)) {
473 // FIXME: How do we know Base.Reg is free??
474 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(&MF);
477 // Unless the ABI requires an extra load, return a direct reference to
479 if (!isGlobalStubReference(GVFlags)) {
480 if (Subtarget->isPICStyleRIPRel()) {
481 // Use rip-relative addressing if we can. Above we verified that the
482 // base and index registers are unused.
483 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
484 AM.Base.Reg = X86::RIP;
486 AM.GVOpFlags = GVFlags;
490 // Ok, we need to do a load from a stub. If we've already loaded from this
491 // stub, reuse the loaded pointer, otherwise emit the load now.
492 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
494 if (I != LocalValueMap.end() && I->second != 0) {
497 // Issue load from stub.
499 const TargetRegisterClass *RC = NULL;
500 X86AddressMode StubAM;
501 StubAM.Base.Reg = AM.Base.Reg;
503 StubAM.GVOpFlags = GVFlags;
505 if (TLI.getPointerTy() == MVT::i64) {
507 RC = X86::GR64RegisterClass;
509 if (Subtarget->isPICStyleRIPRel())
510 StubAM.Base.Reg = X86::RIP;
513 RC = X86::GR32RegisterClass;
516 LoadReg = createResultReg(RC);
517 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), LoadReg), StubAM);
519 // Prevent loading GV stub multiple times in same MBB.
520 LocalValueMap[V] = LoadReg;
523 // Now construct the final address. Note that the Disp, Scale,
524 // and Index values may already be set here.
525 AM.Base.Reg = LoadReg;
530 // If all else fails, try to materialize the value in a register.
531 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
532 if (AM.Base.Reg == 0) {
533 AM.Base.Reg = getRegForValue(V);
534 return AM.Base.Reg != 0;
536 if (AM.IndexReg == 0) {
537 assert(AM.Scale == 1 && "Scale with no index!");
538 AM.IndexReg = getRegForValue(V);
539 return AM.IndexReg != 0;
546 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
548 bool X86FastISel::X86SelectCallAddress(Value *V, X86AddressMode &AM) {
550 unsigned Opcode = Instruction::UserOp1;
551 if (Instruction *I = dyn_cast<Instruction>(V)) {
552 Opcode = I->getOpcode();
554 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
555 Opcode = C->getOpcode();
561 case Instruction::BitCast:
562 // Look past bitcasts.
563 return X86SelectCallAddress(U->getOperand(0), AM);
565 case Instruction::IntToPtr:
566 // Look past no-op inttoptrs.
567 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
568 return X86SelectCallAddress(U->getOperand(0), AM);
571 case Instruction::PtrToInt:
572 // Look past no-op ptrtoints.
573 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
574 return X86SelectCallAddress(U->getOperand(0), AM);
578 // Handle constant address.
579 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
580 // Can't handle alternate code models yet.
581 if (TM.getCodeModel() != CodeModel::Small)
584 // RIP-relative addresses can't have additional register operands.
585 if (Subtarget->isPICStyleRIPRel() &&
586 (AM.Base.Reg != 0 || AM.IndexReg != 0))
589 // Can't handle TLS or DLLImport.
590 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
591 if (GVar->isThreadLocal() || GVar->hasDLLImportLinkage())
594 // Okay, we've committed to selecting this global. Set up the basic address.
597 // No ABI requires an extra load for anything other than DLLImport, which
598 // we rejected above. Return a direct reference to the global.
599 if (Subtarget->isPICStyleRIPRel()) {
600 // Use rip-relative addressing if we can. Above we verified that the
601 // base and index registers are unused.
602 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
603 AM.Base.Reg = X86::RIP;
604 } else if (Subtarget->isPICStyleStubPIC()) {
605 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
606 } else if (Subtarget->isPICStyleGOT()) {
607 AM.GVOpFlags = X86II::MO_GOTOFF;
613 // If all else fails, try to materialize the value in a register.
614 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
615 if (AM.Base.Reg == 0) {
616 AM.Base.Reg = getRegForValue(V);
617 return AM.Base.Reg != 0;
619 if (AM.IndexReg == 0) {
620 assert(AM.Scale == 1 && "Scale with no index!");
621 AM.IndexReg = getRegForValue(V);
622 return AM.IndexReg != 0;
630 /// X86SelectStore - Select and emit code to implement store instructions.
631 bool X86FastISel::X86SelectStore(Instruction* I) {
633 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
637 if (!X86SelectAddress(I->getOperand(1), AM))
640 return X86FastEmitStore(VT, I->getOperand(0), AM);
643 /// X86SelectLoad - Select and emit code to implement load instructions.
645 bool X86FastISel::X86SelectLoad(Instruction *I) {
647 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
651 if (!X86SelectAddress(I->getOperand(0), AM))
654 unsigned ResultReg = 0;
655 if (X86FastEmitLoad(VT, AM, ResultReg)) {
656 UpdateValueMap(I, ResultReg);
662 static unsigned X86ChooseCmpOpcode(EVT VT) {
663 switch (VT.getSimpleVT().SimpleTy) {
665 case MVT::i8: return X86::CMP8rr;
666 case MVT::i16: return X86::CMP16rr;
667 case MVT::i32: return X86::CMP32rr;
668 case MVT::i64: return X86::CMP64rr;
669 case MVT::f32: return X86::UCOMISSrr;
670 case MVT::f64: return X86::UCOMISDrr;
674 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
675 /// of the comparison, return an opcode that works for the compare (e.g.
676 /// CMP32ri) otherwise return 0.
677 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, ConstantInt *RHSC) {
678 switch (VT.getSimpleVT().SimpleTy) {
679 // Otherwise, we can't fold the immediate into this comparison.
681 case MVT::i8: return X86::CMP8ri;
682 case MVT::i16: return X86::CMP16ri;
683 case MVT::i32: return X86::CMP32ri;
685 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
687 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
688 return X86::CMP64ri32;
693 bool X86FastISel::X86FastEmitCompare(Value *Op0, Value *Op1, EVT VT) {
694 unsigned Op0Reg = getRegForValue(Op0);
695 if (Op0Reg == 0) return false;
697 // Handle 'null' like i32/i64 0.
698 if (isa<ConstantPointerNull>(Op1))
699 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
701 // We have two options: compare with register or immediate. If the RHS of
702 // the compare is an immediate that we can fold into this compare, use
703 // CMPri, otherwise use CMPrr.
704 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
705 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
706 BuildMI(MBB, DL, TII.get(CompareImmOpc)).addReg(Op0Reg)
707 .addImm(Op1C->getSExtValue());
712 unsigned CompareOpc = X86ChooseCmpOpcode(VT);
713 if (CompareOpc == 0) return false;
715 unsigned Op1Reg = getRegForValue(Op1);
716 if (Op1Reg == 0) return false;
717 BuildMI(MBB, DL, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
722 bool X86FastISel::X86SelectCmp(Instruction *I) {
723 CmpInst *CI = cast<CmpInst>(I);
726 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
729 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
731 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
732 switch (CI->getPredicate()) {
733 case CmpInst::FCMP_OEQ: {
734 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
737 unsigned EReg = createResultReg(&X86::GR8RegClass);
738 unsigned NPReg = createResultReg(&X86::GR8RegClass);
739 BuildMI(MBB, DL, TII.get(X86::SETEr), EReg);
740 BuildMI(MBB, DL, TII.get(X86::SETNPr), NPReg);
742 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
743 UpdateValueMap(I, ResultReg);
746 case CmpInst::FCMP_UNE: {
747 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
750 unsigned NEReg = createResultReg(&X86::GR8RegClass);
751 unsigned PReg = createResultReg(&X86::GR8RegClass);
752 BuildMI(MBB, DL, TII.get(X86::SETNEr), NEReg);
753 BuildMI(MBB, DL, TII.get(X86::SETPr), PReg);
754 BuildMI(MBB, DL, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
755 UpdateValueMap(I, ResultReg);
758 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
759 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
760 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
761 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
762 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
763 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
764 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
765 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
766 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
767 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
768 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
769 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
771 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
772 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
773 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
774 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
775 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
776 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
777 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
778 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
779 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
780 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
785 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
789 // Emit a compare of Op0/Op1.
790 if (!X86FastEmitCompare(Op0, Op1, VT))
793 BuildMI(MBB, DL, TII.get(SetCCOpc), ResultReg);
794 UpdateValueMap(I, ResultReg);
798 bool X86FastISel::X86SelectZExt(Instruction *I) {
799 // Handle zero-extension from i1 to i8, which is common.
800 if (I->getType()->isIntegerTy(8) &&
801 I->getOperand(0)->getType()->isIntegerTy(1)) {
802 unsigned ResultReg = getRegForValue(I->getOperand(0));
803 if (ResultReg == 0) return false;
804 // Set the high bits to zero.
805 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg);
806 if (ResultReg == 0) return false;
807 UpdateValueMap(I, ResultReg);
815 bool X86FastISel::X86SelectBranch(Instruction *I) {
816 // Unconditional branches are selected by tablegen-generated code.
817 // Handle a conditional branch.
818 BranchInst *BI = cast<BranchInst>(I);
819 MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
820 MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
822 // Fold the common case of a conditional branch with a comparison.
823 if (CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
824 if (CI->hasOneUse()) {
825 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
827 // Try to take advantage of fallthrough opportunities.
828 CmpInst::Predicate Predicate = CI->getPredicate();
829 if (MBB->isLayoutSuccessor(TrueMBB)) {
830 std::swap(TrueMBB, FalseMBB);
831 Predicate = CmpInst::getInversePredicate(Predicate);
834 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
835 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
838 case CmpInst::FCMP_OEQ:
839 std::swap(TrueMBB, FalseMBB);
840 Predicate = CmpInst::FCMP_UNE;
842 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
843 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
844 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
845 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
846 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
847 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
848 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
849 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
850 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
851 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
852 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
853 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
854 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
856 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
857 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
858 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
859 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
860 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
861 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
862 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
863 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
864 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
865 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
870 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
874 // Emit a compare of the LHS and RHS, setting the flags.
875 if (!X86FastEmitCompare(Op0, Op1, VT))
878 BuildMI(MBB, DL, TII.get(BranchOpc)).addMBB(TrueMBB);
880 if (Predicate == CmpInst::FCMP_UNE) {
881 // X86 requires a second branch to handle UNE (and OEQ,
882 // which is mapped to UNE above).
883 BuildMI(MBB, DL, TII.get(X86::JP_4)).addMBB(TrueMBB);
886 FastEmitBranch(FalseMBB);
887 MBB->addSuccessor(TrueMBB);
890 } else if (ExtractValueInst *EI =
891 dyn_cast<ExtractValueInst>(BI->getCondition())) {
892 // Check to see if the branch instruction is from an "arithmetic with
893 // overflow" intrinsic. The main way these intrinsics are used is:
895 // %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
896 // %sum = extractvalue { i32, i1 } %t, 0
897 // %obit = extractvalue { i32, i1 } %t, 1
898 // br i1 %obit, label %overflow, label %normal
900 // The %sum and %obit are converted in an ADD and a SETO/SETB before
901 // reaching the branch. Therefore, we search backwards through the MBB
902 // looking for the SETO/SETB instruction. If an instruction modifies the
903 // EFLAGS register before we reach the SETO/SETB instruction, then we can't
904 // convert the branch into a JO/JB instruction.
905 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(EI->getAggregateOperand())){
906 if (CI->getIntrinsicID() == Intrinsic::sadd_with_overflow ||
907 CI->getIntrinsicID() == Intrinsic::uadd_with_overflow) {
908 const MachineInstr *SetMI = 0;
909 unsigned Reg = lookUpRegForValue(EI);
911 for (MachineBasicBlock::const_reverse_iterator
912 RI = MBB->rbegin(), RE = MBB->rend(); RI != RE; ++RI) {
913 const MachineInstr &MI = *RI;
915 if (MI.modifiesRegister(Reg)) {
916 unsigned Src, Dst, SrcSR, DstSR;
918 if (getInstrInfo()->isMoveInstr(MI, Src, Dst, SrcSR, DstSR)) {
927 const TargetInstrDesc &TID = MI.getDesc();
928 if (TID.hasUnmodeledSideEffects() ||
929 TID.hasImplicitDefOfPhysReg(X86::EFLAGS))
934 unsigned OpCode = SetMI->getOpcode();
936 if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
937 BuildMI(MBB, DL, TII.get(OpCode == X86::SETOr ?
938 X86::JO_4 : X86::JB_4))
940 FastEmitBranch(FalseMBB);
941 MBB->addSuccessor(TrueMBB);
949 // Otherwise do a clumsy setcc and re-test it.
950 unsigned OpReg = getRegForValue(BI->getCondition());
951 if (OpReg == 0) return false;
953 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
954 BuildMI(MBB, DL, TII.get(X86::JNE_4)).addMBB(TrueMBB);
955 FastEmitBranch(FalseMBB);
956 MBB->addSuccessor(TrueMBB);
960 bool X86FastISel::X86SelectShift(Instruction *I) {
961 unsigned CReg = 0, OpReg = 0, OpImm = 0;
962 const TargetRegisterClass *RC = NULL;
963 if (I->getType()->isIntegerTy(8)) {
965 RC = &X86::GR8RegClass;
966 switch (I->getOpcode()) {
967 case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
968 case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
969 case Instruction::Shl: OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
970 default: return false;
972 } else if (I->getType()->isIntegerTy(16)) {
974 RC = &X86::GR16RegClass;
975 switch (I->getOpcode()) {
976 case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
977 case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
978 case Instruction::Shl: OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
979 default: return false;
981 } else if (I->getType()->isIntegerTy(32)) {
983 RC = &X86::GR32RegClass;
984 switch (I->getOpcode()) {
985 case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
986 case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
987 case Instruction::Shl: OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
988 default: return false;
990 } else if (I->getType()->isIntegerTy(64)) {
992 RC = &X86::GR64RegClass;
993 switch (I->getOpcode()) {
994 case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
995 case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
996 case Instruction::Shl: OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
997 default: return false;
1003 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1004 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1007 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1008 if (Op0Reg == 0) return false;
1010 // Fold immediate in shl(x,3).
1011 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1012 unsigned ResultReg = createResultReg(RC);
1013 BuildMI(MBB, DL, TII.get(OpImm),
1014 ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
1015 UpdateValueMap(I, ResultReg);
1019 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1020 if (Op1Reg == 0) return false;
1021 TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
1023 // The shift instruction uses X86::CL. If we defined a super-register
1024 // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
1025 // we're doing here.
1026 if (CReg != X86::CL)
1027 BuildMI(MBB, DL, TII.get(TargetOpcode::EXTRACT_SUBREG), X86::CL)
1028 .addReg(CReg).addImm(X86::SUBREG_8BIT);
1030 unsigned ResultReg = createResultReg(RC);
1031 BuildMI(MBB, DL, TII.get(OpReg), ResultReg).addReg(Op0Reg);
1032 UpdateValueMap(I, ResultReg);
1036 bool X86FastISel::X86SelectSelect(Instruction *I) {
1037 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1038 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1042 const TargetRegisterClass *RC = NULL;
1043 if (VT.getSimpleVT() == MVT::i16) {
1044 Opc = X86::CMOVE16rr;
1045 RC = &X86::GR16RegClass;
1046 } else if (VT.getSimpleVT() == MVT::i32) {
1047 Opc = X86::CMOVE32rr;
1048 RC = &X86::GR32RegClass;
1049 } else if (VT.getSimpleVT() == MVT::i64) {
1050 Opc = X86::CMOVE64rr;
1051 RC = &X86::GR64RegClass;
1056 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1057 if (Op0Reg == 0) return false;
1058 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1059 if (Op1Reg == 0) return false;
1060 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1061 if (Op2Reg == 0) return false;
1063 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
1064 unsigned ResultReg = createResultReg(RC);
1065 BuildMI(MBB, DL, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
1066 UpdateValueMap(I, ResultReg);
1070 bool X86FastISel::X86SelectFPExt(Instruction *I) {
1071 // fpext from float to double.
1072 if (Subtarget->hasSSE2() &&
1073 I->getType()->isDoubleTy()) {
1074 Value *V = I->getOperand(0);
1075 if (V->getType()->isFloatTy()) {
1076 unsigned OpReg = getRegForValue(V);
1077 if (OpReg == 0) return false;
1078 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1079 BuildMI(MBB, DL, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
1080 UpdateValueMap(I, ResultReg);
1088 bool X86FastISel::X86SelectFPTrunc(Instruction *I) {
1089 if (Subtarget->hasSSE2()) {
1090 if (I->getType()->isFloatTy()) {
1091 Value *V = I->getOperand(0);
1092 if (V->getType()->isDoubleTy()) {
1093 unsigned OpReg = getRegForValue(V);
1094 if (OpReg == 0) return false;
1095 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1096 BuildMI(MBB, DL, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
1097 UpdateValueMap(I, ResultReg);
1106 bool X86FastISel::X86SelectTrunc(Instruction *I) {
1107 if (Subtarget->is64Bit())
1108 // All other cases should be handled by the tblgen generated code.
1110 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1111 EVT DstVT = TLI.getValueType(I->getType());
1113 // This code only handles truncation to byte right now.
1114 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1115 // All other cases should be handled by the tblgen generated code.
1117 if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1118 // All other cases should be handled by the tblgen generated code.
1121 unsigned InputReg = getRegForValue(I->getOperand(0));
1123 // Unhandled operand. Halt "fast" selection and bail.
1126 // First issue a copy to GR16_ABCD or GR32_ABCD.
1127 unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16rr : X86::MOV32rr;
1128 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1129 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1130 unsigned CopyReg = createResultReg(CopyRC);
1131 BuildMI(MBB, DL, TII.get(CopyOpc), CopyReg).addReg(InputReg);
1133 // Then issue an extract_subreg.
1134 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1135 CopyReg, X86::SUBREG_8BIT);
1139 UpdateValueMap(I, ResultReg);
1143 bool X86FastISel::X86SelectExtractValue(Instruction *I) {
1144 ExtractValueInst *EI = cast<ExtractValueInst>(I);
1145 Value *Agg = EI->getAggregateOperand();
1147 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1148 switch (CI->getIntrinsicID()) {
1150 case Intrinsic::sadd_with_overflow:
1151 case Intrinsic::uadd_with_overflow:
1152 // Cheat a little. We know that the registers for "add" and "seto" are
1153 // allocated sequentially. However, we only keep track of the register
1154 // for "add" in the value map. Use extractvalue's index to get the
1155 // correct register for "seto".
1156 UpdateValueMap(I, lookUpRegForValue(Agg) + *EI->idx_begin());
1164 bool X86FastISel::X86VisitIntrinsicCall(IntrinsicInst &I) {
1165 // FIXME: Handle more intrinsics.
1166 switch (I.getIntrinsicID()) {
1167 default: return false;
1168 case Intrinsic::stackprotector: {
1169 // Emit code inline code to store the stack guard onto the stack.
1170 EVT PtrTy = TLI.getPointerTy();
1172 Value *Op1 = I.getOperand(1); // The guard's value.
1173 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
1175 // Grab the frame index.
1177 if (!X86SelectAddress(Slot, AM)) return false;
1179 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1183 case Intrinsic::objectsize: {
1184 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
1185 const Type *Ty = I.getCalledFunction()->getReturnType();
1187 assert(CI && "Non-constant type in Intrinsic::objectsize?");
1190 if (!isTypeLegal(Ty, VT))
1196 else if (VT == MVT::i64)
1201 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1202 BuildMI(MBB, DL, TII.get(OpC), ResultReg).
1203 addImm(CI->getZExtValue() == 0 ? -1ULL : 0);
1204 UpdateValueMap(&I, ResultReg);
1207 case Intrinsic::dbg_declare: {
1208 DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1210 assert(DI->getAddress() && "Null address should be checked earlier!");
1211 if (!X86SelectAddress(DI->getAddress(), AM))
1213 const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1214 // FIXME may need to add RegState::Debug to any registers produced,
1215 // although ESP/EBP should be the only ones at the moment.
1216 addFullAddress(BuildMI(MBB, DL, II), AM).addImm(0).
1217 addMetadata(DI->getVariable());
1220 case Intrinsic::trap: {
1221 BuildMI(MBB, DL, TII.get(X86::TRAP));
1224 case Intrinsic::sadd_with_overflow:
1225 case Intrinsic::uadd_with_overflow: {
1226 // Replace "add with overflow" intrinsics with an "add" instruction followed
1227 // by a seto/setc instruction. Later on, when the "extractvalue"
1228 // instructions are encountered, we use the fact that two registers were
1229 // created sequentially to get the correct registers for the "sum" and the
1231 const Function *Callee = I.getCalledFunction();
1233 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1236 if (!isTypeLegal(RetTy, VT))
1239 Value *Op1 = I.getOperand(1);
1240 Value *Op2 = I.getOperand(2);
1241 unsigned Reg1 = getRegForValue(Op1);
1242 unsigned Reg2 = getRegForValue(Op2);
1244 if (Reg1 == 0 || Reg2 == 0)
1245 // FIXME: Handle values *not* in registers.
1251 else if (VT == MVT::i64)
1256 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1257 BuildMI(MBB, DL, TII.get(OpC), ResultReg).addReg(Reg1).addReg(Reg2);
1258 unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1260 // If the add with overflow is an intra-block value then we just want to
1261 // create temporaries for it like normal. If it is a cross-block value then
1262 // UpdateValueMap will return the cross-block register used. Since we
1263 // *really* want the value to be live in the register pair known by
1264 // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1265 // the cross block case. In the non-cross-block case, we should just make
1266 // another register for the value.
1267 if (DestReg1 != ResultReg)
1268 ResultReg = DestReg1+1;
1270 ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1272 unsigned Opc = X86::SETBr;
1273 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1275 BuildMI(MBB, DL, TII.get(Opc), ResultReg);
1281 bool X86FastISel::X86SelectCall(Instruction *I) {
1282 CallInst *CI = cast<CallInst>(I);
1283 Value *Callee = I->getOperand(0);
1285 // Can't handle inline asm yet.
1286 if (isa<InlineAsm>(Callee))
1289 // Handle intrinsic calls.
1290 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1291 return X86VisitIntrinsicCall(*II);
1293 // Handle only C and fastcc calling conventions for now.
1295 CallingConv::ID CC = CS.getCallingConv();
1296 if (CC != CallingConv::C &&
1297 CC != CallingConv::Fast &&
1298 CC != CallingConv::X86_FastCall)
1301 // fastcc with -tailcallopt is intended to provide a guaranteed
1302 // tail call optimization. Fastisel doesn't know how to do that.
1303 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1306 // Let SDISel handle vararg functions.
1307 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1308 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1309 if (FTy->isVarArg())
1312 // Handle *simple* calls for now.
1313 const Type *RetTy = CS.getType();
1315 if (RetTy->isVoidTy())
1316 RetVT = MVT::isVoid;
1317 else if (!isTypeLegal(RetTy, RetVT, true))
1320 // Materialize callee address in a register. FIXME: GV address can be
1321 // handled with a CALLpcrel32 instead.
1322 X86AddressMode CalleeAM;
1323 if (!X86SelectCallAddress(Callee, CalleeAM))
1325 unsigned CalleeOp = 0;
1326 GlobalValue *GV = 0;
1327 if (CalleeAM.GV != 0) {
1329 } else if (CalleeAM.Base.Reg != 0) {
1330 CalleeOp = CalleeAM.Base.Reg;
1334 // Allow calls which produce i1 results.
1335 bool AndToI1 = false;
1336 if (RetVT == MVT::i1) {
1341 // Deal with call operands first.
1342 SmallVector<Value*, 8> ArgVals;
1343 SmallVector<unsigned, 8> Args;
1344 SmallVector<EVT, 8> ArgVTs;
1345 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1346 Args.reserve(CS.arg_size());
1347 ArgVals.reserve(CS.arg_size());
1348 ArgVTs.reserve(CS.arg_size());
1349 ArgFlags.reserve(CS.arg_size());
1350 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1352 unsigned Arg = getRegForValue(*i);
1355 ISD::ArgFlagsTy Flags;
1356 unsigned AttrInd = i - CS.arg_begin() + 1;
1357 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1359 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1362 // FIXME: Only handle *easy* calls for now.
1363 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1364 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1365 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1366 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1369 const Type *ArgTy = (*i)->getType();
1371 if (!isTypeLegal(ArgTy, ArgVT))
1373 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1374 Flags.setOrigAlign(OriginalAlignment);
1376 Args.push_back(Arg);
1377 ArgVals.push_back(*i);
1378 ArgVTs.push_back(ArgVT);
1379 ArgFlags.push_back(Flags);
1382 // Analyze operands of the call, assigning locations to each operand.
1383 SmallVector<CCValAssign, 16> ArgLocs;
1384 CCState CCInfo(CC, false, TM, ArgLocs, I->getParent()->getContext());
1385 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1387 // Get a count of how many bytes are to be pushed on the stack.
1388 unsigned NumBytes = CCInfo.getNextStackOffset();
1390 // Issue CALLSEQ_START
1391 unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1392 BuildMI(MBB, DL, TII.get(AdjStackDown)).addImm(NumBytes);
1394 // Process argument: walk the register/memloc assignments, inserting
1396 SmallVector<unsigned, 4> RegArgs;
1397 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1398 CCValAssign &VA = ArgLocs[i];
1399 unsigned Arg = Args[VA.getValNo()];
1400 EVT ArgVT = ArgVTs[VA.getValNo()];
1402 // Promote the value if needed.
1403 switch (VA.getLocInfo()) {
1404 default: llvm_unreachable("Unknown loc info!");
1405 case CCValAssign::Full: break;
1406 case CCValAssign::SExt: {
1407 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1409 assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1411 ArgVT = VA.getLocVT();
1414 case CCValAssign::ZExt: {
1415 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1417 assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1419 ArgVT = VA.getLocVT();
1422 case CCValAssign::AExt: {
1423 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1426 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1429 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1432 assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1433 ArgVT = VA.getLocVT();
1436 case CCValAssign::BCvt: {
1437 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT().getSimpleVT(),
1438 ISD::BIT_CONVERT, Arg);
1439 assert(BC != 0 && "Failed to emit a bitcast!");
1441 ArgVT = VA.getLocVT();
1446 if (VA.isRegLoc()) {
1447 TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1448 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1450 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1452 RegArgs.push_back(VA.getLocReg());
1454 unsigned LocMemOffset = VA.getLocMemOffset();
1456 AM.Base.Reg = StackPtr;
1457 AM.Disp = LocMemOffset;
1458 Value *ArgVal = ArgVals[VA.getValNo()];
1460 // If this is a really simple value, emit this with the Value* version of
1461 // X86FastEmitStore. If it isn't simple, we don't want to do this, as it
1462 // can cause us to reevaluate the argument.
1463 if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1464 X86FastEmitStore(ArgVT, ArgVal, AM);
1466 X86FastEmitStore(ArgVT, Arg, AM);
1470 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1472 if (Subtarget->isPICStyleGOT()) {
1473 TargetRegisterClass *RC = X86::GR32RegisterClass;
1474 unsigned Base = getInstrInfo()->getGlobalBaseReg(&MF);
1475 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC);
1476 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1481 MachineInstrBuilder MIB;
1483 // Register-indirect call.
1484 unsigned CallOpc = Subtarget->is64Bit() ? X86::CALL64r : X86::CALL32r;
1485 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addReg(CalleeOp);
1489 assert(GV && "Not a direct call");
1491 Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
1493 // See if we need any target-specific flags on the GV operand.
1494 unsigned char OpFlags = 0;
1496 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1497 // external symbols most go through the PLT in PIC mode. If the symbol
1498 // has hidden or protected visibility, or if it is static or local, then
1499 // we don't need to use the PLT - we can directly call it.
1500 if (Subtarget->isTargetELF() &&
1501 TM.getRelocationModel() == Reloc::PIC_ &&
1502 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1503 OpFlags = X86II::MO_PLT;
1504 } else if (Subtarget->isPICStyleStubAny() &&
1505 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1506 Subtarget->getDarwinVers() < 9) {
1507 // PC-relative references to external symbols should go through $stub,
1508 // unless we're building with the leopard linker or later, which
1509 // automatically synthesizes these stubs.
1510 OpFlags = X86II::MO_DARWIN_STUB;
1514 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addGlobalAddress(GV, 0, OpFlags);
1517 // Add an implicit use GOT pointer in EBX.
1518 if (Subtarget->isPICStyleGOT())
1519 MIB.addReg(X86::EBX);
1521 // Add implicit physical register uses to the call.
1522 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1523 MIB.addReg(RegArgs[i]);
1525 // Issue CALLSEQ_END
1526 unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1527 BuildMI(MBB, DL, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1529 // Now handle call return value (if any).
1530 if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1531 SmallVector<CCValAssign, 16> RVLocs;
1532 CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1533 CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1535 // Copy all of the result registers out of their specified physreg.
1536 assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1537 EVT CopyVT = RVLocs[0].getValVT();
1538 TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1539 TargetRegisterClass *SrcRC = DstRC;
1541 // If this is a call to a function that returns an fp value on the x87 fp
1542 // stack, but where we prefer to use the value in xmm registers, copy it
1543 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1544 if ((RVLocs[0].getLocReg() == X86::ST0 ||
1545 RVLocs[0].getLocReg() == X86::ST1) &&
1546 isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1548 SrcRC = X86::RSTRegisterClass;
1549 DstRC = X86::RFP80RegisterClass;
1552 unsigned ResultReg = createResultReg(DstRC);
1553 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1554 RVLocs[0].getLocReg(), DstRC, SrcRC);
1555 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1557 if (CopyVT != RVLocs[0].getValVT()) {
1558 // Round the F80 the right size, which also moves to the appropriate xmm
1559 // register. This is accomplished by storing the F80 value in memory and
1560 // then loading it back. Ewww...
1561 EVT ResVT = RVLocs[0].getValVT();
1562 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1563 unsigned MemSize = ResVT.getSizeInBits()/8;
1564 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1565 addFrameReference(BuildMI(MBB, DL, TII.get(Opc)), FI).addReg(ResultReg);
1566 DstRC = ResVT == MVT::f32
1567 ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1568 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1569 ResultReg = createResultReg(DstRC);
1570 addFrameReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg), FI);
1574 // Mask out all but lowest bit for some call which produces an i1.
1575 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1577 TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1578 ResultReg = AndResult;
1581 UpdateValueMap(I, ResultReg);
1589 X86FastISel::TargetSelectInstruction(Instruction *I) {
1590 switch (I->getOpcode()) {
1592 case Instruction::Load:
1593 return X86SelectLoad(I);
1594 case Instruction::Store:
1595 return X86SelectStore(I);
1596 case Instruction::ICmp:
1597 case Instruction::FCmp:
1598 return X86SelectCmp(I);
1599 case Instruction::ZExt:
1600 return X86SelectZExt(I);
1601 case Instruction::Br:
1602 return X86SelectBranch(I);
1603 case Instruction::Call:
1604 return X86SelectCall(I);
1605 case Instruction::LShr:
1606 case Instruction::AShr:
1607 case Instruction::Shl:
1608 return X86SelectShift(I);
1609 case Instruction::Select:
1610 return X86SelectSelect(I);
1611 case Instruction::Trunc:
1612 return X86SelectTrunc(I);
1613 case Instruction::FPExt:
1614 return X86SelectFPExt(I);
1615 case Instruction::FPTrunc:
1616 return X86SelectFPTrunc(I);
1617 case Instruction::ExtractValue:
1618 return X86SelectExtractValue(I);
1619 case Instruction::IntToPtr: // Deliberate fall-through.
1620 case Instruction::PtrToInt: {
1621 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1622 EVT DstVT = TLI.getValueType(I->getType());
1623 if (DstVT.bitsGT(SrcVT))
1624 return X86SelectZExt(I);
1625 if (DstVT.bitsLT(SrcVT))
1626 return X86SelectTrunc(I);
1627 unsigned Reg = getRegForValue(I->getOperand(0));
1628 if (Reg == 0) return false;
1629 UpdateValueMap(I, Reg);
1637 unsigned X86FastISel::TargetMaterializeConstant(Constant *C) {
1639 if (!isTypeLegal(C->getType(), VT))
1642 // Get opcode and regclass of the output for the given load instruction.
1644 const TargetRegisterClass *RC = NULL;
1645 switch (VT.getSimpleVT().SimpleTy) {
1646 default: return false;
1649 RC = X86::GR8RegisterClass;
1653 RC = X86::GR16RegisterClass;
1657 RC = X86::GR32RegisterClass;
1660 // Must be in x86-64 mode.
1662 RC = X86::GR64RegisterClass;
1665 if (Subtarget->hasSSE1()) {
1667 RC = X86::FR32RegisterClass;
1669 Opc = X86::LD_Fp32m;
1670 RC = X86::RFP32RegisterClass;
1674 if (Subtarget->hasSSE2()) {
1676 RC = X86::FR64RegisterClass;
1678 Opc = X86::LD_Fp64m;
1679 RC = X86::RFP64RegisterClass;
1683 // No f80 support yet.
1687 // Materialize addresses with LEA instructions.
1688 if (isa<GlobalValue>(C)) {
1690 if (X86SelectAddress(C, AM)) {
1691 if (TLI.getPointerTy() == MVT::i32)
1695 unsigned ResultReg = createResultReg(RC);
1696 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1702 // MachineConstantPool wants an explicit alignment.
1703 unsigned Align = TD.getPrefTypeAlignment(C->getType());
1705 // Alignment of vector types. FIXME!
1706 Align = TD.getTypeAllocSize(C->getType());
1709 // x86-32 PIC requires a PIC base register for constant pools.
1710 unsigned PICBase = 0;
1711 unsigned char OpFlag = 0;
1712 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1713 OpFlag = X86II::MO_PIC_BASE_OFFSET;
1714 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1715 } else if (Subtarget->isPICStyleGOT()) {
1716 OpFlag = X86II::MO_GOTOFF;
1717 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1718 } else if (Subtarget->isPICStyleRIPRel() &&
1719 TM.getCodeModel() == CodeModel::Small) {
1723 // Create the load from the constant pool.
1724 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1725 unsigned ResultReg = createResultReg(RC);
1726 addConstantPoolReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg),
1727 MCPOffset, PICBase, OpFlag);
1732 unsigned X86FastISel::TargetMaterializeAlloca(AllocaInst *C) {
1733 // Fail on dynamic allocas. At this point, getRegForValue has already
1734 // checked its CSE maps, so if we're here trying to handle a dynamic
1735 // alloca, we're not going to succeed. X86SelectAddress has a
1736 // check for dynamic allocas, because it's called directly from
1737 // various places, but TargetMaterializeAlloca also needs a check
1738 // in order to avoid recursion between getRegForValue,
1739 // X86SelectAddrss, and TargetMaterializeAlloca.
1740 if (!StaticAllocaMap.count(C))
1744 if (!X86SelectAddress(C, AM))
1746 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1747 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1748 unsigned ResultReg = createResultReg(RC);
1749 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1754 llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1755 MachineModuleInfo *mmi,
1756 DenseMap<const Value *, unsigned> &vm,
1757 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
1758 DenseMap<const AllocaInst *, int> &am
1760 , SmallSet<Instruction*, 8> &cil
1763 return new X86FastISel(mf, mmi, vm, bm, am