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"
38 class X86FastISel : public FastISel {
39 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
40 /// make the right decision when generating code for different targets.
41 const X86Subtarget *Subtarget;
43 /// StackPtr - Register used as the stack pointer.
47 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
48 /// floating point ops.
49 /// When SSE is available, use it for f32 operations.
50 /// When SSE2 is available, use it for f64 operations.
55 explicit X86FastISel(MachineFunction &mf,
56 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, dw, 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 (Subtarget->isTargetWin64())
175 return CC_X86_Win64_C;
180 if (CC == CallingConv::X86_FastCall)
181 return CC_X86_32_FastCall;
182 else if (CC == CallingConv::Fast)
183 return CC_X86_32_FastCC;
188 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
189 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
190 /// Return true and the result register by reference if it is possible.
191 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
192 unsigned &ResultReg) {
193 // Get opcode and regclass of the output for the given load instruction.
195 const TargetRegisterClass *RC = NULL;
196 switch (VT.getSimpleVT().SimpleTy) {
197 default: return false;
201 RC = X86::GR8RegisterClass;
205 RC = X86::GR16RegisterClass;
209 RC = X86::GR32RegisterClass;
212 // Must be in x86-64 mode.
214 RC = X86::GR64RegisterClass;
217 if (Subtarget->hasSSE1()) {
219 RC = X86::FR32RegisterClass;
222 RC = X86::RFP32RegisterClass;
226 if (Subtarget->hasSSE2()) {
228 RC = X86::FR64RegisterClass;
231 RC = X86::RFP64RegisterClass;
235 // No f80 support yet.
239 ResultReg = createResultReg(RC);
240 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
244 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
245 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
246 /// and a displacement offset, or a GlobalAddress,
247 /// i.e. V. Return true if it is possible.
249 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val,
250 const X86AddressMode &AM) {
251 // Get opcode and regclass of the output for the given store instruction.
253 switch (VT.getSimpleVT().SimpleTy) {
254 case MVT::f80: // No f80 support yet.
255 default: return false;
257 // Mask out all but lowest bit.
258 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
260 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
263 // FALLTHROUGH, handling i1 as i8.
264 case MVT::i8: Opc = X86::MOV8mr; break;
265 case MVT::i16: Opc = X86::MOV16mr; break;
266 case MVT::i32: Opc = X86::MOV32mr; break;
267 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
269 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
272 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
276 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM).addReg(Val);
280 bool X86FastISel::X86FastEmitStore(EVT VT, Value *Val,
281 const X86AddressMode &AM) {
282 // Handle 'null' like i32/i64 0.
283 if (isa<ConstantPointerNull>(Val))
284 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
286 // If this is a store of a simple constant, fold the constant into the store.
287 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
290 switch (VT.getSimpleVT().SimpleTy) {
292 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
293 case MVT::i8: Opc = X86::MOV8mi; break;
294 case MVT::i16: Opc = X86::MOV16mi; break;
295 case MVT::i32: Opc = X86::MOV32mi; break;
297 // Must be a 32-bit sign extended value.
298 if ((int)CI->getSExtValue() == CI->getSExtValue())
299 Opc = X86::MOV64mi32;
304 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM)
305 .addImm(Signed ? CI->getSExtValue() :
311 unsigned ValReg = getRegForValue(Val);
315 return X86FastEmitStore(VT, ValReg, AM);
318 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
319 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
320 /// ISD::SIGN_EXTEND).
321 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
322 unsigned Src, EVT SrcVT,
323 unsigned &ResultReg) {
324 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
333 /// X86SelectAddress - Attempt to fill in an address from the given value.
335 bool X86FastISel::X86SelectAddress(Value *V, X86AddressMode &AM) {
337 unsigned Opcode = Instruction::UserOp1;
338 if (Instruction *I = dyn_cast<Instruction>(V)) {
339 Opcode = I->getOpcode();
341 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
342 Opcode = C->getOpcode();
348 case Instruction::BitCast:
349 // Look past bitcasts.
350 return X86SelectAddress(U->getOperand(0), AM);
352 case Instruction::IntToPtr:
353 // Look past no-op inttoptrs.
354 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
355 return X86SelectAddress(U->getOperand(0), AM);
358 case Instruction::PtrToInt:
359 // Look past no-op ptrtoints.
360 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
361 return X86SelectAddress(U->getOperand(0), AM);
364 case Instruction::Alloca: {
365 // Do static allocas.
366 const AllocaInst *A = cast<AllocaInst>(V);
367 DenseMap<const AllocaInst*, int>::iterator SI = StaticAllocaMap.find(A);
368 if (SI != StaticAllocaMap.end()) {
369 AM.BaseType = X86AddressMode::FrameIndexBase;
370 AM.Base.FrameIndex = SI->second;
376 case Instruction::Add: {
377 // Adds of constants are common and easy enough.
378 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
379 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
380 // They have to fit in the 32-bit signed displacement field though.
382 AM.Disp = (uint32_t)Disp;
383 return X86SelectAddress(U->getOperand(0), AM);
389 case Instruction::GetElementPtr: {
390 // Pattern-match simple GEPs.
391 uint64_t Disp = (int32_t)AM.Disp;
392 unsigned IndexReg = AM.IndexReg;
393 unsigned Scale = AM.Scale;
394 gep_type_iterator GTI = gep_type_begin(U);
395 // Iterate through the indices, folding what we can. Constants can be
396 // folded, and one dynamic index can be handled, if the scale is supported.
397 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end();
398 i != e; ++i, ++GTI) {
400 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
401 const StructLayout *SL = TD.getStructLayout(STy);
402 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
403 Disp += SL->getElementOffset(Idx);
405 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
407 // Constant-offset addressing.
408 Disp += CI->getSExtValue() * S;
409 } else if (IndexReg == 0 &&
410 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
411 (S == 1 || S == 2 || S == 4 || S == 8)) {
412 // Scaled-index addressing.
414 IndexReg = getRegForGEPIndex(Op);
419 goto unsupported_gep;
422 // Check for displacement overflow.
425 // Ok, the GEP indices were covered by constant-offset and scaled-index
426 // addressing. Update the address state and move on to examining the base.
427 AM.IndexReg = IndexReg;
429 AM.Disp = (uint32_t)Disp;
430 return X86SelectAddress(U->getOperand(0), AM);
432 // Ok, the GEP indices weren't all covered.
437 // Handle constant address.
438 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
439 // Can't handle alternate code models yet.
440 if (TM.getCodeModel() != CodeModel::Small)
443 // RIP-relative addresses can't have additional register operands.
444 if (Subtarget->isPICStyleRIPRel() &&
445 (AM.Base.Reg != 0 || AM.IndexReg != 0))
448 // Can't handle TLS yet.
449 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
450 if (GVar->isThreadLocal())
453 // Okay, we've committed to selecting this global. Set up the basic address.
456 // Allow the subtarget to classify the global.
457 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
459 // If this reference is relative to the pic base, set it now.
460 if (isGlobalRelativeToPICBase(GVFlags)) {
461 // FIXME: How do we know Base.Reg is free??
462 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(&MF);
465 // Unless the ABI requires an extra load, return a direct reference to
467 if (!isGlobalStubReference(GVFlags)) {
468 if (Subtarget->isPICStyleRIPRel()) {
469 // Use rip-relative addressing if we can. Above we verified that the
470 // base and index registers are unused.
471 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
472 AM.Base.Reg = X86::RIP;
474 AM.GVOpFlags = GVFlags;
478 // Ok, we need to do a load from a stub. If we've already loaded from this
479 // stub, reuse the loaded pointer, otherwise emit the load now.
480 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
482 if (I != LocalValueMap.end() && I->second != 0) {
485 // Issue load from stub.
487 const TargetRegisterClass *RC = NULL;
488 X86AddressMode StubAM;
489 StubAM.Base.Reg = AM.Base.Reg;
491 StubAM.GVOpFlags = GVFlags;
493 if (TLI.getPointerTy() == MVT::i64) {
495 RC = X86::GR64RegisterClass;
497 if (Subtarget->isPICStyleRIPRel())
498 StubAM.Base.Reg = X86::RIP;
501 RC = X86::GR32RegisterClass;
504 LoadReg = createResultReg(RC);
505 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), LoadReg), StubAM);
507 // Prevent loading GV stub multiple times in same MBB.
508 LocalValueMap[V] = LoadReg;
511 // Now construct the final address. Note that the Disp, Scale,
512 // and Index values may already be set here.
513 AM.Base.Reg = LoadReg;
518 // If all else fails, try to materialize the value in a register.
519 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
520 if (AM.Base.Reg == 0) {
521 AM.Base.Reg = getRegForValue(V);
522 return AM.Base.Reg != 0;
524 if (AM.IndexReg == 0) {
525 assert(AM.Scale == 1 && "Scale with no index!");
526 AM.IndexReg = getRegForValue(V);
527 return AM.IndexReg != 0;
534 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
536 bool X86FastISel::X86SelectCallAddress(Value *V, X86AddressMode &AM) {
538 unsigned Opcode = Instruction::UserOp1;
539 if (Instruction *I = dyn_cast<Instruction>(V)) {
540 Opcode = I->getOpcode();
542 } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
543 Opcode = C->getOpcode();
549 case Instruction::BitCast:
550 // Look past bitcasts.
551 return X86SelectCallAddress(U->getOperand(0), AM);
553 case Instruction::IntToPtr:
554 // Look past no-op inttoptrs.
555 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
556 return X86SelectCallAddress(U->getOperand(0), AM);
559 case Instruction::PtrToInt:
560 // Look past no-op ptrtoints.
561 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
562 return X86SelectCallAddress(U->getOperand(0), AM);
566 // Handle constant address.
567 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
568 // Can't handle alternate code models yet.
569 if (TM.getCodeModel() != CodeModel::Small)
572 // RIP-relative addresses can't have additional register operands.
573 if (Subtarget->isPICStyleRIPRel() &&
574 (AM.Base.Reg != 0 || AM.IndexReg != 0))
577 // Can't handle TLS or DLLImport.
578 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
579 if (GVar->isThreadLocal() || GVar->hasDLLImportLinkage())
582 // Okay, we've committed to selecting this global. Set up the basic address.
585 // No ABI requires an extra load for anything other than DLLImport, which
586 // we rejected above. Return a direct reference to the global.
587 if (Subtarget->isPICStyleRIPRel()) {
588 // Use rip-relative addressing if we can. Above we verified that the
589 // base and index registers are unused.
590 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
591 AM.Base.Reg = X86::RIP;
592 } else if (Subtarget->isPICStyleStubPIC()) {
593 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
594 } else if (Subtarget->isPICStyleGOT()) {
595 AM.GVOpFlags = X86II::MO_GOTOFF;
601 // If all else fails, try to materialize the value in a register.
602 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
603 if (AM.Base.Reg == 0) {
604 AM.Base.Reg = getRegForValue(V);
605 return AM.Base.Reg != 0;
607 if (AM.IndexReg == 0) {
608 assert(AM.Scale == 1 && "Scale with no index!");
609 AM.IndexReg = getRegForValue(V);
610 return AM.IndexReg != 0;
618 /// X86SelectStore - Select and emit code to implement store instructions.
619 bool X86FastISel::X86SelectStore(Instruction* I) {
621 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
625 if (!X86SelectAddress(I->getOperand(1), AM))
628 return X86FastEmitStore(VT, I->getOperand(0), AM);
631 /// X86SelectLoad - Select and emit code to implement load instructions.
633 bool X86FastISel::X86SelectLoad(Instruction *I) {
635 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
639 if (!X86SelectAddress(I->getOperand(0), AM))
642 unsigned ResultReg = 0;
643 if (X86FastEmitLoad(VT, AM, ResultReg)) {
644 UpdateValueMap(I, ResultReg);
650 static unsigned X86ChooseCmpOpcode(EVT VT) {
651 switch (VT.getSimpleVT().SimpleTy) {
653 case MVT::i8: return X86::CMP8rr;
654 case MVT::i16: return X86::CMP16rr;
655 case MVT::i32: return X86::CMP32rr;
656 case MVT::i64: return X86::CMP64rr;
657 case MVT::f32: return X86::UCOMISSrr;
658 case MVT::f64: return X86::UCOMISDrr;
662 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
663 /// of the comparison, return an opcode that works for the compare (e.g.
664 /// CMP32ri) otherwise return 0.
665 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, ConstantInt *RHSC) {
666 switch (VT.getSimpleVT().SimpleTy) {
667 // Otherwise, we can't fold the immediate into this comparison.
669 case MVT::i8: return X86::CMP8ri;
670 case MVT::i16: return X86::CMP16ri;
671 case MVT::i32: return X86::CMP32ri;
673 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
675 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
676 return X86::CMP64ri32;
681 bool X86FastISel::X86FastEmitCompare(Value *Op0, Value *Op1, EVT VT) {
682 unsigned Op0Reg = getRegForValue(Op0);
683 if (Op0Reg == 0) return false;
685 // Handle 'null' like i32/i64 0.
686 if (isa<ConstantPointerNull>(Op1))
687 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
689 // We have two options: compare with register or immediate. If the RHS of
690 // the compare is an immediate that we can fold into this compare, use
691 // CMPri, otherwise use CMPrr.
692 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
693 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
694 BuildMI(MBB, DL, TII.get(CompareImmOpc)).addReg(Op0Reg)
695 .addImm(Op1C->getSExtValue());
700 unsigned CompareOpc = X86ChooseCmpOpcode(VT);
701 if (CompareOpc == 0) return false;
703 unsigned Op1Reg = getRegForValue(Op1);
704 if (Op1Reg == 0) return false;
705 BuildMI(MBB, DL, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
710 bool X86FastISel::X86SelectCmp(Instruction *I) {
711 CmpInst *CI = cast<CmpInst>(I);
714 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
717 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
719 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
720 switch (CI->getPredicate()) {
721 case CmpInst::FCMP_OEQ: {
722 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
725 unsigned EReg = createResultReg(&X86::GR8RegClass);
726 unsigned NPReg = createResultReg(&X86::GR8RegClass);
727 BuildMI(MBB, DL, TII.get(X86::SETEr), EReg);
728 BuildMI(MBB, DL, TII.get(X86::SETNPr), NPReg);
730 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
731 UpdateValueMap(I, ResultReg);
734 case CmpInst::FCMP_UNE: {
735 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
738 unsigned NEReg = createResultReg(&X86::GR8RegClass);
739 unsigned PReg = createResultReg(&X86::GR8RegClass);
740 BuildMI(MBB, DL, TII.get(X86::SETNEr), NEReg);
741 BuildMI(MBB, DL, TII.get(X86::SETPr), PReg);
742 BuildMI(MBB, DL, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
743 UpdateValueMap(I, ResultReg);
746 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
747 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
748 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
749 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
750 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
751 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
752 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
753 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
754 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
755 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
756 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
757 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
759 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
760 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
761 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
762 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
763 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
764 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
765 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
766 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
767 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
768 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
773 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
777 // Emit a compare of Op0/Op1.
778 if (!X86FastEmitCompare(Op0, Op1, VT))
781 BuildMI(MBB, DL, TII.get(SetCCOpc), ResultReg);
782 UpdateValueMap(I, ResultReg);
786 bool X86FastISel::X86SelectZExt(Instruction *I) {
787 // Handle zero-extension from i1 to i8, which is common.
788 if (I->getType()->isInteger(8) &&
789 I->getOperand(0)->getType()->isInteger(1)) {
790 unsigned ResultReg = getRegForValue(I->getOperand(0));
791 if (ResultReg == 0) return false;
792 // Set the high bits to zero.
793 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg);
794 if (ResultReg == 0) return false;
795 UpdateValueMap(I, ResultReg);
803 bool X86FastISel::X86SelectBranch(Instruction *I) {
804 // Unconditional branches are selected by tablegen-generated code.
805 // Handle a conditional branch.
806 BranchInst *BI = cast<BranchInst>(I);
807 MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
808 MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
810 // Fold the common case of a conditional branch with a comparison.
811 if (CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
812 if (CI->hasOneUse()) {
813 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
815 // Try to take advantage of fallthrough opportunities.
816 CmpInst::Predicate Predicate = CI->getPredicate();
817 if (MBB->isLayoutSuccessor(TrueMBB)) {
818 std::swap(TrueMBB, FalseMBB);
819 Predicate = CmpInst::getInversePredicate(Predicate);
822 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
823 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
826 case CmpInst::FCMP_OEQ:
827 std::swap(TrueMBB, FalseMBB);
828 Predicate = CmpInst::FCMP_UNE;
830 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE; break;
831 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA; break;
832 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE; break;
833 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA; break;
834 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE; break;
835 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE; break;
836 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP; break;
837 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP; break;
838 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE; break;
839 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB; break;
840 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE; break;
841 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB; break;
842 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
844 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE; break;
845 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE; break;
846 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA; break;
847 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE; break;
848 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB; break;
849 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
850 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG; break;
851 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE; break;
852 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL; break;
853 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE; break;
858 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
862 // Emit a compare of the LHS and RHS, setting the flags.
863 if (!X86FastEmitCompare(Op0, Op1, VT))
866 BuildMI(MBB, DL, TII.get(BranchOpc)).addMBB(TrueMBB);
868 if (Predicate == CmpInst::FCMP_UNE) {
869 // X86 requires a second branch to handle UNE (and OEQ,
870 // which is mapped to UNE above).
871 BuildMI(MBB, DL, TII.get(X86::JP)).addMBB(TrueMBB);
874 FastEmitBranch(FalseMBB);
875 MBB->addSuccessor(TrueMBB);
878 } else if (ExtractValueInst *EI =
879 dyn_cast<ExtractValueInst>(BI->getCondition())) {
880 // Check to see if the branch instruction is from an "arithmetic with
881 // overflow" intrinsic. The main way these intrinsics are used is:
883 // %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
884 // %sum = extractvalue { i32, i1 } %t, 0
885 // %obit = extractvalue { i32, i1 } %t, 1
886 // br i1 %obit, label %overflow, label %normal
888 // The %sum and %obit are converted in an ADD and a SETO/SETB before
889 // reaching the branch. Therefore, we search backwards through the MBB
890 // looking for the SETO/SETB instruction. If an instruction modifies the
891 // EFLAGS register before we reach the SETO/SETB instruction, then we can't
892 // convert the branch into a JO/JB instruction.
893 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(EI->getAggregateOperand())){
894 if (CI->getIntrinsicID() == Intrinsic::sadd_with_overflow ||
895 CI->getIntrinsicID() == Intrinsic::uadd_with_overflow) {
896 const MachineInstr *SetMI = 0;
897 unsigned Reg = lookUpRegForValue(EI);
899 for (MachineBasicBlock::const_reverse_iterator
900 RI = MBB->rbegin(), RE = MBB->rend(); RI != RE; ++RI) {
901 const MachineInstr &MI = *RI;
903 if (MI.modifiesRegister(Reg)) {
904 unsigned Src, Dst, SrcSR, DstSR;
906 if (getInstrInfo()->isMoveInstr(MI, Src, Dst, SrcSR, DstSR)) {
915 const TargetInstrDesc &TID = MI.getDesc();
916 if (TID.hasUnmodeledSideEffects() ||
917 TID.hasImplicitDefOfPhysReg(X86::EFLAGS))
922 unsigned OpCode = SetMI->getOpcode();
924 if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
925 BuildMI(MBB, DL, TII.get(OpCode == X86::SETOr ? X86::JO : X86::JB))
927 FastEmitBranch(FalseMBB);
928 MBB->addSuccessor(TrueMBB);
936 // Otherwise do a clumsy setcc and re-test it.
937 unsigned OpReg = getRegForValue(BI->getCondition());
938 if (OpReg == 0) return false;
940 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
941 BuildMI(MBB, DL, TII.get(X86::JNE)).addMBB(TrueMBB);
942 FastEmitBranch(FalseMBB);
943 MBB->addSuccessor(TrueMBB);
947 bool X86FastISel::X86SelectShift(Instruction *I) {
948 unsigned CReg = 0, OpReg = 0, OpImm = 0;
949 const TargetRegisterClass *RC = NULL;
950 if (I->getType()->isInteger(8)) {
952 RC = &X86::GR8RegClass;
953 switch (I->getOpcode()) {
954 case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
955 case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
956 case Instruction::Shl: OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
957 default: return false;
959 } else if (I->getType()->isInteger(16)) {
961 RC = &X86::GR16RegClass;
962 switch (I->getOpcode()) {
963 case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
964 case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
965 case Instruction::Shl: OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
966 default: return false;
968 } else if (I->getType()->isInteger(32)) {
970 RC = &X86::GR32RegClass;
971 switch (I->getOpcode()) {
972 case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
973 case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
974 case Instruction::Shl: OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
975 default: return false;
977 } else if (I->getType()->isInteger(64)) {
979 RC = &X86::GR64RegClass;
980 switch (I->getOpcode()) {
981 case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
982 case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
983 case Instruction::Shl: OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
984 default: return false;
990 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
991 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
994 unsigned Op0Reg = getRegForValue(I->getOperand(0));
995 if (Op0Reg == 0) return false;
997 // Fold immediate in shl(x,3).
998 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
999 unsigned ResultReg = createResultReg(RC);
1000 BuildMI(MBB, DL, TII.get(OpImm),
1001 ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
1002 UpdateValueMap(I, ResultReg);
1006 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1007 if (Op1Reg == 0) return false;
1008 TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
1010 // The shift instruction uses X86::CL. If we defined a super-register
1011 // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
1012 // we're doing here.
1013 if (CReg != X86::CL)
1014 BuildMI(MBB, DL, TII.get(TargetInstrInfo::EXTRACT_SUBREG), X86::CL)
1015 .addReg(CReg).addImm(X86::SUBREG_8BIT);
1017 unsigned ResultReg = createResultReg(RC);
1018 BuildMI(MBB, DL, TII.get(OpReg), ResultReg).addReg(Op0Reg);
1019 UpdateValueMap(I, ResultReg);
1023 bool X86FastISel::X86SelectSelect(Instruction *I) {
1024 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1025 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1029 const TargetRegisterClass *RC = NULL;
1030 if (VT.getSimpleVT() == MVT::i16) {
1031 Opc = X86::CMOVE16rr;
1032 RC = &X86::GR16RegClass;
1033 } else if (VT.getSimpleVT() == MVT::i32) {
1034 Opc = X86::CMOVE32rr;
1035 RC = &X86::GR32RegClass;
1036 } else if (VT.getSimpleVT() == MVT::i64) {
1037 Opc = X86::CMOVE64rr;
1038 RC = &X86::GR64RegClass;
1043 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1044 if (Op0Reg == 0) return false;
1045 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1046 if (Op1Reg == 0) return false;
1047 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1048 if (Op2Reg == 0) return false;
1050 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
1051 unsigned ResultReg = createResultReg(RC);
1052 BuildMI(MBB, DL, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
1053 UpdateValueMap(I, ResultReg);
1057 bool X86FastISel::X86SelectFPExt(Instruction *I) {
1058 // fpext from float to double.
1059 if (Subtarget->hasSSE2() &&
1060 I->getType()->isDoubleTy()) {
1061 Value *V = I->getOperand(0);
1062 if (V->getType()->isFloatTy()) {
1063 unsigned OpReg = getRegForValue(V);
1064 if (OpReg == 0) return false;
1065 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1066 BuildMI(MBB, DL, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
1067 UpdateValueMap(I, ResultReg);
1075 bool X86FastISel::X86SelectFPTrunc(Instruction *I) {
1076 if (Subtarget->hasSSE2()) {
1077 if (I->getType()->isFloatTy()) {
1078 Value *V = I->getOperand(0);
1079 if (V->getType()->isDoubleTy()) {
1080 unsigned OpReg = getRegForValue(V);
1081 if (OpReg == 0) return false;
1082 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1083 BuildMI(MBB, DL, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
1084 UpdateValueMap(I, ResultReg);
1093 bool X86FastISel::X86SelectTrunc(Instruction *I) {
1094 if (Subtarget->is64Bit())
1095 // All other cases should be handled by the tblgen generated code.
1097 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1098 EVT DstVT = TLI.getValueType(I->getType());
1100 // This code only handles truncation to byte right now.
1101 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1102 // All other cases should be handled by the tblgen generated code.
1104 if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1105 // All other cases should be handled by the tblgen generated code.
1108 unsigned InputReg = getRegForValue(I->getOperand(0));
1110 // Unhandled operand. Halt "fast" selection and bail.
1113 // First issue a copy to GR16_ABCD or GR32_ABCD.
1114 unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16rr : X86::MOV32rr;
1115 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1116 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1117 unsigned CopyReg = createResultReg(CopyRC);
1118 BuildMI(MBB, DL, TII.get(CopyOpc), CopyReg).addReg(InputReg);
1120 // Then issue an extract_subreg.
1121 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1122 CopyReg, X86::SUBREG_8BIT);
1126 UpdateValueMap(I, ResultReg);
1130 bool X86FastISel::X86SelectExtractValue(Instruction *I) {
1131 ExtractValueInst *EI = cast<ExtractValueInst>(I);
1132 Value *Agg = EI->getAggregateOperand();
1134 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1135 switch (CI->getIntrinsicID()) {
1137 case Intrinsic::sadd_with_overflow:
1138 case Intrinsic::uadd_with_overflow:
1139 // Cheat a little. We know that the registers for "add" and "seto" are
1140 // allocated sequentially. However, we only keep track of the register
1141 // for "add" in the value map. Use extractvalue's index to get the
1142 // correct register for "seto".
1143 UpdateValueMap(I, lookUpRegForValue(Agg) + *EI->idx_begin());
1151 bool X86FastISel::X86VisitIntrinsicCall(IntrinsicInst &I) {
1152 // FIXME: Handle more intrinsics.
1153 switch (I.getIntrinsicID()) {
1154 default: return false;
1155 case Intrinsic::dbg_declare: {
1156 DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1158 if (!X86SelectAddress(DI->getAddress(), AM))
1160 const TargetInstrDesc &II = TII.get(TargetInstrInfo::DEBUG_VALUE);
1161 addFullAddress(BuildMI(MBB, DL, II), AM).addImm(0).
1162 addMetadata(DI->getVariable());
1165 case Intrinsic::trap: {
1166 BuildMI(MBB, DL, TII.get(X86::TRAP));
1169 case Intrinsic::sadd_with_overflow:
1170 case Intrinsic::uadd_with_overflow: {
1171 // Replace "add with overflow" intrinsics with an "add" instruction followed
1172 // by a seto/setc instruction. Later on, when the "extractvalue"
1173 // instructions are encountered, we use the fact that two registers were
1174 // created sequentially to get the correct registers for the "sum" and the
1176 const Function *Callee = I.getCalledFunction();
1178 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1181 if (!isTypeLegal(RetTy, VT))
1184 Value *Op1 = I.getOperand(1);
1185 Value *Op2 = I.getOperand(2);
1186 unsigned Reg1 = getRegForValue(Op1);
1187 unsigned Reg2 = getRegForValue(Op2);
1189 if (Reg1 == 0 || Reg2 == 0)
1190 // FIXME: Handle values *not* in registers.
1196 else if (VT == MVT::i64)
1201 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1202 BuildMI(MBB, DL, TII.get(OpC), ResultReg).addReg(Reg1).addReg(Reg2);
1203 unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1205 // If the add with overflow is an intra-block value then we just want to
1206 // create temporaries for it like normal. If it is a cross-block value then
1207 // UpdateValueMap will return the cross-block register used. Since we
1208 // *really* want the value to be live in the register pair known by
1209 // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1210 // the cross block case. In the non-cross-block case, we should just make
1211 // another register for the value.
1212 if (DestReg1 != ResultReg)
1213 ResultReg = DestReg1+1;
1215 ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1217 unsigned Opc = X86::SETBr;
1218 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1220 BuildMI(MBB, DL, TII.get(Opc), ResultReg);
1226 bool X86FastISel::X86SelectCall(Instruction *I) {
1227 CallInst *CI = cast<CallInst>(I);
1228 Value *Callee = I->getOperand(0);
1230 // Can't handle inline asm yet.
1231 if (isa<InlineAsm>(Callee))
1234 // Handle intrinsic calls.
1235 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1236 return X86VisitIntrinsicCall(*II);
1238 // Handle only C and fastcc calling conventions for now.
1240 CallingConv::ID CC = CS.getCallingConv();
1241 if (CC != CallingConv::C &&
1242 CC != CallingConv::Fast &&
1243 CC != CallingConv::X86_FastCall)
1246 // Let SDISel handle vararg functions.
1247 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1248 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1249 if (FTy->isVarArg())
1252 // Handle *simple* calls for now.
1253 const Type *RetTy = CS.getType();
1255 if (RetTy->isVoidTy())
1256 RetVT = MVT::isVoid;
1257 else if (!isTypeLegal(RetTy, RetVT, true))
1260 // Materialize callee address in a register. FIXME: GV address can be
1261 // handled with a CALLpcrel32 instead.
1262 X86AddressMode CalleeAM;
1263 if (!X86SelectCallAddress(Callee, CalleeAM))
1265 unsigned CalleeOp = 0;
1266 GlobalValue *GV = 0;
1267 if (CalleeAM.GV != 0) {
1269 } else if (CalleeAM.Base.Reg != 0) {
1270 CalleeOp = CalleeAM.Base.Reg;
1274 // Allow calls which produce i1 results.
1275 bool AndToI1 = false;
1276 if (RetVT == MVT::i1) {
1281 // Deal with call operands first.
1282 SmallVector<Value*, 8> ArgVals;
1283 SmallVector<unsigned, 8> Args;
1284 SmallVector<EVT, 8> ArgVTs;
1285 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1286 Args.reserve(CS.arg_size());
1287 ArgVals.reserve(CS.arg_size());
1288 ArgVTs.reserve(CS.arg_size());
1289 ArgFlags.reserve(CS.arg_size());
1290 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1292 unsigned Arg = getRegForValue(*i);
1295 ISD::ArgFlagsTy Flags;
1296 unsigned AttrInd = i - CS.arg_begin() + 1;
1297 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1299 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1302 // FIXME: Only handle *easy* calls for now.
1303 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1304 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1305 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1306 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1309 const Type *ArgTy = (*i)->getType();
1311 if (!isTypeLegal(ArgTy, ArgVT))
1313 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1314 Flags.setOrigAlign(OriginalAlignment);
1316 Args.push_back(Arg);
1317 ArgVals.push_back(*i);
1318 ArgVTs.push_back(ArgVT);
1319 ArgFlags.push_back(Flags);
1322 // Analyze operands of the call, assigning locations to each operand.
1323 SmallVector<CCValAssign, 16> ArgLocs;
1324 CCState CCInfo(CC, false, TM, ArgLocs, I->getParent()->getContext());
1325 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1327 // Get a count of how many bytes are to be pushed on the stack.
1328 unsigned NumBytes = CCInfo.getNextStackOffset();
1330 // Issue CALLSEQ_START
1331 unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1332 BuildMI(MBB, DL, TII.get(AdjStackDown)).addImm(NumBytes);
1334 // Process argument: walk the register/memloc assignments, inserting
1336 SmallVector<unsigned, 4> RegArgs;
1337 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1338 CCValAssign &VA = ArgLocs[i];
1339 unsigned Arg = Args[VA.getValNo()];
1340 EVT ArgVT = ArgVTs[VA.getValNo()];
1342 // Promote the value if needed.
1343 switch (VA.getLocInfo()) {
1344 default: llvm_unreachable("Unknown loc info!");
1345 case CCValAssign::Full: break;
1346 case CCValAssign::SExt: {
1347 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1349 assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1351 ArgVT = VA.getLocVT();
1354 case CCValAssign::ZExt: {
1355 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1357 assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1359 ArgVT = VA.getLocVT();
1362 case CCValAssign::AExt: {
1363 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1366 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1369 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1372 assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1373 ArgVT = VA.getLocVT();
1376 case CCValAssign::BCvt: {
1377 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT().getSimpleVT(),
1378 ISD::BIT_CONVERT, Arg);
1379 assert(BC != 0 && "Failed to emit a bitcast!");
1381 ArgVT = VA.getLocVT();
1386 if (VA.isRegLoc()) {
1387 TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1388 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1390 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1392 RegArgs.push_back(VA.getLocReg());
1394 unsigned LocMemOffset = VA.getLocMemOffset();
1396 AM.Base.Reg = StackPtr;
1397 AM.Disp = LocMemOffset;
1398 Value *ArgVal = ArgVals[VA.getValNo()];
1400 // If this is a really simple value, emit this with the Value* version of
1401 // X86FastEmitStore. If it isn't simple, we don't want to do this, as it
1402 // can cause us to reevaluate the argument.
1403 if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1404 X86FastEmitStore(ArgVT, ArgVal, AM);
1406 X86FastEmitStore(ArgVT, Arg, AM);
1410 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1412 if (Subtarget->isPICStyleGOT()) {
1413 TargetRegisterClass *RC = X86::GR32RegisterClass;
1414 unsigned Base = getInstrInfo()->getGlobalBaseReg(&MF);
1415 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC);
1416 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1421 MachineInstrBuilder MIB;
1423 // Register-indirect call.
1424 unsigned CallOpc = Subtarget->is64Bit() ? X86::CALL64r : X86::CALL32r;
1425 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addReg(CalleeOp);
1429 assert(GV && "Not a direct call");
1431 Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
1433 // See if we need any target-specific flags on the GV operand.
1434 unsigned char OpFlags = 0;
1436 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1437 // external symbols most go through the PLT in PIC mode. If the symbol
1438 // has hidden or protected visibility, or if it is static or local, then
1439 // we don't need to use the PLT - we can directly call it.
1440 if (Subtarget->isTargetELF() &&
1441 TM.getRelocationModel() == Reloc::PIC_ &&
1442 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1443 OpFlags = X86II::MO_PLT;
1444 } else if (Subtarget->isPICStyleStubAny() &&
1445 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1446 Subtarget->getDarwinVers() < 9) {
1447 // PC-relative references to external symbols should go through $stub,
1448 // unless we're building with the leopard linker or later, which
1449 // automatically synthesizes these stubs.
1450 OpFlags = X86II::MO_DARWIN_STUB;
1454 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addGlobalAddress(GV, 0, OpFlags);
1457 // Add an implicit use GOT pointer in EBX.
1458 if (Subtarget->isPICStyleGOT())
1459 MIB.addReg(X86::EBX);
1461 // Add implicit physical register uses to the call.
1462 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1463 MIB.addReg(RegArgs[i]);
1465 // Issue CALLSEQ_END
1466 unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1467 BuildMI(MBB, DL, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1469 // Now handle call return value (if any).
1470 if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1471 SmallVector<CCValAssign, 16> RVLocs;
1472 CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1473 CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1475 // Copy all of the result registers out of their specified physreg.
1476 assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1477 EVT CopyVT = RVLocs[0].getValVT();
1478 TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1479 TargetRegisterClass *SrcRC = DstRC;
1481 // If this is a call to a function that returns an fp value on the x87 fp
1482 // stack, but where we prefer to use the value in xmm registers, copy it
1483 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1484 if ((RVLocs[0].getLocReg() == X86::ST0 ||
1485 RVLocs[0].getLocReg() == X86::ST1) &&
1486 isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1488 SrcRC = X86::RSTRegisterClass;
1489 DstRC = X86::RFP80RegisterClass;
1492 unsigned ResultReg = createResultReg(DstRC);
1493 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1494 RVLocs[0].getLocReg(), DstRC, SrcRC);
1495 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1497 if (CopyVT != RVLocs[0].getValVT()) {
1498 // Round the F80 the right size, which also moves to the appropriate xmm
1499 // register. This is accomplished by storing the F80 value in memory and
1500 // then loading it back. Ewww...
1501 EVT ResVT = RVLocs[0].getValVT();
1502 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1503 unsigned MemSize = ResVT.getSizeInBits()/8;
1504 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1505 addFrameReference(BuildMI(MBB, DL, TII.get(Opc)), FI).addReg(ResultReg);
1506 DstRC = ResVT == MVT::f32
1507 ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1508 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1509 ResultReg = createResultReg(DstRC);
1510 addFrameReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg), FI);
1514 // Mask out all but lowest bit for some call which produces an i1.
1515 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1517 TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1518 ResultReg = AndResult;
1521 UpdateValueMap(I, ResultReg);
1529 X86FastISel::TargetSelectInstruction(Instruction *I) {
1530 switch (I->getOpcode()) {
1532 case Instruction::Load:
1533 return X86SelectLoad(I);
1534 case Instruction::Store:
1535 return X86SelectStore(I);
1536 case Instruction::ICmp:
1537 case Instruction::FCmp:
1538 return X86SelectCmp(I);
1539 case Instruction::ZExt:
1540 return X86SelectZExt(I);
1541 case Instruction::Br:
1542 return X86SelectBranch(I);
1543 case Instruction::Call:
1544 return X86SelectCall(I);
1545 case Instruction::LShr:
1546 case Instruction::AShr:
1547 case Instruction::Shl:
1548 return X86SelectShift(I);
1549 case Instruction::Select:
1550 return X86SelectSelect(I);
1551 case Instruction::Trunc:
1552 return X86SelectTrunc(I);
1553 case Instruction::FPExt:
1554 return X86SelectFPExt(I);
1555 case Instruction::FPTrunc:
1556 return X86SelectFPTrunc(I);
1557 case Instruction::ExtractValue:
1558 return X86SelectExtractValue(I);
1559 case Instruction::IntToPtr: // Deliberate fall-through.
1560 case Instruction::PtrToInt: {
1561 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1562 EVT DstVT = TLI.getValueType(I->getType());
1563 if (DstVT.bitsGT(SrcVT))
1564 return X86SelectZExt(I);
1565 if (DstVT.bitsLT(SrcVT))
1566 return X86SelectTrunc(I);
1567 unsigned Reg = getRegForValue(I->getOperand(0));
1568 if (Reg == 0) return false;
1569 UpdateValueMap(I, Reg);
1577 unsigned X86FastISel::TargetMaterializeConstant(Constant *C) {
1579 if (!isTypeLegal(C->getType(), VT))
1582 // Get opcode and regclass of the output for the given load instruction.
1584 const TargetRegisterClass *RC = NULL;
1585 switch (VT.getSimpleVT().SimpleTy) {
1586 default: return false;
1589 RC = X86::GR8RegisterClass;
1593 RC = X86::GR16RegisterClass;
1597 RC = X86::GR32RegisterClass;
1600 // Must be in x86-64 mode.
1602 RC = X86::GR64RegisterClass;
1605 if (Subtarget->hasSSE1()) {
1607 RC = X86::FR32RegisterClass;
1609 Opc = X86::LD_Fp32m;
1610 RC = X86::RFP32RegisterClass;
1614 if (Subtarget->hasSSE2()) {
1616 RC = X86::FR64RegisterClass;
1618 Opc = X86::LD_Fp64m;
1619 RC = X86::RFP64RegisterClass;
1623 // No f80 support yet.
1627 // Materialize addresses with LEA instructions.
1628 if (isa<GlobalValue>(C)) {
1630 if (X86SelectAddress(C, AM)) {
1631 if (TLI.getPointerTy() == MVT::i32)
1635 unsigned ResultReg = createResultReg(RC);
1636 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1642 // MachineConstantPool wants an explicit alignment.
1643 unsigned Align = TD.getPrefTypeAlignment(C->getType());
1645 // Alignment of vector types. FIXME!
1646 Align = TD.getTypeAllocSize(C->getType());
1649 // x86-32 PIC requires a PIC base register for constant pools.
1650 unsigned PICBase = 0;
1651 unsigned char OpFlag = 0;
1652 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1653 OpFlag = X86II::MO_PIC_BASE_OFFSET;
1654 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1655 } else if (Subtarget->isPICStyleGOT()) {
1656 OpFlag = X86II::MO_GOTOFF;
1657 PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1658 } else if (Subtarget->isPICStyleRIPRel() &&
1659 TM.getCodeModel() == CodeModel::Small) {
1663 // Create the load from the constant pool.
1664 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1665 unsigned ResultReg = createResultReg(RC);
1666 addConstantPoolReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg),
1667 MCPOffset, PICBase, OpFlag);
1672 unsigned X86FastISel::TargetMaterializeAlloca(AllocaInst *C) {
1673 // Fail on dynamic allocas. At this point, getRegForValue has already
1674 // checked its CSE maps, so if we're here trying to handle a dynamic
1675 // alloca, we're not going to succeed. X86SelectAddress has a
1676 // check for dynamic allocas, because it's called directly from
1677 // various places, but TargetMaterializeAlloca also needs a check
1678 // in order to avoid recursion between getRegForValue,
1679 // X86SelectAddrss, and TargetMaterializeAlloca.
1680 if (!StaticAllocaMap.count(C))
1684 if (!X86SelectAddress(C, AM))
1686 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1687 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1688 unsigned ResultReg = createResultReg(RC);
1689 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1694 llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1695 MachineModuleInfo *mmi,
1697 DenseMap<const Value *, unsigned> &vm,
1698 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
1699 DenseMap<const AllocaInst *, int> &am
1701 , SmallSet<Instruction*, 8> &cil
1704 return new X86FastISel(mf, mmi, dw, vm, bm, am