Use %ull here.
[llvm/stm8.git] / lib / Target / X86 / X86FastISel.cpp
blob521eb30b7763725726e79e3561e86c313ca2b134
1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 //===----------------------------------------------------------------------===//
16 #include "X86.h"
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/Operator.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/FunctionLoweringInfo.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include "llvm/Target/TargetOptions.h"
37 using namespace llvm;
39 namespace {
41 class X86FastISel : public FastISel {
42 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
43 /// make the right decision when generating code for different targets.
44 const X86Subtarget *Subtarget;
46 /// StackPtr - Register used as the stack pointer.
47 ///
48 unsigned StackPtr;
50 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
51 /// floating point ops.
52 /// When SSE is available, use it for f32 operations.
53 /// When SSE2 is available, use it for f64 operations.
54 bool X86ScalarSSEf64;
55 bool X86ScalarSSEf32;
57 public:
58 explicit X86FastISel(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo) {
59 Subtarget = &TM.getSubtarget<X86Subtarget>();
60 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
61 X86ScalarSSEf64 = Subtarget->hasSSE2();
62 X86ScalarSSEf32 = Subtarget->hasSSE1();
65 virtual bool TargetSelectInstruction(const Instruction *I);
67 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
68 /// vreg is being provided by the specified load instruction. If possible,
69 /// try to fold the load as an operand to the instruction, returning true if
70 /// possible.
71 virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
72 const LoadInst *LI);
74 #include "X86GenFastISel.inc"
76 private:
77 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
79 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
81 bool X86FastEmitStore(EVT VT, const Value *Val,
82 const X86AddressMode &AM);
83 bool X86FastEmitStore(EVT VT, unsigned Val,
84 const X86AddressMode &AM);
86 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
87 unsigned &ResultReg);
89 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
90 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
92 bool X86SelectLoad(const Instruction *I);
94 bool X86SelectStore(const Instruction *I);
96 bool X86SelectRet(const Instruction *I);
98 bool X86SelectCmp(const Instruction *I);
100 bool X86SelectZExt(const Instruction *I);
102 bool X86SelectBranch(const Instruction *I);
104 bool X86SelectShift(const Instruction *I);
106 bool X86SelectSelect(const Instruction *I);
108 bool X86SelectTrunc(const Instruction *I);
110 bool X86SelectFPExt(const Instruction *I);
111 bool X86SelectFPTrunc(const Instruction *I);
113 bool X86SelectExtractValue(const Instruction *I);
115 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
116 bool X86SelectCall(const Instruction *I);
118 const X86InstrInfo *getInstrInfo() const {
119 return getTargetMachine()->getInstrInfo();
121 const X86TargetMachine *getTargetMachine() const {
122 return static_cast<const X86TargetMachine *>(&TM);
125 unsigned TargetMaterializeConstant(const Constant *C);
127 unsigned TargetMaterializeAlloca(const AllocaInst *C);
129 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
130 /// computed in an SSE register, not on the X87 floating point stack.
131 bool isScalarFPTypeInSSEReg(EVT VT) const {
132 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
133 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
136 bool isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1 = false);
139 } // end anonymous namespace.
141 bool X86FastISel::isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1) {
142 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
143 if (evt == MVT::Other || !evt.isSimple())
144 // Unhandled type. Halt "fast" selection and bail.
145 return false;
147 VT = evt.getSimpleVT();
148 // For now, require SSE/SSE2 for performing floating-point operations,
149 // since x87 requires additional work.
150 if (VT == MVT::f64 && !X86ScalarSSEf64)
151 return false;
152 if (VT == MVT::f32 && !X86ScalarSSEf32)
153 return false;
154 // Similarly, no f80 support yet.
155 if (VT == MVT::f80)
156 return false;
157 // We only handle legal types. For example, on x86-32 the instruction
158 // selector contains all of the 64-bit instructions from x86-64,
159 // under the assumption that i64 won't be used if the target doesn't
160 // support it.
161 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
164 #include "X86GenCallingConv.inc"
166 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
167 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
168 /// Return true and the result register by reference if it is possible.
169 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
170 unsigned &ResultReg) {
171 // Get opcode and regclass of the output for the given load instruction.
172 unsigned Opc = 0;
173 const TargetRegisterClass *RC = NULL;
174 switch (VT.getSimpleVT().SimpleTy) {
175 default: return false;
176 case MVT::i1:
177 case MVT::i8:
178 Opc = X86::MOV8rm;
179 RC = X86::GR8RegisterClass;
180 break;
181 case MVT::i16:
182 Opc = X86::MOV16rm;
183 RC = X86::GR16RegisterClass;
184 break;
185 case MVT::i32:
186 Opc = X86::MOV32rm;
187 RC = X86::GR32RegisterClass;
188 break;
189 case MVT::i64:
190 // Must be in x86-64 mode.
191 Opc = X86::MOV64rm;
192 RC = X86::GR64RegisterClass;
193 break;
194 case MVT::f32:
195 if (Subtarget->hasSSE1()) {
196 Opc = X86::MOVSSrm;
197 RC = X86::FR32RegisterClass;
198 } else {
199 Opc = X86::LD_Fp32m;
200 RC = X86::RFP32RegisterClass;
202 break;
203 case MVT::f64:
204 if (Subtarget->hasSSE2()) {
205 Opc = X86::MOVSDrm;
206 RC = X86::FR64RegisterClass;
207 } else {
208 Opc = X86::LD_Fp64m;
209 RC = X86::RFP64RegisterClass;
211 break;
212 case MVT::f80:
213 // No f80 support yet.
214 return false;
217 ResultReg = createResultReg(RC);
218 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
219 DL, TII.get(Opc), ResultReg), AM);
220 return true;
223 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
224 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
225 /// and a displacement offset, or a GlobalAddress,
226 /// i.e. V. Return true if it is possible.
227 bool
228 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val,
229 const X86AddressMode &AM) {
230 // Get opcode and regclass of the output for the given store instruction.
231 unsigned Opc = 0;
232 switch (VT.getSimpleVT().SimpleTy) {
233 case MVT::f80: // No f80 support yet.
234 default: return false;
235 case MVT::i1: {
236 // Mask out all but lowest bit.
237 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
239 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
240 Val = AndResult;
242 // FALLTHROUGH, handling i1 as i8.
243 case MVT::i8: Opc = X86::MOV8mr; break;
244 case MVT::i16: Opc = X86::MOV16mr; break;
245 case MVT::i32: Opc = X86::MOV32mr; break;
246 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
247 case MVT::f32:
248 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
249 break;
250 case MVT::f64:
251 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
252 break;
255 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
256 DL, TII.get(Opc)), AM).addReg(Val);
257 return true;
260 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
261 const X86AddressMode &AM) {
262 // Handle 'null' like i32/i64 0.
263 if (isa<ConstantPointerNull>(Val))
264 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
266 // If this is a store of a simple constant, fold the constant into the store.
267 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
268 unsigned Opc = 0;
269 bool Signed = true;
270 switch (VT.getSimpleVT().SimpleTy) {
271 default: break;
272 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
273 case MVT::i8: Opc = X86::MOV8mi; break;
274 case MVT::i16: Opc = X86::MOV16mi; break;
275 case MVT::i32: Opc = X86::MOV32mi; break;
276 case MVT::i64:
277 // Must be a 32-bit sign extended value.
278 if ((int)CI->getSExtValue() == CI->getSExtValue())
279 Opc = X86::MOV64mi32;
280 break;
283 if (Opc) {
284 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
285 DL, TII.get(Opc)), AM)
286 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
287 CI->getZExtValue());
288 return true;
292 unsigned ValReg = getRegForValue(Val);
293 if (ValReg == 0)
294 return false;
296 return X86FastEmitStore(VT, ValReg, AM);
299 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
300 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
301 /// ISD::SIGN_EXTEND).
302 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
303 unsigned Src, EVT SrcVT,
304 unsigned &ResultReg) {
305 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
306 Src, /*TODO: Kill=*/false);
308 if (RR != 0) {
309 ResultReg = RR;
310 return true;
311 } else
312 return false;
315 /// X86SelectAddress - Attempt to fill in an address from the given value.
317 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
318 const User *U = NULL;
319 unsigned Opcode = Instruction::UserOp1;
320 if (const Instruction *I = dyn_cast<Instruction>(V)) {
321 // Don't walk into other basic blocks; it's possible we haven't
322 // visited them yet, so the instructions may not yet be assigned
323 // virtual registers.
324 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
325 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
326 Opcode = I->getOpcode();
327 U = I;
329 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
330 Opcode = C->getOpcode();
331 U = C;
334 if (const PointerType *Ty = dyn_cast<PointerType>(V->getType()))
335 if (Ty->getAddressSpace() > 255)
336 // Fast instruction selection doesn't support the special
337 // address spaces.
338 return false;
340 switch (Opcode) {
341 default: break;
342 case Instruction::BitCast:
343 // Look past bitcasts.
344 return X86SelectAddress(U->getOperand(0), AM);
346 case Instruction::IntToPtr:
347 // Look past no-op inttoptrs.
348 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
349 return X86SelectAddress(U->getOperand(0), AM);
350 break;
352 case Instruction::PtrToInt:
353 // Look past no-op ptrtoints.
354 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
355 return X86SelectAddress(U->getOperand(0), AM);
356 break;
358 case Instruction::Alloca: {
359 // Do static allocas.
360 const AllocaInst *A = cast<AllocaInst>(V);
361 DenseMap<const AllocaInst*, int>::iterator SI =
362 FuncInfo.StaticAllocaMap.find(A);
363 if (SI != FuncInfo.StaticAllocaMap.end()) {
364 AM.BaseType = X86AddressMode::FrameIndexBase;
365 AM.Base.FrameIndex = SI->second;
366 return true;
368 break;
371 case Instruction::Add: {
372 // Adds of constants are common and easy enough.
373 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
374 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
375 // They have to fit in the 32-bit signed displacement field though.
376 if (isInt<32>(Disp)) {
377 AM.Disp = (uint32_t)Disp;
378 return X86SelectAddress(U->getOperand(0), AM);
381 break;
384 case Instruction::GetElementPtr: {
385 X86AddressMode SavedAM = AM;
387 // Pattern-match simple GEPs.
388 uint64_t Disp = (int32_t)AM.Disp;
389 unsigned IndexReg = AM.IndexReg;
390 unsigned Scale = AM.Scale;
391 gep_type_iterator GTI = gep_type_begin(U);
392 // Iterate through the indices, folding what we can. Constants can be
393 // folded, and one dynamic index can be handled, if the scale is supported.
394 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
395 i != e; ++i, ++GTI) {
396 const Value *Op = *i;
397 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
398 const StructLayout *SL = TD.getStructLayout(STy);
399 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
400 Disp += SL->getElementOffset(Idx);
401 } else {
402 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
403 for (;;) {
404 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
405 // Constant-offset addressing.
406 Disp += CI->getSExtValue() * S;
407 break;
409 if (isa<AddOperator>(Op) &&
410 (!isa<Instruction>(Op) ||
411 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
412 == FuncInfo.MBB) &&
413 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
414 // An add (in the same block) with a constant operand. Fold the
415 // constant.
416 ConstantInt *CI =
417 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
418 Disp += CI->getSExtValue() * S;
419 // Iterate on the other operand.
420 Op = cast<AddOperator>(Op)->getOperand(0);
421 continue;
423 if (IndexReg == 0 &&
424 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
425 (S == 1 || S == 2 || S == 4 || S == 8)) {
426 // Scaled-index addressing.
427 Scale = S;
428 IndexReg = getRegForGEPIndex(Op).first;
429 if (IndexReg == 0)
430 return false;
431 break;
433 // Unsupported.
434 goto unsupported_gep;
438 // Check for displacement overflow.
439 if (!isInt<32>(Disp))
440 break;
441 // Ok, the GEP indices were covered by constant-offset and scaled-index
442 // addressing. Update the address state and move on to examining the base.
443 AM.IndexReg = IndexReg;
444 AM.Scale = Scale;
445 AM.Disp = (uint32_t)Disp;
446 if (X86SelectAddress(U->getOperand(0), AM))
447 return true;
449 // If we couldn't merge the sub value into this addr mode, revert back to
450 // our address and just match the value instead of completely failing.
451 AM = SavedAM;
452 break;
453 unsupported_gep:
454 // Ok, the GEP indices weren't all covered.
455 break;
459 // Handle constant address.
460 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
461 // Can't handle alternate code models yet.
462 if (TM.getCodeModel() != CodeModel::Small)
463 return false;
465 // RIP-relative addresses can't have additional register operands.
466 if (Subtarget->isPICStyleRIPRel() &&
467 (AM.Base.Reg != 0 || AM.IndexReg != 0))
468 return false;
470 // Can't handle TLS yet.
471 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
472 if (GVar->isThreadLocal())
473 return false;
475 // Okay, we've committed to selecting this global. Set up the basic address.
476 AM.GV = GV;
478 // Allow the subtarget to classify the global.
479 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
481 // If this reference is relative to the pic base, set it now.
482 if (isGlobalRelativeToPICBase(GVFlags)) {
483 // FIXME: How do we know Base.Reg is free??
484 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
487 // Unless the ABI requires an extra load, return a direct reference to
488 // the global.
489 if (!isGlobalStubReference(GVFlags)) {
490 if (Subtarget->isPICStyleRIPRel()) {
491 // Use rip-relative addressing if we can. Above we verified that the
492 // base and index registers are unused.
493 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
494 AM.Base.Reg = X86::RIP;
496 AM.GVOpFlags = GVFlags;
497 return true;
500 // Ok, we need to do a load from a stub. If we've already loaded from this
501 // stub, reuse the loaded pointer, otherwise emit the load now.
502 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
503 unsigned LoadReg;
504 if (I != LocalValueMap.end() && I->second != 0) {
505 LoadReg = I->second;
506 } else {
507 // Issue load from stub.
508 unsigned Opc = 0;
509 const TargetRegisterClass *RC = NULL;
510 X86AddressMode StubAM;
511 StubAM.Base.Reg = AM.Base.Reg;
512 StubAM.GV = GV;
513 StubAM.GVOpFlags = GVFlags;
515 // Prepare for inserting code in the local-value area.
516 SavePoint SaveInsertPt = enterLocalValueArea();
518 if (TLI.getPointerTy() == MVT::i64) {
519 Opc = X86::MOV64rm;
520 RC = X86::GR64RegisterClass;
522 if (Subtarget->isPICStyleRIPRel())
523 StubAM.Base.Reg = X86::RIP;
524 } else {
525 Opc = X86::MOV32rm;
526 RC = X86::GR32RegisterClass;
529 LoadReg = createResultReg(RC);
530 MachineInstrBuilder LoadMI =
531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
532 addFullAddress(LoadMI, StubAM);
534 // Ok, back to normal mode.
535 leaveLocalValueArea(SaveInsertPt);
537 // Prevent loading GV stub multiple times in same MBB.
538 LocalValueMap[V] = LoadReg;
541 // Now construct the final address. Note that the Disp, Scale,
542 // and Index values may already be set here.
543 AM.Base.Reg = LoadReg;
544 AM.GV = 0;
545 return true;
548 // If all else fails, try to materialize the value in a register.
549 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
550 if (AM.Base.Reg == 0) {
551 AM.Base.Reg = getRegForValue(V);
552 return AM.Base.Reg != 0;
554 if (AM.IndexReg == 0) {
555 assert(AM.Scale == 1 && "Scale with no index!");
556 AM.IndexReg = getRegForValue(V);
557 return AM.IndexReg != 0;
561 return false;
564 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
566 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
567 const User *U = NULL;
568 unsigned Opcode = Instruction::UserOp1;
569 if (const Instruction *I = dyn_cast<Instruction>(V)) {
570 Opcode = I->getOpcode();
571 U = I;
572 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
573 Opcode = C->getOpcode();
574 U = C;
577 switch (Opcode) {
578 default: break;
579 case Instruction::BitCast:
580 // Look past bitcasts.
581 return X86SelectCallAddress(U->getOperand(0), AM);
583 case Instruction::IntToPtr:
584 // Look past no-op inttoptrs.
585 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
586 return X86SelectCallAddress(U->getOperand(0), AM);
587 break;
589 case Instruction::PtrToInt:
590 // Look past no-op ptrtoints.
591 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
592 return X86SelectCallAddress(U->getOperand(0), AM);
593 break;
596 // Handle constant address.
597 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
598 // Can't handle alternate code models yet.
599 if (TM.getCodeModel() != CodeModel::Small)
600 return false;
602 // RIP-relative addresses can't have additional register operands.
603 if (Subtarget->isPICStyleRIPRel() &&
604 (AM.Base.Reg != 0 || AM.IndexReg != 0))
605 return false;
607 // Can't handle DLLImport.
608 if (GV->hasDLLImportLinkage())
609 return false;
611 // Can't handle TLS.
612 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
613 if (GVar->isThreadLocal())
614 return false;
616 // Okay, we've committed to selecting this global. Set up the basic address.
617 AM.GV = GV;
619 // No ABI requires an extra load for anything other than DLLImport, which
620 // we rejected above. Return a direct reference to the global.
621 if (Subtarget->isPICStyleRIPRel()) {
622 // Use rip-relative addressing if we can. Above we verified that the
623 // base and index registers are unused.
624 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
625 AM.Base.Reg = X86::RIP;
626 } else if (Subtarget->isPICStyleStubPIC()) {
627 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
628 } else if (Subtarget->isPICStyleGOT()) {
629 AM.GVOpFlags = X86II::MO_GOTOFF;
632 return true;
635 // If all else fails, try to materialize the value in a register.
636 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
637 if (AM.Base.Reg == 0) {
638 AM.Base.Reg = getRegForValue(V);
639 return AM.Base.Reg != 0;
641 if (AM.IndexReg == 0) {
642 assert(AM.Scale == 1 && "Scale with no index!");
643 AM.IndexReg = getRegForValue(V);
644 return AM.IndexReg != 0;
648 return false;
652 /// X86SelectStore - Select and emit code to implement store instructions.
653 bool X86FastISel::X86SelectStore(const Instruction *I) {
654 MVT VT;
655 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
656 return false;
658 X86AddressMode AM;
659 if (!X86SelectAddress(I->getOperand(1), AM))
660 return false;
662 return X86FastEmitStore(VT, I->getOperand(0), AM);
665 /// X86SelectRet - Select and emit code to implement ret instructions.
666 bool X86FastISel::X86SelectRet(const Instruction *I) {
667 const ReturnInst *Ret = cast<ReturnInst>(I);
668 const Function &F = *I->getParent()->getParent();
670 if (!FuncInfo.CanLowerReturn)
671 return false;
673 CallingConv::ID CC = F.getCallingConv();
674 if (CC != CallingConv::C &&
675 CC != CallingConv::Fast &&
676 CC != CallingConv::X86_FastCall)
677 return false;
679 if (Subtarget->isTargetWin64())
680 return false;
682 // Don't handle popping bytes on return for now.
683 if (FuncInfo.MF->getInfo<X86MachineFunctionInfo>()
684 ->getBytesToPopOnReturn() != 0)
685 return 0;
687 // fastcc with -tailcallopt is intended to provide a guaranteed
688 // tail call optimization. Fastisel doesn't know how to do that.
689 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
690 return false;
692 // Let SDISel handle vararg functions.
693 if (F.isVarArg())
694 return false;
696 if (Ret->getNumOperands() > 0) {
697 SmallVector<ISD::OutputArg, 4> Outs;
698 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
699 Outs, TLI);
701 // Analyze operands of the call, assigning locations to each operand.
702 SmallVector<CCValAssign, 16> ValLocs;
703 CCState CCInfo(CC, F.isVarArg(), TM, ValLocs, I->getContext());
704 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
706 const Value *RV = Ret->getOperand(0);
707 unsigned Reg = getRegForValue(RV);
708 if (Reg == 0)
709 return false;
711 // Only handle a single return value for now.
712 if (ValLocs.size() != 1)
713 return false;
715 CCValAssign &VA = ValLocs[0];
717 // Don't bother handling odd stuff for now.
718 if (VA.getLocInfo() != CCValAssign::Full)
719 return false;
720 // Only handle register returns for now.
721 if (!VA.isRegLoc())
722 return false;
723 // TODO: For now, don't try to handle cases where getLocInfo()
724 // says Full but the types don't match.
725 if (TLI.getValueType(RV->getType()) != VA.getValVT())
726 return false;
728 // The calling-convention tables for x87 returns don't tell
729 // the whole story.
730 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
731 return false;
733 // Make the copy.
734 unsigned SrcReg = Reg + VA.getValNo();
735 unsigned DstReg = VA.getLocReg();
736 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
737 // Avoid a cross-class copy. This is very unlikely.
738 if (!SrcRC->contains(DstReg))
739 return false;
740 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
741 DstReg).addReg(SrcReg);
743 // Mark the register as live out of the function.
744 MRI.addLiveOut(VA.getLocReg());
747 // Now emit the RET.
748 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
749 return true;
752 /// X86SelectLoad - Select and emit code to implement load instructions.
754 bool X86FastISel::X86SelectLoad(const Instruction *I) {
755 MVT VT;
756 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
757 return false;
759 X86AddressMode AM;
760 if (!X86SelectAddress(I->getOperand(0), AM))
761 return false;
763 unsigned ResultReg = 0;
764 if (X86FastEmitLoad(VT, AM, ResultReg)) {
765 UpdateValueMap(I, ResultReg);
766 return true;
768 return false;
771 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
772 switch (VT.getSimpleVT().SimpleTy) {
773 default: return 0;
774 case MVT::i8: return X86::CMP8rr;
775 case MVT::i16: return X86::CMP16rr;
776 case MVT::i32: return X86::CMP32rr;
777 case MVT::i64: return X86::CMP64rr;
778 case MVT::f32: return Subtarget->hasSSE1() ? X86::UCOMISSrr : 0;
779 case MVT::f64: return Subtarget->hasSSE2() ? X86::UCOMISDrr : 0;
783 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
784 /// of the comparison, return an opcode that works for the compare (e.g.
785 /// CMP32ri) otherwise return 0.
786 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
787 switch (VT.getSimpleVT().SimpleTy) {
788 // Otherwise, we can't fold the immediate into this comparison.
789 default: return 0;
790 case MVT::i8: return X86::CMP8ri;
791 case MVT::i16: return X86::CMP16ri;
792 case MVT::i32: return X86::CMP32ri;
793 case MVT::i64:
794 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
795 // field.
796 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
797 return X86::CMP64ri32;
798 return 0;
802 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
803 EVT VT) {
804 unsigned Op0Reg = getRegForValue(Op0);
805 if (Op0Reg == 0) return false;
807 // Handle 'null' like i32/i64 0.
808 if (isa<ConstantPointerNull>(Op1))
809 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
811 // We have two options: compare with register or immediate. If the RHS of
812 // the compare is an immediate that we can fold into this compare, use
813 // CMPri, otherwise use CMPrr.
814 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
815 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
816 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
817 .addReg(Op0Reg)
818 .addImm(Op1C->getSExtValue());
819 return true;
823 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
824 if (CompareOpc == 0) return false;
826 unsigned Op1Reg = getRegForValue(Op1);
827 if (Op1Reg == 0) return false;
828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
829 .addReg(Op0Reg)
830 .addReg(Op1Reg);
832 return true;
835 bool X86FastISel::X86SelectCmp(const Instruction *I) {
836 const CmpInst *CI = cast<CmpInst>(I);
838 MVT VT;
839 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
840 return false;
842 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
843 unsigned SetCCOpc;
844 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
845 switch (CI->getPredicate()) {
846 case CmpInst::FCMP_OEQ: {
847 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
848 return false;
850 unsigned EReg = createResultReg(&X86::GR8RegClass);
851 unsigned NPReg = createResultReg(&X86::GR8RegClass);
852 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
853 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
854 TII.get(X86::SETNPr), NPReg);
855 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
856 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
857 UpdateValueMap(I, ResultReg);
858 return true;
860 case CmpInst::FCMP_UNE: {
861 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
862 return false;
864 unsigned NEReg = createResultReg(&X86::GR8RegClass);
865 unsigned PReg = createResultReg(&X86::GR8RegClass);
866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
867 TII.get(X86::SETNEr), NEReg);
868 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
869 TII.get(X86::SETPr), PReg);
870 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
871 TII.get(X86::OR8rr), ResultReg)
872 .addReg(PReg).addReg(NEReg);
873 UpdateValueMap(I, ResultReg);
874 return true;
876 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
877 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
878 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
879 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
880 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
881 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
882 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
883 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
884 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
885 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
886 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
887 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
889 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
890 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
891 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
892 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
893 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
894 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
895 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
896 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
897 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
898 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
899 default:
900 return false;
903 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
904 if (SwapArgs)
905 std::swap(Op0, Op1);
907 // Emit a compare of Op0/Op1.
908 if (!X86FastEmitCompare(Op0, Op1, VT))
909 return false;
911 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
912 UpdateValueMap(I, ResultReg);
913 return true;
916 bool X86FastISel::X86SelectZExt(const Instruction *I) {
917 // Handle zero-extension from i1 to i8, which is common.
918 if (I->getType()->isIntegerTy(8) &&
919 I->getOperand(0)->getType()->isIntegerTy(1)) {
920 unsigned ResultReg = getRegForValue(I->getOperand(0));
921 if (ResultReg == 0) return false;
922 // Set the high bits to zero.
923 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
924 if (ResultReg == 0) return false;
925 UpdateValueMap(I, ResultReg);
926 return true;
929 return false;
933 bool X86FastISel::X86SelectBranch(const Instruction *I) {
934 // Unconditional branches are selected by tablegen-generated code.
935 // Handle a conditional branch.
936 const BranchInst *BI = cast<BranchInst>(I);
937 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
938 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
940 // Fold the common case of a conditional branch with a comparison
941 // in the same block (values defined on other blocks may not have
942 // initialized registers).
943 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
944 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
945 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
947 // Try to take advantage of fallthrough opportunities.
948 CmpInst::Predicate Predicate = CI->getPredicate();
949 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
950 std::swap(TrueMBB, FalseMBB);
951 Predicate = CmpInst::getInversePredicate(Predicate);
954 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
955 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
957 switch (Predicate) {
958 case CmpInst::FCMP_OEQ:
959 std::swap(TrueMBB, FalseMBB);
960 Predicate = CmpInst::FCMP_UNE;
961 // FALL THROUGH
962 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
963 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
964 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
965 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
966 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
967 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
968 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
969 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
970 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
971 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
972 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
973 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
974 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
976 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
977 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
978 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
979 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
980 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
981 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
982 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
983 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
984 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
985 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
986 default:
987 return false;
990 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
991 if (SwapArgs)
992 std::swap(Op0, Op1);
994 // Emit a compare of the LHS and RHS, setting the flags.
995 if (!X86FastEmitCompare(Op0, Op1, VT))
996 return false;
998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
999 .addMBB(TrueMBB);
1001 if (Predicate == CmpInst::FCMP_UNE) {
1002 // X86 requires a second branch to handle UNE (and OEQ,
1003 // which is mapped to UNE above).
1004 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1005 .addMBB(TrueMBB);
1008 FastEmitBranch(FalseMBB, DL);
1009 FuncInfo.MBB->addSuccessor(TrueMBB);
1010 return true;
1012 } else if (ExtractValueInst *EI =
1013 dyn_cast<ExtractValueInst>(BI->getCondition())) {
1014 // Check to see if the branch instruction is from an "arithmetic with
1015 // overflow" intrinsic. The main way these intrinsics are used is:
1017 // %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
1018 // %sum = extractvalue { i32, i1 } %t, 0
1019 // %obit = extractvalue { i32, i1 } %t, 1
1020 // br i1 %obit, label %overflow, label %normal
1022 // The %sum and %obit are converted in an ADD and a SETO/SETB before
1023 // reaching the branch. Therefore, we search backwards through the MBB
1024 // looking for the SETO/SETB instruction. If an instruction modifies the
1025 // EFLAGS register before we reach the SETO/SETB instruction, then we can't
1026 // convert the branch into a JO/JB instruction.
1027 if (const IntrinsicInst *CI =
1028 dyn_cast<IntrinsicInst>(EI->getAggregateOperand())){
1029 if (CI->getIntrinsicID() == Intrinsic::sadd_with_overflow ||
1030 CI->getIntrinsicID() == Intrinsic::uadd_with_overflow) {
1031 const MachineInstr *SetMI = 0;
1032 unsigned Reg = getRegForValue(EI);
1034 for (MachineBasicBlock::const_reverse_iterator
1035 RI = FuncInfo.MBB->rbegin(), RE = FuncInfo.MBB->rend();
1036 RI != RE; ++RI) {
1037 const MachineInstr &MI = *RI;
1039 if (MI.definesRegister(Reg)) {
1040 if (MI.isCopy()) {
1041 Reg = MI.getOperand(1).getReg();
1042 continue;
1045 SetMI = &MI;
1046 break;
1049 const TargetInstrDesc &TID = MI.getDesc();
1050 if (TID.hasImplicitDefOfPhysReg(X86::EFLAGS) ||
1051 MI.hasUnmodeledSideEffects())
1052 break;
1055 if (SetMI) {
1056 unsigned OpCode = SetMI->getOpcode();
1058 if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
1059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1060 TII.get(OpCode == X86::SETOr ? X86::JO_4 : X86::JB_4))
1061 .addMBB(TrueMBB);
1062 FastEmitBranch(FalseMBB, DL);
1063 FuncInfo.MBB->addSuccessor(TrueMBB);
1064 return true;
1071 // Otherwise do a clumsy setcc and re-test it.
1072 unsigned OpReg = getRegForValue(BI->getCondition());
1073 if (OpReg == 0) return false;
1075 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1076 .addReg(OpReg).addReg(OpReg);
1077 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1078 .addMBB(TrueMBB);
1079 FastEmitBranch(FalseMBB, DL);
1080 FuncInfo.MBB->addSuccessor(TrueMBB);
1081 return true;
1084 bool X86FastISel::X86SelectShift(const Instruction *I) {
1085 unsigned CReg = 0, OpReg = 0, OpImm = 0;
1086 const TargetRegisterClass *RC = NULL;
1087 if (I->getType()->isIntegerTy(8)) {
1088 CReg = X86::CL;
1089 RC = &X86::GR8RegClass;
1090 switch (I->getOpcode()) {
1091 case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
1092 case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
1093 case Instruction::Shl: OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
1094 default: return false;
1096 } else if (I->getType()->isIntegerTy(16)) {
1097 CReg = X86::CX;
1098 RC = &X86::GR16RegClass;
1099 switch (I->getOpcode()) {
1100 case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
1101 case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
1102 case Instruction::Shl: OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
1103 default: return false;
1105 } else if (I->getType()->isIntegerTy(32)) {
1106 CReg = X86::ECX;
1107 RC = &X86::GR32RegClass;
1108 switch (I->getOpcode()) {
1109 case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
1110 case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
1111 case Instruction::Shl: OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
1112 default: return false;
1114 } else if (I->getType()->isIntegerTy(64)) {
1115 CReg = X86::RCX;
1116 RC = &X86::GR64RegClass;
1117 switch (I->getOpcode()) {
1118 case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
1119 case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
1120 case Instruction::Shl: OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
1121 default: return false;
1123 } else {
1124 return false;
1127 MVT VT;
1128 if (!isTypeLegal(I->getType(), VT))
1129 return false;
1131 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1132 if (Op0Reg == 0) return false;
1134 // Fold immediate in shl(x,3).
1135 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136 unsigned ResultReg = createResultReg(RC);
1137 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpImm),
1138 ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
1139 UpdateValueMap(I, ResultReg);
1140 return true;
1143 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1144 if (Op1Reg == 0) return false;
1145 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1146 CReg).addReg(Op1Reg);
1148 // The shift instruction uses X86::CL. If we defined a super-register
1149 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1150 if (CReg != X86::CL)
1151 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1152 TII.get(TargetOpcode::KILL), X86::CL)
1153 .addReg(CReg, RegState::Kill);
1155 unsigned ResultReg = createResultReg(RC);
1156 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1157 .addReg(Op0Reg);
1158 UpdateValueMap(I, ResultReg);
1159 return true;
1162 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1163 MVT VT;
1164 if (!isTypeLegal(I->getType(), VT))
1165 return false;
1167 // We only use cmov here, if we don't have a cmov instruction bail.
1168 if (!Subtarget->hasCMov()) return false;
1170 unsigned Opc = 0;
1171 const TargetRegisterClass *RC = NULL;
1172 if (VT == MVT::i16) {
1173 Opc = X86::CMOVE16rr;
1174 RC = &X86::GR16RegClass;
1175 } else if (VT == MVT::i32) {
1176 Opc = X86::CMOVE32rr;
1177 RC = &X86::GR32RegClass;
1178 } else if (VT == MVT::i64) {
1179 Opc = X86::CMOVE64rr;
1180 RC = &X86::GR64RegClass;
1181 } else {
1182 return false;
1185 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1186 if (Op0Reg == 0) return false;
1187 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1188 if (Op1Reg == 0) return false;
1189 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1190 if (Op2Reg == 0) return false;
1192 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1193 .addReg(Op0Reg).addReg(Op0Reg);
1194 unsigned ResultReg = createResultReg(RC);
1195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1196 .addReg(Op1Reg).addReg(Op2Reg);
1197 UpdateValueMap(I, ResultReg);
1198 return true;
1201 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1202 // fpext from float to double.
1203 if (Subtarget->hasSSE2() &&
1204 I->getType()->isDoubleTy()) {
1205 const Value *V = I->getOperand(0);
1206 if (V->getType()->isFloatTy()) {
1207 unsigned OpReg = getRegForValue(V);
1208 if (OpReg == 0) return false;
1209 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1210 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1211 TII.get(X86::CVTSS2SDrr), ResultReg)
1212 .addReg(OpReg);
1213 UpdateValueMap(I, ResultReg);
1214 return true;
1218 return false;
1221 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1222 if (Subtarget->hasSSE2()) {
1223 if (I->getType()->isFloatTy()) {
1224 const Value *V = I->getOperand(0);
1225 if (V->getType()->isDoubleTy()) {
1226 unsigned OpReg = getRegForValue(V);
1227 if (OpReg == 0) return false;
1228 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1229 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1230 TII.get(X86::CVTSD2SSrr), ResultReg)
1231 .addReg(OpReg);
1232 UpdateValueMap(I, ResultReg);
1233 return true;
1238 return false;
1241 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1242 if (Subtarget->is64Bit())
1243 // All other cases should be handled by the tblgen generated code.
1244 return false;
1245 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1246 EVT DstVT = TLI.getValueType(I->getType());
1248 // This code only handles truncation to byte right now.
1249 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1250 // All other cases should be handled by the tblgen generated code.
1251 return false;
1252 if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1253 // All other cases should be handled by the tblgen generated code.
1254 return false;
1256 unsigned InputReg = getRegForValue(I->getOperand(0));
1257 if (!InputReg)
1258 // Unhandled operand. Halt "fast" selection and bail.
1259 return false;
1261 // First issue a copy to GR16_ABCD or GR32_ABCD.
1262 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1263 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1264 unsigned CopyReg = createResultReg(CopyRC);
1265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1266 CopyReg).addReg(InputReg);
1268 // Then issue an extract_subreg.
1269 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1270 CopyReg, /*Kill=*/true,
1271 X86::sub_8bit);
1272 if (!ResultReg)
1273 return false;
1275 UpdateValueMap(I, ResultReg);
1276 return true;
1279 bool X86FastISel::X86SelectExtractValue(const Instruction *I) {
1280 const ExtractValueInst *EI = cast<ExtractValueInst>(I);
1281 const Value *Agg = EI->getAggregateOperand();
1283 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1284 switch (CI->getIntrinsicID()) {
1285 default: break;
1286 case Intrinsic::sadd_with_overflow:
1287 case Intrinsic::uadd_with_overflow: {
1288 // Cheat a little. We know that the registers for "add" and "seto" are
1289 // allocated sequentially. However, we only keep track of the register
1290 // for "add" in the value map. Use extractvalue's index to get the
1291 // correct register for "seto".
1292 unsigned OpReg = getRegForValue(Agg);
1293 if (OpReg == 0)
1294 return false;
1295 UpdateValueMap(I, OpReg + *EI->idx_begin());
1296 return true;
1301 return false;
1304 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1305 // FIXME: Handle more intrinsics.
1306 switch (I.getIntrinsicID()) {
1307 default: return false;
1308 case Intrinsic::stackprotector: {
1309 // Emit code inline code to store the stack guard onto the stack.
1310 EVT PtrTy = TLI.getPointerTy();
1312 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1313 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1315 // Grab the frame index.
1316 X86AddressMode AM;
1317 if (!X86SelectAddress(Slot, AM)) return false;
1319 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1321 return true;
1323 case Intrinsic::objectsize: {
1324 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
1325 const Type *Ty = I.getCalledFunction()->getReturnType();
1327 assert(CI && "Non-constant type in Intrinsic::objectsize?");
1329 MVT VT;
1330 if (!isTypeLegal(Ty, VT))
1331 return false;
1333 unsigned OpC = 0;
1334 if (VT == MVT::i32)
1335 OpC = X86::MOV32ri;
1336 else if (VT == MVT::i64)
1337 OpC = X86::MOV64ri;
1338 else
1339 return false;
1341 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg).
1343 addImm(CI->isZero() ? -1ULL : 0);
1344 UpdateValueMap(&I, ResultReg);
1345 return true;
1347 case Intrinsic::dbg_declare: {
1348 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1349 X86AddressMode AM;
1350 assert(DI->getAddress() && "Null address should be checked earlier!");
1351 if (!X86SelectAddress(DI->getAddress(), AM))
1352 return false;
1353 const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1354 // FIXME may need to add RegState::Debug to any registers produced,
1355 // although ESP/EBP should be the only ones at the moment.
1356 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1357 addImm(0).addMetadata(DI->getVariable());
1358 return true;
1360 case Intrinsic::trap: {
1361 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1362 return true;
1364 case Intrinsic::sadd_with_overflow:
1365 case Intrinsic::uadd_with_overflow: {
1366 // Replace "add with overflow" intrinsics with an "add" instruction followed
1367 // by a seto/setc instruction. Later on, when the "extractvalue"
1368 // instructions are encountered, we use the fact that two registers were
1369 // created sequentially to get the correct registers for the "sum" and the
1370 // "overflow bit".
1371 const Function *Callee = I.getCalledFunction();
1372 const Type *RetTy =
1373 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1375 MVT VT;
1376 if (!isTypeLegal(RetTy, VT))
1377 return false;
1379 const Value *Op1 = I.getArgOperand(0);
1380 const Value *Op2 = I.getArgOperand(1);
1381 unsigned Reg1 = getRegForValue(Op1);
1382 unsigned Reg2 = getRegForValue(Op2);
1384 if (Reg1 == 0 || Reg2 == 0)
1385 // FIXME: Handle values *not* in registers.
1386 return false;
1388 unsigned OpC = 0;
1389 if (VT == MVT::i32)
1390 OpC = X86::ADD32rr;
1391 else if (VT == MVT::i64)
1392 OpC = X86::ADD64rr;
1393 else
1394 return false;
1396 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1398 .addReg(Reg1).addReg(Reg2);
1399 unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1401 // If the add with overflow is an intra-block value then we just want to
1402 // create temporaries for it like normal. If it is a cross-block value then
1403 // UpdateValueMap will return the cross-block register used. Since we
1404 // *really* want the value to be live in the register pair known by
1405 // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1406 // the cross block case. In the non-cross-block case, we should just make
1407 // another register for the value.
1408 if (DestReg1 != ResultReg)
1409 ResultReg = DestReg1+1;
1410 else
1411 ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1413 unsigned Opc = X86::SETBr;
1414 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1415 Opc = X86::SETOr;
1416 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
1417 return true;
1422 bool X86FastISel::X86SelectCall(const Instruction *I) {
1423 const CallInst *CI = cast<CallInst>(I);
1424 const Value *Callee = CI->getCalledValue();
1426 // Can't handle inline asm yet.
1427 if (isa<InlineAsm>(Callee))
1428 return false;
1430 // Handle intrinsic calls.
1431 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1432 return X86VisitIntrinsicCall(*II);
1434 // Handle only C and fastcc calling conventions for now.
1435 ImmutableCallSite CS(CI);
1436 CallingConv::ID CC = CS.getCallingConv();
1437 if (CC != CallingConv::C &&
1438 CC != CallingConv::Fast &&
1439 CC != CallingConv::X86_FastCall)
1440 return false;
1442 // fastcc with -tailcallopt is intended to provide a guaranteed
1443 // tail call optimization. Fastisel doesn't know how to do that.
1444 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1445 return false;
1447 // Let SDISel handle vararg functions.
1448 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1449 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1450 if (FTy->isVarArg())
1451 return false;
1453 // Fast-isel doesn't know about callee-pop yet.
1454 if (Subtarget->IsCalleePop(FTy->isVarArg(), CC))
1455 return false;
1457 // Handle *simple* calls for now.
1458 const Type *RetTy = CS.getType();
1459 MVT RetVT;
1460 if (RetTy->isVoidTy())
1461 RetVT = MVT::isVoid;
1462 else if (!isTypeLegal(RetTy, RetVT, true))
1463 return false;
1465 // Materialize callee address in a register. FIXME: GV address can be
1466 // handled with a CALLpcrel32 instead.
1467 X86AddressMode CalleeAM;
1468 if (!X86SelectCallAddress(Callee, CalleeAM))
1469 return false;
1470 unsigned CalleeOp = 0;
1471 const GlobalValue *GV = 0;
1472 if (CalleeAM.GV != 0) {
1473 GV = CalleeAM.GV;
1474 } else if (CalleeAM.Base.Reg != 0) {
1475 CalleeOp = CalleeAM.Base.Reg;
1476 } else
1477 return false;
1479 // Allow calls which produce i1 results.
1480 bool AndToI1 = false;
1481 if (RetVT == MVT::i1) {
1482 RetVT = MVT::i8;
1483 AndToI1 = true;
1486 // Deal with call operands first.
1487 SmallVector<const Value *, 8> ArgVals;
1488 SmallVector<unsigned, 8> Args;
1489 SmallVector<MVT, 8> ArgVTs;
1490 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1491 Args.reserve(CS.arg_size());
1492 ArgVals.reserve(CS.arg_size());
1493 ArgVTs.reserve(CS.arg_size());
1494 ArgFlags.reserve(CS.arg_size());
1495 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1496 i != e; ++i) {
1497 unsigned Arg = getRegForValue(*i);
1498 if (Arg == 0)
1499 return false;
1500 ISD::ArgFlagsTy Flags;
1501 unsigned AttrInd = i - CS.arg_begin() + 1;
1502 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1503 Flags.setSExt();
1504 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1505 Flags.setZExt();
1507 // FIXME: Only handle *easy* calls for now.
1508 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1509 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1510 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1511 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1512 return false;
1514 const Type *ArgTy = (*i)->getType();
1515 MVT ArgVT;
1516 if (!isTypeLegal(ArgTy, ArgVT))
1517 return false;
1518 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1519 Flags.setOrigAlign(OriginalAlignment);
1521 Args.push_back(Arg);
1522 ArgVals.push_back(*i);
1523 ArgVTs.push_back(ArgVT);
1524 ArgFlags.push_back(Flags);
1527 // Analyze operands of the call, assigning locations to each operand.
1528 SmallVector<CCValAssign, 16> ArgLocs;
1529 CCState CCInfo(CC, false, TM, ArgLocs, I->getParent()->getContext());
1531 // Allocate shadow area for Win64
1532 if (Subtarget->isTargetWin64()) {
1533 CCInfo.AllocateStack(32, 8);
1536 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1538 // Get a count of how many bytes are to be pushed on the stack.
1539 unsigned NumBytes = CCInfo.getNextStackOffset();
1541 // Issue CALLSEQ_START
1542 unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1543 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1544 .addImm(NumBytes);
1546 // Process argument: walk the register/memloc assignments, inserting
1547 // copies / loads.
1548 SmallVector<unsigned, 4> RegArgs;
1549 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1550 CCValAssign &VA = ArgLocs[i];
1551 unsigned Arg = Args[VA.getValNo()];
1552 EVT ArgVT = ArgVTs[VA.getValNo()];
1554 // Promote the value if needed.
1555 switch (VA.getLocInfo()) {
1556 default: llvm_unreachable("Unknown loc info!");
1557 case CCValAssign::Full: break;
1558 case CCValAssign::SExt: {
1559 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1560 Arg, ArgVT, Arg);
1561 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1562 ArgVT = VA.getLocVT();
1563 break;
1565 case CCValAssign::ZExt: {
1566 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1567 Arg, ArgVT, Arg);
1568 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1569 ArgVT = VA.getLocVT();
1570 break;
1572 case CCValAssign::AExt: {
1573 // We don't handle MMX parameters yet.
1574 if (VA.getLocVT().isVector() && VA.getLocVT().getSizeInBits() == 128)
1575 return false;
1576 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1577 Arg, ArgVT, Arg);
1578 if (!Emitted)
1579 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1580 Arg, ArgVT, Arg);
1581 if (!Emitted)
1582 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1583 Arg, ArgVT, Arg);
1585 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1586 ArgVT = VA.getLocVT();
1587 break;
1589 case CCValAssign::BCvt: {
1590 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1591 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1592 assert(BC != 0 && "Failed to emit a bitcast!");
1593 Arg = BC;
1594 ArgVT = VA.getLocVT();
1595 break;
1599 if (VA.isRegLoc()) {
1600 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1601 VA.getLocReg()).addReg(Arg);
1602 RegArgs.push_back(VA.getLocReg());
1603 } else {
1604 unsigned LocMemOffset = VA.getLocMemOffset();
1605 X86AddressMode AM;
1606 AM.Base.Reg = StackPtr;
1607 AM.Disp = LocMemOffset;
1608 const Value *ArgVal = ArgVals[VA.getValNo()];
1610 // If this is a really simple value, emit this with the Value* version of
1611 // X86FastEmitStore. If it isn't simple, we don't want to do this, as it
1612 // can cause us to reevaluate the argument.
1613 if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1614 X86FastEmitStore(ArgVT, ArgVal, AM);
1615 else
1616 X86FastEmitStore(ArgVT, Arg, AM);
1620 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1621 // GOT pointer.
1622 if (Subtarget->isPICStyleGOT()) {
1623 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1625 X86::EBX).addReg(Base);
1628 // Issue the call.
1629 MachineInstrBuilder MIB;
1630 if (CalleeOp) {
1631 // Register-indirect call.
1632 unsigned CallOpc;
1633 if (Subtarget->isTargetWin64())
1634 CallOpc = X86::WINCALL64r;
1635 else if (Subtarget->is64Bit())
1636 CallOpc = X86::CALL64r;
1637 else
1638 CallOpc = X86::CALL32r;
1639 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1640 .addReg(CalleeOp);
1642 } else {
1643 // Direct call.
1644 assert(GV && "Not a direct call");
1645 unsigned CallOpc;
1646 if (Subtarget->isTargetWin64())
1647 CallOpc = X86::WINCALL64pcrel32;
1648 else if (Subtarget->is64Bit())
1649 CallOpc = X86::CALL64pcrel32;
1650 else
1651 CallOpc = X86::CALLpcrel32;
1653 // See if we need any target-specific flags on the GV operand.
1654 unsigned char OpFlags = 0;
1656 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1657 // external symbols most go through the PLT in PIC mode. If the symbol
1658 // has hidden or protected visibility, or if it is static or local, then
1659 // we don't need to use the PLT - we can directly call it.
1660 if (Subtarget->isTargetELF() &&
1661 TM.getRelocationModel() == Reloc::PIC_ &&
1662 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1663 OpFlags = X86II::MO_PLT;
1664 } else if (Subtarget->isPICStyleStubAny() &&
1665 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1666 Subtarget->getDarwinVers() < 9) {
1667 // PC-relative references to external symbols should go through $stub,
1668 // unless we're building with the leopard linker or later, which
1669 // automatically synthesizes these stubs.
1670 OpFlags = X86II::MO_DARWIN_STUB;
1674 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1675 .addGlobalAddress(GV, 0, OpFlags);
1678 // Add an implicit use GOT pointer in EBX.
1679 if (Subtarget->isPICStyleGOT())
1680 MIB.addReg(X86::EBX);
1682 // Add implicit physical register uses to the call.
1683 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1684 MIB.addReg(RegArgs[i]);
1686 // Issue CALLSEQ_END
1687 unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1689 .addImm(NumBytes).addImm(0);
1691 // Now handle call return value (if any).
1692 SmallVector<unsigned, 4> UsedRegs;
1693 if (RetVT != MVT::isVoid) {
1694 SmallVector<CCValAssign, 16> RVLocs;
1695 CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1696 CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1698 // Copy all of the result registers out of their specified physreg.
1699 assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1700 EVT CopyVT = RVLocs[0].getValVT();
1701 TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1703 // If this is a call to a function that returns an fp value on the x87 fp
1704 // stack, but where we prefer to use the value in xmm registers, copy it
1705 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1706 if ((RVLocs[0].getLocReg() == X86::ST0 ||
1707 RVLocs[0].getLocReg() == X86::ST1) &&
1708 isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1709 CopyVT = MVT::f80;
1710 DstRC = X86::RFP80RegisterClass;
1713 unsigned ResultReg = createResultReg(DstRC);
1714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1715 ResultReg).addReg(RVLocs[0].getLocReg());
1716 UsedRegs.push_back(RVLocs[0].getLocReg());
1718 if (CopyVT != RVLocs[0].getValVT()) {
1719 // Round the F80 the right size, which also moves to the appropriate xmm
1720 // register. This is accomplished by storing the F80 value in memory and
1721 // then loading it back. Ewww...
1722 EVT ResVT = RVLocs[0].getValVT();
1723 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1724 unsigned MemSize = ResVT.getSizeInBits()/8;
1725 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1726 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1727 TII.get(Opc)), FI)
1728 .addReg(ResultReg);
1729 DstRC = ResVT == MVT::f32
1730 ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1731 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1732 ResultReg = createResultReg(DstRC);
1733 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1734 TII.get(Opc), ResultReg), FI);
1737 if (AndToI1) {
1738 // Mask out all but lowest bit for some call which produces an i1.
1739 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1740 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1741 TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1742 ResultReg = AndResult;
1745 UpdateValueMap(I, ResultReg);
1748 // Set all unused physreg defs as dead.
1749 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1751 return true;
1755 bool
1756 X86FastISel::TargetSelectInstruction(const Instruction *I) {
1757 switch (I->getOpcode()) {
1758 default: break;
1759 case Instruction::Load:
1760 return X86SelectLoad(I);
1761 case Instruction::Store:
1762 return X86SelectStore(I);
1763 case Instruction::Ret:
1764 return X86SelectRet(I);
1765 case Instruction::ICmp:
1766 case Instruction::FCmp:
1767 return X86SelectCmp(I);
1768 case Instruction::ZExt:
1769 return X86SelectZExt(I);
1770 case Instruction::Br:
1771 return X86SelectBranch(I);
1772 case Instruction::Call:
1773 return X86SelectCall(I);
1774 case Instruction::LShr:
1775 case Instruction::AShr:
1776 case Instruction::Shl:
1777 return X86SelectShift(I);
1778 case Instruction::Select:
1779 return X86SelectSelect(I);
1780 case Instruction::Trunc:
1781 return X86SelectTrunc(I);
1782 case Instruction::FPExt:
1783 return X86SelectFPExt(I);
1784 case Instruction::FPTrunc:
1785 return X86SelectFPTrunc(I);
1786 case Instruction::ExtractValue:
1787 return X86SelectExtractValue(I);
1788 case Instruction::IntToPtr: // Deliberate fall-through.
1789 case Instruction::PtrToInt: {
1790 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1791 EVT DstVT = TLI.getValueType(I->getType());
1792 if (DstVT.bitsGT(SrcVT))
1793 return X86SelectZExt(I);
1794 if (DstVT.bitsLT(SrcVT))
1795 return X86SelectTrunc(I);
1796 unsigned Reg = getRegForValue(I->getOperand(0));
1797 if (Reg == 0) return false;
1798 UpdateValueMap(I, Reg);
1799 return true;
1803 return false;
1806 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
1807 MVT VT;
1808 if (!isTypeLegal(C->getType(), VT))
1809 return false;
1811 // Get opcode and regclass of the output for the given load instruction.
1812 unsigned Opc = 0;
1813 const TargetRegisterClass *RC = NULL;
1814 switch (VT.SimpleTy) {
1815 default: return false;
1816 case MVT::i8:
1817 Opc = X86::MOV8rm;
1818 RC = X86::GR8RegisterClass;
1819 break;
1820 case MVT::i16:
1821 Opc = X86::MOV16rm;
1822 RC = X86::GR16RegisterClass;
1823 break;
1824 case MVT::i32:
1825 Opc = X86::MOV32rm;
1826 RC = X86::GR32RegisterClass;
1827 break;
1828 case MVT::i64:
1829 // Must be in x86-64 mode.
1830 Opc = X86::MOV64rm;
1831 RC = X86::GR64RegisterClass;
1832 break;
1833 case MVT::f32:
1834 if (Subtarget->hasSSE1()) {
1835 Opc = X86::MOVSSrm;
1836 RC = X86::FR32RegisterClass;
1837 } else {
1838 Opc = X86::LD_Fp32m;
1839 RC = X86::RFP32RegisterClass;
1841 break;
1842 case MVT::f64:
1843 if (Subtarget->hasSSE2()) {
1844 Opc = X86::MOVSDrm;
1845 RC = X86::FR64RegisterClass;
1846 } else {
1847 Opc = X86::LD_Fp64m;
1848 RC = X86::RFP64RegisterClass;
1850 break;
1851 case MVT::f80:
1852 // No f80 support yet.
1853 return false;
1856 // Materialize addresses with LEA instructions.
1857 if (isa<GlobalValue>(C)) {
1858 X86AddressMode AM;
1859 if (X86SelectAddress(C, AM)) {
1860 if (TLI.getPointerTy() == MVT::i32)
1861 Opc = X86::LEA32r;
1862 else
1863 Opc = X86::LEA64r;
1864 unsigned ResultReg = createResultReg(RC);
1865 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1866 TII.get(Opc), ResultReg), AM);
1867 return ResultReg;
1869 return 0;
1872 // MachineConstantPool wants an explicit alignment.
1873 unsigned Align = TD.getPrefTypeAlignment(C->getType());
1874 if (Align == 0) {
1875 // Alignment of vector types. FIXME!
1876 Align = TD.getTypeAllocSize(C->getType());
1879 // x86-32 PIC requires a PIC base register for constant pools.
1880 unsigned PICBase = 0;
1881 unsigned char OpFlag = 0;
1882 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1883 OpFlag = X86II::MO_PIC_BASE_OFFSET;
1884 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1885 } else if (Subtarget->isPICStyleGOT()) {
1886 OpFlag = X86II::MO_GOTOFF;
1887 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1888 } else if (Subtarget->isPICStyleRIPRel() &&
1889 TM.getCodeModel() == CodeModel::Small) {
1890 PICBase = X86::RIP;
1893 // Create the load from the constant pool.
1894 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1895 unsigned ResultReg = createResultReg(RC);
1896 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1897 TII.get(Opc), ResultReg),
1898 MCPOffset, PICBase, OpFlag);
1900 return ResultReg;
1903 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
1904 // Fail on dynamic allocas. At this point, getRegForValue has already
1905 // checked its CSE maps, so if we're here trying to handle a dynamic
1906 // alloca, we're not going to succeed. X86SelectAddress has a
1907 // check for dynamic allocas, because it's called directly from
1908 // various places, but TargetMaterializeAlloca also needs a check
1909 // in order to avoid recursion between getRegForValue,
1910 // X86SelectAddrss, and TargetMaterializeAlloca.
1911 if (!FuncInfo.StaticAllocaMap.count(C))
1912 return 0;
1914 X86AddressMode AM;
1915 if (!X86SelectAddress(C, AM))
1916 return 0;
1917 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1918 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1919 unsigned ResultReg = createResultReg(RC);
1920 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1921 TII.get(Opc), ResultReg), AM);
1922 return ResultReg;
1925 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
1926 /// vreg is being provided by the specified load instruction. If possible,
1927 /// try to fold the load as an operand to the instruction, returning true if
1928 /// possible.
1929 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
1930 const LoadInst *LI) {
1931 X86AddressMode AM;
1932 if (!X86SelectAddress(LI->getOperand(0), AM))
1933 return false;
1935 X86InstrInfo &XII = (X86InstrInfo&)TII;
1937 unsigned Size = TD.getTypeAllocSize(LI->getType());
1938 unsigned Alignment = LI->getAlignment();
1940 SmallVector<MachineOperand, 8> AddrOps;
1941 AM.getFullAddress(AddrOps);
1943 MachineInstr *Result =
1944 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
1945 if (Result == 0) return false;
1947 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
1948 MI->eraseFromParent();
1949 return true;
1953 namespace llvm {
1954 llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
1955 return new X86FastISel(funcInfo);