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 "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.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(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo) {
57 Subtarget = &TM.getSubtarget<X86Subtarget>();
58 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 X86ScalarSSEf64 = Subtarget->hasSSE2();
60 X86ScalarSSEf32 = Subtarget->hasSSE1();
63 virtual bool TargetSelectInstruction(const Instruction *I);
65 #include "X86GenFastISel.inc"
68 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
70 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
72 bool X86FastEmitStore(EVT VT, const Value *Val,
73 const X86AddressMode &AM);
74 bool X86FastEmitStore(EVT VT, unsigned Val,
75 const X86AddressMode &AM);
77 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
80 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
81 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
83 bool X86SelectLoad(const Instruction *I);
85 bool X86SelectStore(const Instruction *I);
87 bool X86SelectCmp(const Instruction *I);
89 bool X86SelectZExt(const Instruction *I);
91 bool X86SelectBranch(const Instruction *I);
93 bool X86SelectShift(const Instruction *I);
95 bool X86SelectSelect(const Instruction *I);
97 bool X86SelectTrunc(const Instruction *I);
99 bool X86SelectFPExt(const Instruction *I);
100 bool X86SelectFPTrunc(const Instruction *I);
102 bool X86SelectExtractValue(const Instruction *I);
104 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
105 bool X86SelectCall(const Instruction *I);
107 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool isTailCall = false);
109 const X86InstrInfo *getInstrInfo() const {
110 return getTargetMachine()->getInstrInfo();
112 const X86TargetMachine *getTargetMachine() const {
113 return static_cast<const X86TargetMachine *>(&TM);
116 unsigned TargetMaterializeConstant(const Constant *C);
118 unsigned TargetMaterializeAlloca(const AllocaInst *C);
120 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
121 /// computed in an SSE register, not on the X87 floating point stack.
122 bool isScalarFPTypeInSSEReg(EVT VT) const {
123 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
124 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
127 bool isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1 = false);
130 } // end anonymous namespace.
132 bool X86FastISel::isTypeLegal(const Type *Ty, EVT &VT, bool AllowI1) {
133 VT = TLI.getValueType(Ty, /*HandleUnknown=*/true);
134 if (VT == MVT::Other || !VT.isSimple())
135 // Unhandled type. Halt "fast" selection and bail.
138 // For now, require SSE/SSE2 for performing floating-point operations,
139 // since x87 requires additional work.
140 if (VT == MVT::f64 && !X86ScalarSSEf64)
142 if (VT == MVT::f32 && !X86ScalarSSEf32)
144 // Similarly, no f80 support yet.
147 // We only handle legal types. For example, on x86-32 the instruction
148 // selector contains all of the 64-bit instructions from x86-64,
149 // under the assumption that i64 won't be used if the target doesn't
151 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
154 #include "X86GenCallingConv.inc"
156 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
158 CCAssignFn *X86FastISel::CCAssignFnForCall(CallingConv::ID CC,
160 if (Subtarget->is64Bit()) {
161 if (CC == CallingConv::GHC)
162 return CC_X86_64_GHC;
163 else if (Subtarget->isTargetWin64())
164 return CC_X86_Win64_C;
169 if (CC == CallingConv::X86_FastCall)
170 return CC_X86_32_FastCall;
171 else if (CC == CallingConv::X86_ThisCall)
172 return CC_X86_32_ThisCall;
173 else if (CC == CallingConv::Fast)
174 return CC_X86_32_FastCC;
175 else if (CC == CallingConv::GHC)
176 return CC_X86_32_GHC;
181 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
182 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
183 /// Return true and the result register by reference if it is possible.
184 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
185 unsigned &ResultReg) {
186 // Get opcode and regclass of the output for the given load instruction.
188 const TargetRegisterClass *RC = NULL;
189 switch (VT.getSimpleVT().SimpleTy) {
190 default: return false;
194 RC = X86::GR8RegisterClass;
198 RC = X86::GR16RegisterClass;
202 RC = X86::GR32RegisterClass;
205 // Must be in x86-64 mode.
207 RC = X86::GR64RegisterClass;
210 if (Subtarget->hasSSE1()) {
212 RC = X86::FR32RegisterClass;
215 RC = X86::RFP32RegisterClass;
219 if (Subtarget->hasSSE2()) {
221 RC = X86::FR64RegisterClass;
224 RC = X86::RFP64RegisterClass;
228 // No f80 support yet.
232 ResultReg = createResultReg(RC);
233 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
237 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
238 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
239 /// and a displacement offset, or a GlobalAddress,
240 /// i.e. V. Return true if it is possible.
242 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val,
243 const X86AddressMode &AM) {
244 // Get opcode and regclass of the output for the given store instruction.
246 switch (VT.getSimpleVT().SimpleTy) {
247 case MVT::f80: // No f80 support yet.
248 default: return false;
250 // Mask out all but lowest bit.
251 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
253 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
256 // FALLTHROUGH, handling i1 as i8.
257 case MVT::i8: Opc = X86::MOV8mr; break;
258 case MVT::i16: Opc = X86::MOV16mr; break;
259 case MVT::i32: Opc = X86::MOV32mr; break;
260 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
262 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
265 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
269 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM).addReg(Val);
273 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
274 const X86AddressMode &AM) {
275 // Handle 'null' like i32/i64 0.
276 if (isa<ConstantPointerNull>(Val))
277 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
279 // If this is a store of a simple constant, fold the constant into the store.
280 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
283 switch (VT.getSimpleVT().SimpleTy) {
285 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
286 case MVT::i8: Opc = X86::MOV8mi; break;
287 case MVT::i16: Opc = X86::MOV16mi; break;
288 case MVT::i32: Opc = X86::MOV32mi; break;
290 // Must be a 32-bit sign extended value.
291 if ((int)CI->getSExtValue() == CI->getSExtValue())
292 Opc = X86::MOV64mi32;
297 addFullAddress(BuildMI(MBB, DL, TII.get(Opc)), AM)
298 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
304 unsigned ValReg = getRegForValue(Val);
308 return X86FastEmitStore(VT, ValReg, AM);
311 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
312 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
313 /// ISD::SIGN_EXTEND).
314 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
315 unsigned Src, EVT SrcVT,
316 unsigned &ResultReg) {
317 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
318 Src, /*TODO: Kill=*/false);
327 /// X86SelectAddress - Attempt to fill in an address from the given value.
329 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
330 const User *U = NULL;
331 unsigned Opcode = Instruction::UserOp1;
332 if (const Instruction *I = dyn_cast<Instruction>(V)) {
333 // Don't walk into other basic blocks; it's possible we haven't
334 // visited them yet, so the instructions may not yet be assigned
335 // virtual registers.
336 if (FuncInfo.MBBMap[I->getParent()] != MBB)
339 Opcode = I->getOpcode();
341 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
342 Opcode = C->getOpcode();
346 if (const PointerType *Ty = dyn_cast<PointerType>(V->getType()))
347 if (Ty->getAddressSpace() > 255)
348 // Fast instruction selection doesn't support the special
354 case Instruction::BitCast:
355 // Look past bitcasts.
356 return X86SelectAddress(U->getOperand(0), AM);
358 case Instruction::IntToPtr:
359 // Look past no-op inttoptrs.
360 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
361 return X86SelectAddress(U->getOperand(0), AM);
364 case Instruction::PtrToInt:
365 // Look past no-op ptrtoints.
366 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
367 return X86SelectAddress(U->getOperand(0), AM);
370 case Instruction::Alloca: {
371 // Do static allocas.
372 const AllocaInst *A = cast<AllocaInst>(V);
373 DenseMap<const AllocaInst*, int>::iterator SI =
374 FuncInfo.StaticAllocaMap.find(A);
375 if (SI != FuncInfo.StaticAllocaMap.end()) {
376 AM.BaseType = X86AddressMode::FrameIndexBase;
377 AM.Base.FrameIndex = SI->second;
383 case Instruction::Add: {
384 // Adds of constants are common and easy enough.
385 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
386 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
387 // They have to fit in the 32-bit signed displacement field though.
388 if (isInt<32>(Disp)) {
389 AM.Disp = (uint32_t)Disp;
390 return X86SelectAddress(U->getOperand(0), AM);
396 case Instruction::GetElementPtr: {
397 X86AddressMode SavedAM = AM;
399 // Pattern-match simple GEPs.
400 uint64_t Disp = (int32_t)AM.Disp;
401 unsigned IndexReg = AM.IndexReg;
402 unsigned Scale = AM.Scale;
403 gep_type_iterator GTI = gep_type_begin(U);
404 // Iterate through the indices, folding what we can. Constants can be
405 // folded, and one dynamic index can be handled, if the scale is supported.
406 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
407 i != e; ++i, ++GTI) {
408 const Value *Op = *i;
409 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
410 const StructLayout *SL = TD.getStructLayout(STy);
411 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
412 Disp += SL->getElementOffset(Idx);
414 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
415 SmallVector<const Value *, 4> Worklist;
416 Worklist.push_back(Op);
418 Op = Worklist.pop_back_val();
419 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
420 // Constant-offset addressing.
421 Disp += CI->getSExtValue() * S;
422 } else if (isa<AddOperator>(Op) &&
423 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
424 // An add with a constant operand. Fold the constant.
426 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
427 Disp += CI->getSExtValue() * S;
428 // Add the other operand back to the work list.
429 Worklist.push_back(cast<AddOperator>(Op)->getOperand(0));
430 } else if (IndexReg == 0 &&
431 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
432 (S == 1 || S == 2 || S == 4 || S == 8)) {
433 // Scaled-index addressing.
435 IndexReg = getRegForGEPIndex(Op).first;
440 goto unsupported_gep;
441 } while (!Worklist.empty());
444 // Check for displacement overflow.
445 if (!isInt<32>(Disp))
447 // Ok, the GEP indices were covered by constant-offset and scaled-index
448 // addressing. Update the address state and move on to examining the base.
449 AM.IndexReg = IndexReg;
451 AM.Disp = (uint32_t)Disp;
452 if (X86SelectAddress(U->getOperand(0), AM))
455 // If we couldn't merge the sub value into this addr mode, revert back to
456 // our address and just match the value instead of completely failing.
460 // Ok, the GEP indices weren't all covered.
465 // Handle constant address.
466 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
467 // Can't handle alternate code models yet.
468 if (TM.getCodeModel() != CodeModel::Small)
471 // RIP-relative addresses can't have additional register operands.
472 if (Subtarget->isPICStyleRIPRel() &&
473 (AM.Base.Reg != 0 || AM.IndexReg != 0))
476 // Can't handle TLS yet.
477 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
478 if (GVar->isThreadLocal())
481 // Okay, we've committed to selecting this global. Set up the basic address.
484 // Allow the subtarget to classify the global.
485 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
487 // If this reference is relative to the pic base, set it now.
488 if (isGlobalRelativeToPICBase(GVFlags)) {
489 // FIXME: How do we know Base.Reg is free??
490 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
493 // Unless the ABI requires an extra load, return a direct reference to
495 if (!isGlobalStubReference(GVFlags)) {
496 if (Subtarget->isPICStyleRIPRel()) {
497 // Use rip-relative addressing if we can. Above we verified that the
498 // base and index registers are unused.
499 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
500 AM.Base.Reg = X86::RIP;
502 AM.GVOpFlags = GVFlags;
506 // Ok, we need to do a load from a stub. If we've already loaded from this
507 // stub, reuse the loaded pointer, otherwise emit the load now.
508 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
510 if (I != LocalValueMap.end() && I->second != 0) {
513 // Issue load from stub.
515 const TargetRegisterClass *RC = NULL;
516 X86AddressMode StubAM;
517 StubAM.Base.Reg = AM.Base.Reg;
519 StubAM.GVOpFlags = GVFlags;
521 if (TLI.getPointerTy() == MVT::i64) {
523 RC = X86::GR64RegisterClass;
525 if (Subtarget->isPICStyleRIPRel())
526 StubAM.Base.Reg = X86::RIP;
529 RC = X86::GR32RegisterClass;
532 LoadReg = createResultReg(RC);
533 addFullAddress(BuildMI(MBB, DL, TII.get(Opc), LoadReg), StubAM);
535 // Prevent loading GV stub multiple times in same MBB.
536 LocalValueMap[V] = LoadReg;
539 // Now construct the final address. Note that the Disp, Scale,
540 // and Index values may already be set here.
541 AM.Base.Reg = LoadReg;
546 // If all else fails, try to materialize the value in a register.
547 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
548 if (AM.Base.Reg == 0) {
549 AM.Base.Reg = getRegForValue(V);
550 return AM.Base.Reg != 0;
552 if (AM.IndexReg == 0) {
553 assert(AM.Scale == 1 && "Scale with no index!");
554 AM.IndexReg = getRegForValue(V);
555 return AM.IndexReg != 0;
562 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
564 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
565 const User *U = NULL;
566 unsigned Opcode = Instruction::UserOp1;
567 if (const Instruction *I = dyn_cast<Instruction>(V)) {
568 Opcode = I->getOpcode();
570 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
571 Opcode = C->getOpcode();
577 case Instruction::BitCast:
578 // Look past bitcasts.
579 return X86SelectCallAddress(U->getOperand(0), AM);
581 case Instruction::IntToPtr:
582 // Look past no-op inttoptrs.
583 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
584 return X86SelectCallAddress(U->getOperand(0), AM);
587 case Instruction::PtrToInt:
588 // Look past no-op ptrtoints.
589 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
590 return X86SelectCallAddress(U->getOperand(0), AM);
594 // Handle constant address.
595 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
596 // Can't handle alternate code models yet.
597 if (TM.getCodeModel() != CodeModel::Small)
600 // RIP-relative addresses can't have additional register operands.
601 if (Subtarget->isPICStyleRIPRel() &&
602 (AM.Base.Reg != 0 || AM.IndexReg != 0))
605 // Can't handle TLS or DLLImport.
606 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
607 if (GVar->isThreadLocal() || GVar->hasDLLImportLinkage())
610 // Okay, we've committed to selecting this global. Set up the basic address.
613 // No ABI requires an extra load for anything other than DLLImport, which
614 // we rejected above. Return a direct reference to the global.
615 if (Subtarget->isPICStyleRIPRel()) {
616 // Use rip-relative addressing if we can. Above we verified that the
617 // base and index registers are unused.
618 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
619 AM.Base.Reg = X86::RIP;
620 } else if (Subtarget->isPICStyleStubPIC()) {
621 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
622 } else if (Subtarget->isPICStyleGOT()) {
623 AM.GVOpFlags = X86II::MO_GOTOFF;
629 // If all else fails, try to materialize the value in a register.
630 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
631 if (AM.Base.Reg == 0) {
632 AM.Base.Reg = getRegForValue(V);
633 return AM.Base.Reg != 0;
635 if (AM.IndexReg == 0) {
636 assert(AM.Scale == 1 && "Scale with no index!");
637 AM.IndexReg = getRegForValue(V);
638 return AM.IndexReg != 0;
646 /// X86SelectStore - Select and emit code to implement store instructions.
647 bool X86FastISel::X86SelectStore(const Instruction *I) {
649 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
653 if (!X86SelectAddress(I->getOperand(1), AM))
656 return X86FastEmitStore(VT, I->getOperand(0), AM);
659 /// X86SelectLoad - Select and emit code to implement load instructions.
661 bool X86FastISel::X86SelectLoad(const Instruction *I) {
663 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
667 if (!X86SelectAddress(I->getOperand(0), AM))
670 unsigned ResultReg = 0;
671 if (X86FastEmitLoad(VT, AM, ResultReg)) {
672 UpdateValueMap(I, ResultReg);
678 static unsigned X86ChooseCmpOpcode(EVT VT) {
679 switch (VT.getSimpleVT().SimpleTy) {
681 case MVT::i8: return X86::CMP8rr;
682 case MVT::i16: return X86::CMP16rr;
683 case MVT::i32: return X86::CMP32rr;
684 case MVT::i64: return X86::CMP64rr;
685 case MVT::f32: return X86::UCOMISSrr;
686 case MVT::f64: return X86::UCOMISDrr;
690 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
691 /// of the comparison, return an opcode that works for the compare (e.g.
692 /// CMP32ri) otherwise return 0.
693 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
694 switch (VT.getSimpleVT().SimpleTy) {
695 // Otherwise, we can't fold the immediate into this comparison.
697 case MVT::i8: return X86::CMP8ri;
698 case MVT::i16: return X86::CMP16ri;
699 case MVT::i32: return X86::CMP32ri;
701 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
703 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
704 return X86::CMP64ri32;
709 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
711 unsigned Op0Reg = getRegForValue(Op0);
712 if (Op0Reg == 0) return false;
714 // Handle 'null' like i32/i64 0.
715 if (isa<ConstantPointerNull>(Op1))
716 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
718 // We have two options: compare with register or immediate. If the RHS of
719 // the compare is an immediate that we can fold into this compare, use
720 // CMPri, otherwise use CMPrr.
721 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
722 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
723 BuildMI(MBB, DL, TII.get(CompareImmOpc)).addReg(Op0Reg)
724 .addImm(Op1C->getSExtValue());
729 unsigned CompareOpc = X86ChooseCmpOpcode(VT);
730 if (CompareOpc == 0) return false;
732 unsigned Op1Reg = getRegForValue(Op1);
733 if (Op1Reg == 0) return false;
734 BuildMI(MBB, DL, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
739 bool X86FastISel::X86SelectCmp(const Instruction *I) {
740 const CmpInst *CI = cast<CmpInst>(I);
743 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
746 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
748 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
749 switch (CI->getPredicate()) {
750 case CmpInst::FCMP_OEQ: {
751 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
754 unsigned EReg = createResultReg(&X86::GR8RegClass);
755 unsigned NPReg = createResultReg(&X86::GR8RegClass);
756 BuildMI(MBB, DL, TII.get(X86::SETEr), EReg);
757 BuildMI(MBB, DL, TII.get(X86::SETNPr), NPReg);
759 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
760 UpdateValueMap(I, ResultReg);
763 case CmpInst::FCMP_UNE: {
764 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
767 unsigned NEReg = createResultReg(&X86::GR8RegClass);
768 unsigned PReg = createResultReg(&X86::GR8RegClass);
769 BuildMI(MBB, DL, TII.get(X86::SETNEr), NEReg);
770 BuildMI(MBB, DL, TII.get(X86::SETPr), PReg);
771 BuildMI(MBB, DL, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
772 UpdateValueMap(I, ResultReg);
775 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
776 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
777 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
778 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
779 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
780 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
781 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
782 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
783 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
784 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
785 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
786 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
788 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
789 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
790 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
791 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
792 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
793 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
794 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
795 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
796 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
797 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
802 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
806 // Emit a compare of Op0/Op1.
807 if (!X86FastEmitCompare(Op0, Op1, VT))
810 BuildMI(MBB, DL, TII.get(SetCCOpc), ResultReg);
811 UpdateValueMap(I, ResultReg);
815 bool X86FastISel::X86SelectZExt(const Instruction *I) {
816 // Handle zero-extension from i1 to i8, which is common.
817 if (I->getType()->isIntegerTy(8) &&
818 I->getOperand(0)->getType()->isIntegerTy(1)) {
819 unsigned ResultReg = getRegForValue(I->getOperand(0));
820 if (ResultReg == 0) return false;
821 // Set the high bits to zero.
822 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
823 if (ResultReg == 0) return false;
824 UpdateValueMap(I, ResultReg);
832 bool X86FastISel::X86SelectBranch(const Instruction *I) {
833 // Unconditional branches are selected by tablegen-generated code.
834 // Handle a conditional branch.
835 const BranchInst *BI = cast<BranchInst>(I);
836 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
837 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
839 // Fold the common case of a conditional branch with a comparison.
840 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
841 if (CI->hasOneUse()) {
842 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
844 // Try to take advantage of fallthrough opportunities.
845 CmpInst::Predicate Predicate = CI->getPredicate();
846 if (MBB->isLayoutSuccessor(TrueMBB)) {
847 std::swap(TrueMBB, FalseMBB);
848 Predicate = CmpInst::getInversePredicate(Predicate);
851 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
852 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
855 case CmpInst::FCMP_OEQ:
856 std::swap(TrueMBB, FalseMBB);
857 Predicate = CmpInst::FCMP_UNE;
859 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
860 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
861 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
862 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
863 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
864 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
865 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
866 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
867 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
868 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
869 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
870 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
871 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
873 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
874 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
875 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
876 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
877 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
878 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
879 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
880 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
881 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
882 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
887 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
891 // Emit a compare of the LHS and RHS, setting the flags.
892 if (!X86FastEmitCompare(Op0, Op1, VT))
895 BuildMI(MBB, DL, TII.get(BranchOpc)).addMBB(TrueMBB);
897 if (Predicate == CmpInst::FCMP_UNE) {
898 // X86 requires a second branch to handle UNE (and OEQ,
899 // which is mapped to UNE above).
900 BuildMI(MBB, DL, TII.get(X86::JP_4)).addMBB(TrueMBB);
903 FastEmitBranch(FalseMBB, DL);
904 MBB->addSuccessor(TrueMBB);
907 } else if (ExtractValueInst *EI =
908 dyn_cast<ExtractValueInst>(BI->getCondition())) {
909 // Check to see if the branch instruction is from an "arithmetic with
910 // overflow" intrinsic. The main way these intrinsics are used is:
912 // %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
913 // %sum = extractvalue { i32, i1 } %t, 0
914 // %obit = extractvalue { i32, i1 } %t, 1
915 // br i1 %obit, label %overflow, label %normal
917 // The %sum and %obit are converted in an ADD and a SETO/SETB before
918 // reaching the branch. Therefore, we search backwards through the MBB
919 // looking for the SETO/SETB instruction. If an instruction modifies the
920 // EFLAGS register before we reach the SETO/SETB instruction, then we can't
921 // convert the branch into a JO/JB instruction.
922 if (const IntrinsicInst *CI =
923 dyn_cast<IntrinsicInst>(EI->getAggregateOperand())){
924 if (CI->getIntrinsicID() == Intrinsic::sadd_with_overflow ||
925 CI->getIntrinsicID() == Intrinsic::uadd_with_overflow) {
926 const MachineInstr *SetMI = 0;
927 unsigned Reg = getRegForValue(EI);
929 for (MachineBasicBlock::const_reverse_iterator
930 RI = MBB->rbegin(), RE = MBB->rend(); RI != RE; ++RI) {
931 const MachineInstr &MI = *RI;
933 if (MI.definesRegister(Reg)) {
934 unsigned Src, Dst, SrcSR, DstSR;
936 if (getInstrInfo()->isMoveInstr(MI, Src, Dst, SrcSR, DstSR)) {
945 const TargetInstrDesc &TID = MI.getDesc();
946 if (TID.hasUnmodeledSideEffects() ||
947 TID.hasImplicitDefOfPhysReg(X86::EFLAGS))
952 unsigned OpCode = SetMI->getOpcode();
954 if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
955 BuildMI(MBB, DL, TII.get(OpCode == X86::SETOr ?
956 X86::JO_4 : X86::JB_4))
958 FastEmitBranch(FalseMBB, DL);
959 MBB->addSuccessor(TrueMBB);
967 // Otherwise do a clumsy setcc and re-test it.
968 unsigned OpReg = getRegForValue(BI->getCondition());
969 if (OpReg == 0) return false;
971 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
972 BuildMI(MBB, DL, TII.get(X86::JNE_4)).addMBB(TrueMBB);
973 FastEmitBranch(FalseMBB, DL);
974 MBB->addSuccessor(TrueMBB);
978 bool X86FastISel::X86SelectShift(const Instruction *I) {
979 unsigned CReg = 0, OpReg = 0, OpImm = 0;
980 const TargetRegisterClass *RC = NULL;
981 if (I->getType()->isIntegerTy(8)) {
983 RC = &X86::GR8RegClass;
984 switch (I->getOpcode()) {
985 case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
986 case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
987 case Instruction::Shl: OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
988 default: return false;
990 } else if (I->getType()->isIntegerTy(16)) {
992 RC = &X86::GR16RegClass;
993 switch (I->getOpcode()) {
994 case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
995 case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
996 case Instruction::Shl: OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
997 default: return false;
999 } else if (I->getType()->isIntegerTy(32)) {
1001 RC = &X86::GR32RegClass;
1002 switch (I->getOpcode()) {
1003 case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
1004 case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
1005 case Instruction::Shl: OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
1006 default: return false;
1008 } else if (I->getType()->isIntegerTy(64)) {
1010 RC = &X86::GR64RegClass;
1011 switch (I->getOpcode()) {
1012 case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
1013 case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
1014 case Instruction::Shl: OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
1015 default: return false;
1021 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1022 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1025 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1026 if (Op0Reg == 0) return false;
1028 // Fold immediate in shl(x,3).
1029 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1030 unsigned ResultReg = createResultReg(RC);
1031 BuildMI(MBB, DL, TII.get(OpImm),
1032 ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
1033 UpdateValueMap(I, ResultReg);
1037 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1038 if (Op1Reg == 0) return false;
1039 TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC, DL);
1041 // The shift instruction uses X86::CL. If we defined a super-register
1042 // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
1043 // we're doing here.
1044 if (CReg != X86::CL)
1045 BuildMI(MBB, DL, TII.get(TargetOpcode::EXTRACT_SUBREG), X86::CL)
1046 .addReg(CReg).addImm(X86::sub_8bit);
1048 unsigned ResultReg = createResultReg(RC);
1049 BuildMI(MBB, DL, TII.get(OpReg), ResultReg).addReg(Op0Reg);
1050 UpdateValueMap(I, ResultReg);
1054 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1055 EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1056 if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1060 const TargetRegisterClass *RC = NULL;
1061 if (VT.getSimpleVT() == MVT::i16) {
1062 Opc = X86::CMOVE16rr;
1063 RC = &X86::GR16RegClass;
1064 } else if (VT.getSimpleVT() == MVT::i32) {
1065 Opc = X86::CMOVE32rr;
1066 RC = &X86::GR32RegClass;
1067 } else if (VT.getSimpleVT() == MVT::i64) {
1068 Opc = X86::CMOVE64rr;
1069 RC = &X86::GR64RegClass;
1074 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1075 if (Op0Reg == 0) return false;
1076 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1077 if (Op1Reg == 0) return false;
1078 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1079 if (Op2Reg == 0) return false;
1081 BuildMI(MBB, DL, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
1082 unsigned ResultReg = createResultReg(RC);
1083 BuildMI(MBB, DL, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
1084 UpdateValueMap(I, ResultReg);
1088 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1089 // fpext from float to double.
1090 if (Subtarget->hasSSE2() &&
1091 I->getType()->isDoubleTy()) {
1092 const Value *V = I->getOperand(0);
1093 if (V->getType()->isFloatTy()) {
1094 unsigned OpReg = getRegForValue(V);
1095 if (OpReg == 0) return false;
1096 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1097 BuildMI(MBB, DL, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
1098 UpdateValueMap(I, ResultReg);
1106 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1107 if (Subtarget->hasSSE2()) {
1108 if (I->getType()->isFloatTy()) {
1109 const Value *V = I->getOperand(0);
1110 if (V->getType()->isDoubleTy()) {
1111 unsigned OpReg = getRegForValue(V);
1112 if (OpReg == 0) return false;
1113 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1114 BuildMI(MBB, DL, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
1115 UpdateValueMap(I, ResultReg);
1124 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1125 if (Subtarget->is64Bit())
1126 // All other cases should be handled by the tblgen generated code.
1128 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1129 EVT DstVT = TLI.getValueType(I->getType());
1131 // This code only handles truncation to byte right now.
1132 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1133 // All other cases should be handled by the tblgen generated code.
1135 if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1136 // All other cases should be handled by the tblgen generated code.
1139 unsigned InputReg = getRegForValue(I->getOperand(0));
1141 // Unhandled operand. Halt "fast" selection and bail.
1144 // First issue a copy to GR16_ABCD or GR32_ABCD.
1145 unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16rr : X86::MOV32rr;
1146 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1147 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1148 unsigned CopyReg = createResultReg(CopyRC);
1149 BuildMI(MBB, DL, TII.get(CopyOpc), CopyReg).addReg(InputReg);
1151 // Then issue an extract_subreg.
1152 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1153 CopyReg, /*Kill=*/true,
1158 UpdateValueMap(I, ResultReg);
1162 bool X86FastISel::X86SelectExtractValue(const Instruction *I) {
1163 const ExtractValueInst *EI = cast<ExtractValueInst>(I);
1164 const Value *Agg = EI->getAggregateOperand();
1166 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1167 switch (CI->getIntrinsicID()) {
1169 case Intrinsic::sadd_with_overflow:
1170 case Intrinsic::uadd_with_overflow:
1171 // Cheat a little. We know that the registers for "add" and "seto" are
1172 // allocated sequentially. However, we only keep track of the register
1173 // for "add" in the value map. Use extractvalue's index to get the
1174 // correct register for "seto".
1175 UpdateValueMap(I, lookUpRegForValue(Agg) + *EI->idx_begin());
1183 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1184 // FIXME: Handle more intrinsics.
1185 switch (I.getIntrinsicID()) {
1186 default: return false;
1187 case Intrinsic::stackprotector: {
1188 // Emit code inline code to store the stack guard onto the stack.
1189 EVT PtrTy = TLI.getPointerTy();
1191 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1192 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1194 // Grab the frame index.
1196 if (!X86SelectAddress(Slot, AM)) return false;
1198 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1202 case Intrinsic::objectsize: {
1203 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
1204 const Type *Ty = I.getCalledFunction()->getReturnType();
1206 assert(CI && "Non-constant type in Intrinsic::objectsize?");
1209 if (!isTypeLegal(Ty, VT))
1215 else if (VT == MVT::i64)
1220 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1221 BuildMI(MBB, DL, TII.get(OpC), ResultReg).
1222 addImm(CI->isZero() ? -1ULL : 0);
1223 UpdateValueMap(&I, ResultReg);
1226 case Intrinsic::dbg_declare: {
1227 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1229 assert(DI->getAddress() && "Null address should be checked earlier!");
1230 if (!X86SelectAddress(DI->getAddress(), AM))
1232 const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1233 // FIXME may need to add RegState::Debug to any registers produced,
1234 // although ESP/EBP should be the only ones at the moment.
1235 addFullAddress(BuildMI(MBB, DL, II), AM).addImm(0).
1236 addMetadata(DI->getVariable());
1239 case Intrinsic::trap: {
1240 BuildMI(MBB, DL, TII.get(X86::TRAP));
1243 case Intrinsic::sadd_with_overflow:
1244 case Intrinsic::uadd_with_overflow: {
1245 // Replace "add with overflow" intrinsics with an "add" instruction followed
1246 // by a seto/setc instruction. Later on, when the "extractvalue"
1247 // instructions are encountered, we use the fact that two registers were
1248 // created sequentially to get the correct registers for the "sum" and the
1250 const Function *Callee = I.getCalledFunction();
1252 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1255 if (!isTypeLegal(RetTy, VT))
1258 const Value *Op1 = I.getArgOperand(0);
1259 const Value *Op2 = I.getArgOperand(1);
1260 unsigned Reg1 = getRegForValue(Op1);
1261 unsigned Reg2 = getRegForValue(Op2);
1263 if (Reg1 == 0 || Reg2 == 0)
1264 // FIXME: Handle values *not* in registers.
1270 else if (VT == MVT::i64)
1275 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1276 BuildMI(MBB, DL, TII.get(OpC), ResultReg).addReg(Reg1).addReg(Reg2);
1277 unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1279 // If the add with overflow is an intra-block value then we just want to
1280 // create temporaries for it like normal. If it is a cross-block value then
1281 // UpdateValueMap will return the cross-block register used. Since we
1282 // *really* want the value to be live in the register pair known by
1283 // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1284 // the cross block case. In the non-cross-block case, we should just make
1285 // another register for the value.
1286 if (DestReg1 != ResultReg)
1287 ResultReg = DestReg1+1;
1289 ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1291 unsigned Opc = X86::SETBr;
1292 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1294 BuildMI(MBB, DL, TII.get(Opc), ResultReg);
1300 bool X86FastISel::X86SelectCall(const Instruction *I) {
1301 const CallInst *CI = cast<CallInst>(I);
1302 const Value *Callee = CI->getCalledValue();
1304 // Can't handle inline asm yet.
1305 if (isa<InlineAsm>(Callee))
1308 // Handle intrinsic calls.
1309 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1310 return X86VisitIntrinsicCall(*II);
1312 // Handle only C and fastcc calling conventions for now.
1313 ImmutableCallSite CS(CI);
1314 CallingConv::ID CC = CS.getCallingConv();
1315 if (CC != CallingConv::C &&
1316 CC != CallingConv::Fast &&
1317 CC != CallingConv::X86_FastCall)
1320 // fastcc with -tailcallopt is intended to provide a guaranteed
1321 // tail call optimization. Fastisel doesn't know how to do that.
1322 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1325 // Let SDISel handle vararg functions.
1326 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1327 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1328 if (FTy->isVarArg())
1331 // Fast-isel doesn't know about callee-pop yet.
1332 if (Subtarget->IsCalleePop(FTy->isVarArg(), CC))
1335 // Handle *simple* calls for now.
1336 const Type *RetTy = CS.getType();
1338 if (RetTy->isVoidTy())
1339 RetVT = MVT::isVoid;
1340 else if (!isTypeLegal(RetTy, RetVT, true))
1343 // Materialize callee address in a register. FIXME: GV address can be
1344 // handled with a CALLpcrel32 instead.
1345 X86AddressMode CalleeAM;
1346 if (!X86SelectCallAddress(Callee, CalleeAM))
1348 unsigned CalleeOp = 0;
1349 const GlobalValue *GV = 0;
1350 if (CalleeAM.GV != 0) {
1352 } else if (CalleeAM.Base.Reg != 0) {
1353 CalleeOp = CalleeAM.Base.Reg;
1357 // Allow calls which produce i1 results.
1358 bool AndToI1 = false;
1359 if (RetVT == MVT::i1) {
1364 // Deal with call operands first.
1365 SmallVector<const Value *, 8> ArgVals;
1366 SmallVector<unsigned, 8> Args;
1367 SmallVector<EVT, 8> ArgVTs;
1368 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1369 Args.reserve(CS.arg_size());
1370 ArgVals.reserve(CS.arg_size());
1371 ArgVTs.reserve(CS.arg_size());
1372 ArgFlags.reserve(CS.arg_size());
1373 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1375 unsigned Arg = getRegForValue(*i);
1378 ISD::ArgFlagsTy Flags;
1379 unsigned AttrInd = i - CS.arg_begin() + 1;
1380 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1382 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1385 // FIXME: Only handle *easy* calls for now.
1386 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1387 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1388 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1389 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1392 const Type *ArgTy = (*i)->getType();
1394 if (!isTypeLegal(ArgTy, ArgVT))
1396 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1397 Flags.setOrigAlign(OriginalAlignment);
1399 Args.push_back(Arg);
1400 ArgVals.push_back(*i);
1401 ArgVTs.push_back(ArgVT);
1402 ArgFlags.push_back(Flags);
1405 // Analyze operands of the call, assigning locations to each operand.
1406 SmallVector<CCValAssign, 16> ArgLocs;
1407 CCState CCInfo(CC, false, TM, ArgLocs, I->getParent()->getContext());
1409 // Allocate shadow area for Win64
1410 if (Subtarget->isTargetWin64()) {
1411 CCInfo.AllocateStack(32, 8);
1414 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1416 // Get a count of how many bytes are to be pushed on the stack.
1417 unsigned NumBytes = CCInfo.getNextStackOffset();
1419 // Issue CALLSEQ_START
1420 unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1421 BuildMI(MBB, DL, TII.get(AdjStackDown)).addImm(NumBytes);
1423 // Process argument: walk the register/memloc assignments, inserting
1425 SmallVector<unsigned, 4> RegArgs;
1426 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1427 CCValAssign &VA = ArgLocs[i];
1428 unsigned Arg = Args[VA.getValNo()];
1429 EVT ArgVT = ArgVTs[VA.getValNo()];
1431 // Promote the value if needed.
1432 switch (VA.getLocInfo()) {
1433 default: llvm_unreachable("Unknown loc info!");
1434 case CCValAssign::Full: break;
1435 case CCValAssign::SExt: {
1436 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1438 assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1440 ArgVT = VA.getLocVT();
1443 case CCValAssign::ZExt: {
1444 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1446 assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1448 ArgVT = VA.getLocVT();
1451 case CCValAssign::AExt: {
1452 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1455 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1458 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1461 assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1462 ArgVT = VA.getLocVT();
1465 case CCValAssign::BCvt: {
1466 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT().getSimpleVT(),
1467 ISD::BIT_CONVERT, Arg, /*TODO: Kill=*/false);
1468 assert(BC != 0 && "Failed to emit a bitcast!");
1470 ArgVT = VA.getLocVT();
1475 if (VA.isRegLoc()) {
1476 TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1477 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1479 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1481 RegArgs.push_back(VA.getLocReg());
1483 unsigned LocMemOffset = VA.getLocMemOffset();
1485 AM.Base.Reg = StackPtr;
1486 AM.Disp = LocMemOffset;
1487 const Value *ArgVal = ArgVals[VA.getValNo()];
1489 // If this is a really simple value, emit this with the Value* version of
1490 // X86FastEmitStore. If it isn't simple, we don't want to do this, as it
1491 // can cause us to reevaluate the argument.
1492 if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1493 X86FastEmitStore(ArgVT, ArgVal, AM);
1495 X86FastEmitStore(ArgVT, Arg, AM);
1499 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1501 if (Subtarget->isPICStyleGOT()) {
1502 TargetRegisterClass *RC = X86::GR32RegisterClass;
1503 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1504 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC,
1506 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1511 MachineInstrBuilder MIB;
1513 // Register-indirect call.
1514 unsigned CallOpc = Subtarget->is64Bit() ? X86::CALL64r : X86::CALL32r;
1515 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addReg(CalleeOp);
1519 assert(GV && "Not a direct call");
1521 Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
1523 // See if we need any target-specific flags on the GV operand.
1524 unsigned char OpFlags = 0;
1526 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1527 // external symbols most go through the PLT in PIC mode. If the symbol
1528 // has hidden or protected visibility, or if it is static or local, then
1529 // we don't need to use the PLT - we can directly call it.
1530 if (Subtarget->isTargetELF() &&
1531 TM.getRelocationModel() == Reloc::PIC_ &&
1532 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1533 OpFlags = X86II::MO_PLT;
1534 } else if (Subtarget->isPICStyleStubAny() &&
1535 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1536 Subtarget->getDarwinVers() < 9) {
1537 // PC-relative references to external symbols should go through $stub,
1538 // unless we're building with the leopard linker or later, which
1539 // automatically synthesizes these stubs.
1540 OpFlags = X86II::MO_DARWIN_STUB;
1544 MIB = BuildMI(MBB, DL, TII.get(CallOpc)).addGlobalAddress(GV, 0, OpFlags);
1547 // Add an implicit use GOT pointer in EBX.
1548 if (Subtarget->isPICStyleGOT())
1549 MIB.addReg(X86::EBX);
1551 // Add implicit physical register uses to the call.
1552 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1553 MIB.addReg(RegArgs[i]);
1555 // Issue CALLSEQ_END
1556 unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1557 BuildMI(MBB, DL, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1559 // Now handle call return value (if any).
1560 SmallVector<unsigned, 4> UsedRegs;
1561 if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1562 SmallVector<CCValAssign, 16> RVLocs;
1563 CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1564 CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1566 // Copy all of the result registers out of their specified physreg.
1567 assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1568 EVT CopyVT = RVLocs[0].getValVT();
1569 TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1570 TargetRegisterClass *SrcRC = DstRC;
1572 // If this is a call to a function that returns an fp value on the x87 fp
1573 // stack, but where we prefer to use the value in xmm registers, copy it
1574 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1575 if ((RVLocs[0].getLocReg() == X86::ST0 ||
1576 RVLocs[0].getLocReg() == X86::ST1) &&
1577 isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1579 SrcRC = X86::RSTRegisterClass;
1580 DstRC = X86::RFP80RegisterClass;
1583 unsigned ResultReg = createResultReg(DstRC);
1584 bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1585 RVLocs[0].getLocReg(), DstRC, SrcRC, DL);
1586 assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1588 UsedRegs.push_back(RVLocs[0].getLocReg());
1590 if (CopyVT != RVLocs[0].getValVT()) {
1591 // Round the F80 the right size, which also moves to the appropriate xmm
1592 // register. This is accomplished by storing the F80 value in memory and
1593 // then loading it back. Ewww...
1594 EVT ResVT = RVLocs[0].getValVT();
1595 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1596 unsigned MemSize = ResVT.getSizeInBits()/8;
1597 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1598 addFrameReference(BuildMI(MBB, DL, TII.get(Opc)), FI).addReg(ResultReg);
1599 DstRC = ResVT == MVT::f32
1600 ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1601 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1602 ResultReg = createResultReg(DstRC);
1603 addFrameReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg), FI);
1607 // Mask out all but lowest bit for some call which produces an i1.
1608 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1610 TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1611 ResultReg = AndResult;
1614 UpdateValueMap(I, ResultReg);
1617 // Set all unused physreg defs as dead.
1618 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1625 X86FastISel::TargetSelectInstruction(const Instruction *I) {
1626 switch (I->getOpcode()) {
1628 case Instruction::Load:
1629 return X86SelectLoad(I);
1630 case Instruction::Store:
1631 return X86SelectStore(I);
1632 case Instruction::ICmp:
1633 case Instruction::FCmp:
1634 return X86SelectCmp(I);
1635 case Instruction::ZExt:
1636 return X86SelectZExt(I);
1637 case Instruction::Br:
1638 return X86SelectBranch(I);
1639 case Instruction::Call:
1640 return X86SelectCall(I);
1641 case Instruction::LShr:
1642 case Instruction::AShr:
1643 case Instruction::Shl:
1644 return X86SelectShift(I);
1645 case Instruction::Select:
1646 return X86SelectSelect(I);
1647 case Instruction::Trunc:
1648 return X86SelectTrunc(I);
1649 case Instruction::FPExt:
1650 return X86SelectFPExt(I);
1651 case Instruction::FPTrunc:
1652 return X86SelectFPTrunc(I);
1653 case Instruction::ExtractValue:
1654 return X86SelectExtractValue(I);
1655 case Instruction::IntToPtr: // Deliberate fall-through.
1656 case Instruction::PtrToInt: {
1657 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1658 EVT DstVT = TLI.getValueType(I->getType());
1659 if (DstVT.bitsGT(SrcVT))
1660 return X86SelectZExt(I);
1661 if (DstVT.bitsLT(SrcVT))
1662 return X86SelectTrunc(I);
1663 unsigned Reg = getRegForValue(I->getOperand(0));
1664 if (Reg == 0) return false;
1665 UpdateValueMap(I, Reg);
1673 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
1675 if (!isTypeLegal(C->getType(), VT))
1678 // Get opcode and regclass of the output for the given load instruction.
1680 const TargetRegisterClass *RC = NULL;
1681 switch (VT.getSimpleVT().SimpleTy) {
1682 default: return false;
1685 RC = X86::GR8RegisterClass;
1689 RC = X86::GR16RegisterClass;
1693 RC = X86::GR32RegisterClass;
1696 // Must be in x86-64 mode.
1698 RC = X86::GR64RegisterClass;
1701 if (Subtarget->hasSSE1()) {
1703 RC = X86::FR32RegisterClass;
1705 Opc = X86::LD_Fp32m;
1706 RC = X86::RFP32RegisterClass;
1710 if (Subtarget->hasSSE2()) {
1712 RC = X86::FR64RegisterClass;
1714 Opc = X86::LD_Fp64m;
1715 RC = X86::RFP64RegisterClass;
1719 // No f80 support yet.
1723 // Materialize addresses with LEA instructions.
1724 if (isa<GlobalValue>(C)) {
1726 if (X86SelectAddress(C, AM)) {
1727 if (TLI.getPointerTy() == MVT::i32)
1731 unsigned ResultReg = createResultReg(RC);
1732 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1738 // MachineConstantPool wants an explicit alignment.
1739 unsigned Align = TD.getPrefTypeAlignment(C->getType());
1741 // Alignment of vector types. FIXME!
1742 Align = TD.getTypeAllocSize(C->getType());
1745 // x86-32 PIC requires a PIC base register for constant pools.
1746 unsigned PICBase = 0;
1747 unsigned char OpFlag = 0;
1748 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1749 OpFlag = X86II::MO_PIC_BASE_OFFSET;
1750 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1751 } else if (Subtarget->isPICStyleGOT()) {
1752 OpFlag = X86II::MO_GOTOFF;
1753 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1754 } else if (Subtarget->isPICStyleRIPRel() &&
1755 TM.getCodeModel() == CodeModel::Small) {
1759 // Create the load from the constant pool.
1760 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1761 unsigned ResultReg = createResultReg(RC);
1762 addConstantPoolReference(BuildMI(MBB, DL, TII.get(Opc), ResultReg),
1763 MCPOffset, PICBase, OpFlag);
1768 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
1769 // Fail on dynamic allocas. At this point, getRegForValue has already
1770 // checked its CSE maps, so if we're here trying to handle a dynamic
1771 // alloca, we're not going to succeed. X86SelectAddress has a
1772 // check for dynamic allocas, because it's called directly from
1773 // various places, but TargetMaterializeAlloca also needs a check
1774 // in order to avoid recursion between getRegForValue,
1775 // X86SelectAddrss, and TargetMaterializeAlloca.
1776 if (!FuncInfo.StaticAllocaMap.count(C))
1780 if (!X86SelectAddress(C, AM))
1782 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1783 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1784 unsigned ResultReg = createResultReg(RC);
1785 addLeaAddress(BuildMI(MBB, DL, TII.get(Opc), ResultReg), AM);
1790 llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
1791 return new X86FastISel(funcInfo);