add support for folding immediates into stores when they
[oota-llvm.git] / lib / Target / X86 / X86FastISel.cpp
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31
32 using namespace llvm;
33
34 class X86FastISel : public FastISel {
35   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
36   /// make the right decision when generating code for different targets.
37   const X86Subtarget *Subtarget;
38
39   /// StackPtr - Register used as the stack pointer.
40   ///
41   unsigned StackPtr;
42
43   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 
44   /// floating point ops.
45   /// When SSE is available, use it for f32 operations.
46   /// When SSE2 is available, use it for f64 operations.
47   bool X86ScalarSSEf64;
48   bool X86ScalarSSEf32;
49
50 public:
51   explicit X86FastISel(MachineFunction &mf,
52                        MachineModuleInfo *mmi,
53                        DenseMap<const Value *, unsigned> &vm,
54                        DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
55                        DenseMap<const AllocaInst *, int> &am
56 #ifndef NDEBUG
57                        , SmallSet<Instruction*, 8> &cil
58 #endif
59                        )
60     : FastISel(mf, mmi, vm, bm, am
61 #ifndef NDEBUG
62                , cil
63 #endif
64                ) {
65     Subtarget = &TM.getSubtarget<X86Subtarget>();
66     StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
67     X86ScalarSSEf64 = Subtarget->hasSSE2();
68     X86ScalarSSEf32 = Subtarget->hasSSE1();
69   }
70
71   virtual bool TargetSelectInstruction(Instruction *I);
72
73 #include "X86GenFastISel.inc"
74
75 private:
76   bool X86FastEmitCompare(Value *LHS, Value *RHS, MVT VT);
77   
78   bool X86FastEmitLoad(MVT VT, const X86AddressMode &AM, unsigned &RR);
79
80   bool X86FastEmitStore(MVT VT, Value *Val,
81                         const X86AddressMode &AM);
82   bool X86FastEmitStore(MVT VT, unsigned Val,
83                         const X86AddressMode &AM);
84
85   bool X86FastEmitExtend(ISD::NodeType Opc, MVT DstVT, unsigned Src, MVT SrcVT,
86                          unsigned &ResultReg);
87   
88   bool X86SelectAddress(Value *V, X86AddressMode &AM, bool isCall);
89
90   bool X86SelectLoad(Instruction *I);
91   
92   bool X86SelectStore(Instruction *I);
93
94   bool X86SelectCmp(Instruction *I);
95
96   bool X86SelectZExt(Instruction *I);
97
98   bool X86SelectBranch(Instruction *I);
99
100   bool X86SelectShift(Instruction *I);
101
102   bool X86SelectSelect(Instruction *I);
103
104   bool X86SelectTrunc(Instruction *I);
105  
106   bool X86SelectFPExt(Instruction *I);
107   bool X86SelectFPTrunc(Instruction *I);
108
109   bool X86SelectCall(Instruction *I);
110
111   CCAssignFn *CCAssignFnForCall(unsigned CC, bool isTailCall = false);
112
113   const X86InstrInfo *getInstrInfo() const {
114     return getTargetMachine()->getInstrInfo();
115   }
116   const X86TargetMachine *getTargetMachine() const {
117     return static_cast<const X86TargetMachine *>(&TM);
118   }
119
120   unsigned TargetMaterializeConstant(Constant *C);
121
122   unsigned TargetMaterializeAlloca(AllocaInst *C);
123
124   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
125   /// computed in an SSE register, not on the X87 floating point stack.
126   bool isScalarFPTypeInSSEReg(MVT VT) const {
127     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
128       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
129   }
130
131   bool isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1 = false);
132 };
133
134 bool X86FastISel::isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1) {
135   VT = TLI.getValueType(Ty, /*HandleUnknown=*/true);
136   if (VT == MVT::Other || !VT.isSimple())
137     // Unhandled type. Halt "fast" selection and bail.
138     return false;
139   
140   // For now, require SSE/SSE2 for performing floating-point operations,
141   // since x87 requires additional work.
142   if (VT == MVT::f64 && !X86ScalarSSEf64)
143      return false;
144   if (VT == MVT::f32 && !X86ScalarSSEf32)
145      return false;
146   // Similarly, no f80 support yet.
147   if (VT == MVT::f80)
148     return false;
149   // We only handle legal types. For example, on x86-32 the instruction
150   // selector contains all of the 64-bit instructions from x86-64,
151   // under the assumption that i64 won't be used if the target doesn't
152   // support it.
153   return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
154 }
155
156 #include "X86GenCallingConv.inc"
157
158 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
159 /// convention.
160 CCAssignFn *X86FastISel::CCAssignFnForCall(unsigned CC, bool isTaillCall) {
161   if (Subtarget->is64Bit()) {
162     if (Subtarget->isTargetWin64())
163       return CC_X86_Win64_C;
164     else if (CC == CallingConv::Fast && isTaillCall)
165       return CC_X86_64_TailCall;
166     else
167       return CC_X86_64_C;
168   }
169
170   if (CC == CallingConv::X86_FastCall)
171     return CC_X86_32_FastCall;
172   else if (CC == CallingConv::Fast)
173     return CC_X86_32_FastCC;
174   else
175     return CC_X86_32_C;
176 }
177
178 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
179 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
180 /// Return true and the result register by reference if it is possible.
181 bool X86FastISel::X86FastEmitLoad(MVT VT, const X86AddressMode &AM,
182                                   unsigned &ResultReg) {
183   // Get opcode and regclass of the output for the given load instruction.
184   unsigned Opc = 0;
185   const TargetRegisterClass *RC = NULL;
186   switch (VT.getSimpleVT()) {
187   default: return false;
188   case MVT::i8:
189     Opc = X86::MOV8rm;
190     RC  = X86::GR8RegisterClass;
191     break;
192   case MVT::i16:
193     Opc = X86::MOV16rm;
194     RC  = X86::GR16RegisterClass;
195     break;
196   case MVT::i32:
197     Opc = X86::MOV32rm;
198     RC  = X86::GR32RegisterClass;
199     break;
200   case MVT::i64:
201     // Must be in x86-64 mode.
202     Opc = X86::MOV64rm;
203     RC  = X86::GR64RegisterClass;
204     break;
205   case MVT::f32:
206     if (Subtarget->hasSSE1()) {
207       Opc = X86::MOVSSrm;
208       RC  = X86::FR32RegisterClass;
209     } else {
210       Opc = X86::LD_Fp32m;
211       RC  = X86::RFP32RegisterClass;
212     }
213     break;
214   case MVT::f64:
215     if (Subtarget->hasSSE2()) {
216       Opc = X86::MOVSDrm;
217       RC  = X86::FR64RegisterClass;
218     } else {
219       Opc = X86::LD_Fp64m;
220       RC  = X86::RFP64RegisterClass;
221     }
222     break;
223   case MVT::f80:
224     // No f80 support yet.
225     return false;
226   }
227
228   ResultReg = createResultReg(RC);
229   addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
230   return true;
231 }
232
233 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
234 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
235 /// and a displacement offset, or a GlobalAddress,
236 /// i.e. V. Return true if it is possible.
237 bool
238 X86FastISel::X86FastEmitStore(MVT VT, unsigned Val,
239                               const X86AddressMode &AM) {
240   // Get opcode and regclass of the output for the given store instruction.
241   unsigned Opc = 0;
242   switch (VT.getSimpleVT()) {
243   case MVT::f80: // No f80 support yet.
244   default: return false;
245   case MVT::i8:  Opc = X86::MOV8mr;  break;
246   case MVT::i16: Opc = X86::MOV16mr; break;
247   case MVT::i32: Opc = X86::MOV32mr; break;
248   case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
249   case MVT::f32:
250     Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
251     break;
252   case MVT::f64:
253     Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
254     break;
255   }
256   
257   addFullAddress(BuildMI(MBB, TII.get(Opc)), AM).addReg(Val);
258   return true;
259 }
260
261 bool X86FastISel::X86FastEmitStore(MVT VT, Value *Val,
262                                    const X86AddressMode &AM) {
263   // Handle 'null' like i32/i64 0.
264   if (isa<ConstantPointerNull>(Val))
265     Val = Constant::getNullValue(TD.getIntPtrType());
266   
267   // If this is a store of a simple constant, fold the constant into the store.
268   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
269     unsigned Opc = 0;
270     switch (VT.getSimpleVT()) {
271     default: break;
272     case MVT::i8:  Opc = X86::MOV8mi;  break;
273     case MVT::i16: Opc = X86::MOV16mi; break;
274     case MVT::i32: Opc = X86::MOV32mi; break;
275     case MVT::i64:
276       // Must be a 32-bit sign extended value.
277       if ((int)CI->getSExtValue() == CI->getSExtValue())
278         Opc = X86::MOV64mi32;
279       break;
280     }
281     
282     if (Opc) {
283       addFullAddress(BuildMI(MBB, TII.get(Opc)), AM).addImm(CI->getSExtValue());
284       return true;
285     }
286   }
287   
288   unsigned ValReg = getRegForValue(Val);
289   if (ValReg == 0)
290     return false;    
291  
292   return X86FastEmitStore(VT, ValReg, AM);
293 }
294
295
296
297 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
298 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
299 /// ISD::SIGN_EXTEND).
300 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, MVT DstVT,
301                                     unsigned Src, MVT SrcVT,
302                                     unsigned &ResultReg) {
303   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
304   
305   if (RR != 0) {
306     ResultReg = RR;
307     return true;
308   } else
309     return false;
310 }
311
312 /// X86SelectAddress - Attempt to fill in an address from the given value.
313 ///
314 bool X86FastISel::X86SelectAddress(Value *V, X86AddressMode &AM, bool isCall) {
315   User *U;
316   unsigned Opcode = Instruction::UserOp1;
317   if (Instruction *I = dyn_cast<Instruction>(V)) {
318     Opcode = I->getOpcode();
319     U = I;
320   } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
321     Opcode = C->getOpcode();
322     U = C;
323   }
324
325   switch (Opcode) {
326   default: break;
327   case Instruction::BitCast:
328     // Look past bitcasts.
329     return X86SelectAddress(U->getOperand(0), AM, isCall);
330
331   case Instruction::IntToPtr:
332     // Look past no-op inttoptrs.
333     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
334       return X86SelectAddress(U->getOperand(0), AM, isCall);
335
336   case Instruction::PtrToInt:
337     // Look past no-op ptrtoints.
338     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
339       return X86SelectAddress(U->getOperand(0), AM, isCall);
340
341   case Instruction::Alloca: {
342     if (isCall) break;
343     // Do static allocas.
344     const AllocaInst *A = cast<AllocaInst>(V);
345     DenseMap<const AllocaInst*, int>::iterator SI = StaticAllocaMap.find(A);
346     if (SI != StaticAllocaMap.end()) {
347       AM.BaseType = X86AddressMode::FrameIndexBase;
348       AM.Base.FrameIndex = SI->second;
349       return true;
350     }
351     break;
352   }
353
354   case Instruction::Add: {
355     if (isCall) break;
356     // Adds of constants are common and easy enough.
357     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
358       uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
359       // They have to fit in the 32-bit signed displacement field though.
360       if (isInt32(Disp)) {
361         AM.Disp = (uint32_t)Disp;
362         return X86SelectAddress(U->getOperand(0), AM, isCall);
363       }
364     }
365     break;
366   }
367
368   case Instruction::GetElementPtr: {
369     if (isCall) break;
370     // Pattern-match simple GEPs.
371     uint64_t Disp = (int32_t)AM.Disp;
372     unsigned IndexReg = AM.IndexReg;
373     unsigned Scale = AM.Scale;
374     gep_type_iterator GTI = gep_type_begin(U);
375     // Look at all but the last index. Constants can be folded,
376     // and one dynamic index can be handled, if the scale is supported.
377     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end();
378          i != e; ++i, ++GTI) {
379       Value *Op = *i;
380       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
381         const StructLayout *SL = TD.getStructLayout(STy);
382         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
383         Disp += SL->getElementOffset(Idx);
384       } else {
385         uint64_t S = TD.getABITypeSize(GTI.getIndexedType());
386         if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
387           // Constant-offset addressing.
388           Disp += CI->getSExtValue() * S;
389         } else if (IndexReg == 0 &&
390                    (!AM.GV ||
391                     !getTargetMachine()->symbolicAddressesAreRIPRel()) &&
392                    (S == 1 || S == 2 || S == 4 || S == 8)) {
393           // Scaled-index addressing.
394           Scale = S;
395           IndexReg = getRegForValue(Op);
396           if (IndexReg == 0)
397             return false;
398         } else
399           // Unsupported.
400           goto unsupported_gep;
401       }
402     }
403     // Check for displacement overflow.
404     if (!isInt32(Disp))
405       break;
406     // Ok, the GEP indices were covered by constant-offset and scaled-index
407     // addressing. Update the address state and move on to examining the base.
408     AM.IndexReg = IndexReg;
409     AM.Scale = Scale;
410     AM.Disp = (uint32_t)Disp;
411     return X86SelectAddress(U->getOperand(0), AM, isCall);
412   unsupported_gep:
413     // Ok, the GEP indices weren't all covered.
414     break;
415   }
416   }
417
418   // Handle constant address.
419   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
420     // Can't handle alternate code models yet.
421     if (TM.getCodeModel() != CodeModel::Default &&
422         TM.getCodeModel() != CodeModel::Small)
423       return false;
424
425     // RIP-relative addresses can't have additional register operands.
426     if (getTargetMachine()->symbolicAddressesAreRIPRel() &&
427         (AM.Base.Reg != 0 || AM.IndexReg != 0))
428       return false;
429
430     // Set up the basic address.
431     AM.GV = GV;
432     if (!isCall &&
433         TM.getRelocationModel() == Reloc::PIC_ &&
434         !Subtarget->is64Bit())
435       AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(&MF);
436
437     // Emit an extra load if the ABI requires it.
438     if (Subtarget->GVRequiresExtraLoad(GV, TM, isCall)) {
439       // Check to see if we've already materialized this
440       // value in a register in this block.
441       if (unsigned Reg = LocalValueMap[V]) {
442         AM.Base.Reg = Reg;
443         AM.GV = 0;
444         return true;
445       }
446       // Issue load from stub if necessary.
447       unsigned Opc = 0;
448       const TargetRegisterClass *RC = NULL;
449       if (TLI.getPointerTy() == MVT::i32) {
450         Opc = X86::MOV32rm;
451         RC  = X86::GR32RegisterClass;
452       } else {
453         Opc = X86::MOV64rm;
454         RC  = X86::GR64RegisterClass;
455       }
456
457       X86AddressMode StubAM;
458       StubAM.Base.Reg = AM.Base.Reg;
459       StubAM.GV = AM.GV;
460       unsigned ResultReg = createResultReg(RC);
461       addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), StubAM);
462
463       // Now construct the final address. Note that the Disp, Scale,
464       // and Index values may already be set here.
465       AM.Base.Reg = ResultReg;
466       AM.GV = 0;
467
468       // Prevent loading GV stub multiple times in same MBB.
469       LocalValueMap[V] = AM.Base.Reg;
470     }
471     return true;
472   }
473
474   // If all else fails, try to materialize the value in a register.
475   if (!AM.GV || !getTargetMachine()->symbolicAddressesAreRIPRel()) {
476     if (AM.Base.Reg == 0) {
477       AM.Base.Reg = getRegForValue(V);
478       return AM.Base.Reg != 0;
479     }
480     if (AM.IndexReg == 0) {
481       assert(AM.Scale == 1 && "Scale with no index!");
482       AM.IndexReg = getRegForValue(V);
483       return AM.IndexReg != 0;
484     }
485   }
486
487   return false;
488 }
489
490 /// X86SelectStore - Select and emit code to implement store instructions.
491 bool X86FastISel::X86SelectStore(Instruction* I) {
492   MVT VT;
493   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
494     return false;
495
496   X86AddressMode AM;
497   if (!X86SelectAddress(I->getOperand(1), AM, false))
498     return false;
499
500   return X86FastEmitStore(VT, I->getOperand(0), AM);
501 }
502
503 /// X86SelectLoad - Select and emit code to implement load instructions.
504 ///
505 bool X86FastISel::X86SelectLoad(Instruction *I)  {
506   MVT VT;
507   if (!isTypeLegal(I->getType(), VT))
508     return false;
509
510   X86AddressMode AM;
511   if (!X86SelectAddress(I->getOperand(0), AM, false))
512     return false;
513
514   unsigned ResultReg = 0;
515   if (X86FastEmitLoad(VT, AM, ResultReg)) {
516     UpdateValueMap(I, ResultReg);
517     return true;
518   }
519   return false;
520 }
521
522 static unsigned X86ChooseCmpOpcode(MVT VT) {
523   switch (VT.getSimpleVT()) {
524   default:       return 0;
525   case MVT::i8:  return X86::CMP8rr;
526   case MVT::i16: return X86::CMP16rr;
527   case MVT::i32: return X86::CMP32rr;
528   case MVT::i64: return X86::CMP64rr;
529   case MVT::f32: return X86::UCOMISSrr;
530   case MVT::f64: return X86::UCOMISDrr;
531   }
532 }
533
534 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
535 /// of the comparison, return an opcode that works for the compare (e.g.
536 /// CMP32ri) otherwise return 0.
537 static unsigned X86ChooseCmpImmediateOpcode(MVT VT, ConstantInt *RHSC) {
538   switch (VT.getSimpleVT()) {
539   // Otherwise, we can't fold the immediate into this comparison.
540   default: return 0;
541   case MVT::i8: return X86::CMP8ri;
542   case MVT::i16: return X86::CMP16ri;
543   case MVT::i32: return X86::CMP32ri;
544   case MVT::i64:
545     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
546     // field.
547     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
548       return X86::CMP64ri32;
549     return 0;
550   }
551 }
552
553 bool X86FastISel::X86FastEmitCompare(Value *Op0, Value *Op1, MVT VT) {
554   unsigned Op0Reg = getRegForValue(Op0);
555   if (Op0Reg == 0) return false;
556   
557   // Handle 'null' like i32/i64 0.
558   if (isa<ConstantPointerNull>(Op1))
559     Op1 = Constant::getNullValue(TD.getIntPtrType());
560   
561   // We have two options: compare with register or immediate.  If the RHS of
562   // the compare is an immediate that we can fold into this compare, use
563   // CMPri, otherwise use CMPrr.
564   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
565     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
566       BuildMI(MBB, TII.get(CompareImmOpc)).addReg(Op0Reg)
567                                           .addImm(Op1C->getSExtValue());
568       return true;
569     }
570   }
571   
572   unsigned CompareOpc = X86ChooseCmpOpcode(VT);
573   if (CompareOpc == 0) return false;
574     
575   unsigned Op1Reg = getRegForValue(Op1);
576   if (Op1Reg == 0) return false;
577   BuildMI(MBB, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
578   
579   return true;
580 }
581
582 bool X86FastISel::X86SelectCmp(Instruction *I) {
583   CmpInst *CI = cast<CmpInst>(I);
584
585   MVT VT;
586   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
587     return false;
588
589   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
590   unsigned SetCCOpc;
591   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
592   switch (CI->getPredicate()) {
593   case CmpInst::FCMP_OEQ: {
594     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
595       return false;
596     
597     unsigned EReg = createResultReg(&X86::GR8RegClass);
598     unsigned NPReg = createResultReg(&X86::GR8RegClass);
599     BuildMI(MBB, TII.get(X86::SETEr), EReg);
600     BuildMI(MBB, TII.get(X86::SETNPr), NPReg);
601     BuildMI(MBB, TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
602     UpdateValueMap(I, ResultReg);
603     return true;
604   }
605   case CmpInst::FCMP_UNE: {
606     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
607       return false;
608
609     unsigned NEReg = createResultReg(&X86::GR8RegClass);
610     unsigned PReg = createResultReg(&X86::GR8RegClass);
611     BuildMI(MBB, TII.get(X86::SETNEr), NEReg);
612     BuildMI(MBB, TII.get(X86::SETPr), PReg);
613     BuildMI(MBB, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
614     UpdateValueMap(I, ResultReg);
615     return true;
616   }
617   case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
618   case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
619   case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
620   case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
621   case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
622   case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
623   case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
624   case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
625   case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
626   case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
627   case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
628   case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
629   
630   case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
631   case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
632   case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
633   case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
634   case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
635   case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
636   case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
637   case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
638   case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
639   case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
640   default:
641     return false;
642   }
643
644   Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
645   if (SwapArgs)
646     std::swap(Op0, Op1);
647
648   // Emit a compare of Op0/Op1.
649   if (!X86FastEmitCompare(Op0, Op1, VT))
650     return false;
651   
652   BuildMI(MBB, TII.get(SetCCOpc), ResultReg);
653   UpdateValueMap(I, ResultReg);
654   return true;
655 }
656
657 bool X86FastISel::X86SelectZExt(Instruction *I) {
658   // Special-case hack: The only i1 values we know how to produce currently
659   // set the upper bits of an i8 value to zero.
660   if (I->getType() == Type::Int8Ty &&
661       I->getOperand(0)->getType() == Type::Int1Ty) {
662     unsigned ResultReg = getRegForValue(I->getOperand(0));
663     if (ResultReg == 0) return false;
664     UpdateValueMap(I, ResultReg);
665     return true;
666   }
667
668   return false;
669 }
670
671
672 bool X86FastISel::X86SelectBranch(Instruction *I) {
673   // Unconditional branches are selected by tablegen-generated code.
674   // Handle a conditional branch.
675   BranchInst *BI = cast<BranchInst>(I);
676   MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
677   MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
678
679   // Fold the common case of a conditional branch with a comparison.
680   if (CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
681     if (CI->hasOneUse()) {
682       MVT VT = TLI.getValueType(CI->getOperand(0)->getType());
683
684       // Try to take advantage of fallthrough opportunities.
685       CmpInst::Predicate Predicate = CI->getPredicate();
686       if (MBB->isLayoutSuccessor(TrueMBB)) {
687         std::swap(TrueMBB, FalseMBB);
688         Predicate = CmpInst::getInversePredicate(Predicate);
689       }
690
691       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
692       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
693
694       switch (Predicate) {
695       case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA;  break;
696       case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE; break;
697       case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA;  break;
698       case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE; break;
699       case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE; break;
700       case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP; break;
701       case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP;  break;
702       case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE;  break;
703       case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB;  break;
704       case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE; break;
705       case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB;  break;
706       case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
707           
708       case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE;  break;
709       case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE; break;
710       case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA;  break;
711       case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE; break;
712       case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB;  break;
713       case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
714       case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG;  break;
715       case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE; break;
716       case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL;  break;
717       case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE; break;
718       default:
719         return false;
720       }
721       
722       Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
723       if (SwapArgs)
724         std::swap(Op0, Op1);
725
726       // Emit a compare of the LHS and RHS, setting the flags.
727       if (!X86FastEmitCompare(Op0, Op1, VT))
728         return false;
729       
730       BuildMI(MBB, TII.get(BranchOpc)).addMBB(TrueMBB);
731       FastEmitBranch(FalseMBB);
732       MBB->addSuccessor(TrueMBB);
733       return true;
734     }
735   }
736
737   // Otherwise do a clumsy setcc and re-test it.
738   unsigned OpReg = getRegForValue(BI->getCondition());
739   if (OpReg == 0) return false;
740
741   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
742   BuildMI(MBB, TII.get(X86::JNE)).addMBB(TrueMBB);
743   FastEmitBranch(FalseMBB);
744   MBB->addSuccessor(TrueMBB);
745   return true;
746 }
747
748 bool X86FastISel::X86SelectShift(Instruction *I) {
749   unsigned CReg = 0, OpReg = 0, OpImm = 0;
750   const TargetRegisterClass *RC = NULL;
751   if (I->getType() == Type::Int8Ty) {
752     CReg = X86::CL;
753     RC = &X86::GR8RegClass;
754     switch (I->getOpcode()) {
755     case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
756     case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
757     case Instruction::Shl:  OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
758     default: return false;
759     }
760   } else if (I->getType() == Type::Int16Ty) {
761     CReg = X86::CX;
762     RC = &X86::GR16RegClass;
763     switch (I->getOpcode()) {
764     case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
765     case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
766     case Instruction::Shl:  OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
767     default: return false;
768     }
769   } else if (I->getType() == Type::Int32Ty) {
770     CReg = X86::ECX;
771     RC = &X86::GR32RegClass;
772     switch (I->getOpcode()) {
773     case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
774     case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
775     case Instruction::Shl:  OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
776     default: return false;
777     }
778   } else if (I->getType() == Type::Int64Ty) {
779     CReg = X86::RCX;
780     RC = &X86::GR64RegClass;
781     switch (I->getOpcode()) {
782     case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
783     case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
784     case Instruction::Shl:  OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
785     default: return false;
786     }
787   } else {
788     return false;
789   }
790
791   MVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
792   if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
793     return false;
794
795   unsigned Op0Reg = getRegForValue(I->getOperand(0));
796   if (Op0Reg == 0) return false;
797   
798   // Fold immediate in shl(x,3).
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
800     unsigned ResultReg = createResultReg(RC);
801     BuildMI(MBB, TII.get(OpImm), 
802             ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue());
803     UpdateValueMap(I, ResultReg);
804     return true;
805   }
806   
807   unsigned Op1Reg = getRegForValue(I->getOperand(1));
808   if (Op1Reg == 0) return false;
809   TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
810
811   // The shift instruction uses X86::CL. If we defined a super-register
812   // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
813   // we're doing here.
814   if (CReg != X86::CL)
815     BuildMI(MBB, TII.get(TargetInstrInfo::EXTRACT_SUBREG), X86::CL)
816       .addReg(CReg).addImm(X86::SUBREG_8BIT);
817
818   unsigned ResultReg = createResultReg(RC);
819   BuildMI(MBB, TII.get(OpReg), ResultReg).addReg(Op0Reg);
820   UpdateValueMap(I, ResultReg);
821   return true;
822 }
823
824 bool X86FastISel::X86SelectSelect(Instruction *I) {
825   MVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
826   if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
827     return false;
828   
829   unsigned Opc = 0;
830   const TargetRegisterClass *RC = NULL;
831   if (VT.getSimpleVT() == MVT::i16) {
832     Opc = X86::CMOVE16rr;
833     RC = &X86::GR16RegClass;
834   } else if (VT.getSimpleVT() == MVT::i32) {
835     Opc = X86::CMOVE32rr;
836     RC = &X86::GR32RegClass;
837   } else if (VT.getSimpleVT() == MVT::i64) {
838     Opc = X86::CMOVE64rr;
839     RC = &X86::GR64RegClass;
840   } else {
841     return false; 
842   }
843
844   unsigned Op0Reg = getRegForValue(I->getOperand(0));
845   if (Op0Reg == 0) return false;
846   unsigned Op1Reg = getRegForValue(I->getOperand(1));
847   if (Op1Reg == 0) return false;
848   unsigned Op2Reg = getRegForValue(I->getOperand(2));
849   if (Op2Reg == 0) return false;
850
851   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
852   unsigned ResultReg = createResultReg(RC);
853   BuildMI(MBB, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
854   UpdateValueMap(I, ResultReg);
855   return true;
856 }
857
858 bool X86FastISel::X86SelectFPExt(Instruction *I) {
859   // fpext from float to double.
860   if (Subtarget->hasSSE2() && I->getType() == Type::DoubleTy) {
861     Value *V = I->getOperand(0);
862     if (V->getType() == Type::FloatTy) {
863       unsigned OpReg = getRegForValue(V);
864       if (OpReg == 0) return false;
865       unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
866       BuildMI(MBB, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
867       UpdateValueMap(I, ResultReg);
868       return true;
869     }
870   }
871
872   return false;
873 }
874
875 bool X86FastISel::X86SelectFPTrunc(Instruction *I) {
876   if (Subtarget->hasSSE2()) {
877     if (I->getType() == Type::FloatTy) {
878       Value *V = I->getOperand(0);
879       if (V->getType() == Type::DoubleTy) {
880         unsigned OpReg = getRegForValue(V);
881         if (OpReg == 0) return false;
882         unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
883         BuildMI(MBB, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
884         UpdateValueMap(I, ResultReg);
885         return true;
886       }
887     }
888   }
889
890   return false;
891 }
892
893 bool X86FastISel::X86SelectTrunc(Instruction *I) {
894   if (Subtarget->is64Bit())
895     // All other cases should be handled by the tblgen generated code.
896     return false;
897   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
898   MVT DstVT = TLI.getValueType(I->getType());
899   if (DstVT != MVT::i8)
900     // All other cases should be handled by the tblgen generated code.
901     return false;
902   if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
903     // All other cases should be handled by the tblgen generated code.
904     return false;
905
906   unsigned InputReg = getRegForValue(I->getOperand(0));
907   if (!InputReg)
908     // Unhandled operand.  Halt "fast" selection and bail.
909     return false;
910
911   // First issue a copy to GR16_ or GR32_.
912   unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16to16_ : X86::MOV32to32_;
913   const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
914     ? X86::GR16_RegisterClass : X86::GR32_RegisterClass;
915   unsigned CopyReg = createResultReg(CopyRC);
916   BuildMI(MBB, TII.get(CopyOpc), CopyReg).addReg(InputReg);
917
918   // Then issue an extract_subreg.
919   unsigned ResultReg = FastEmitInst_extractsubreg(CopyReg, X86::SUBREG_8BIT);
920   if (!ResultReg)
921     return false;
922
923   UpdateValueMap(I, ResultReg);
924   return true;
925 }
926
927 bool X86FastISel::X86SelectCall(Instruction *I) {
928   CallInst *CI = cast<CallInst>(I);
929   Value *Callee = I->getOperand(0);
930
931   // Can't handle inline asm yet.
932   if (isa<InlineAsm>(Callee))
933     return false;
934
935   // FIXME: Handle some intrinsics.
936   if (Function *F = CI->getCalledFunction()) {
937     if (F->isDeclaration() &&F->getIntrinsicID())
938       return false;
939   }
940
941   // Handle only C and fastcc calling conventions for now.
942   CallSite CS(CI);
943   unsigned CC = CS.getCallingConv();
944   if (CC != CallingConv::C &&
945       CC != CallingConv::Fast &&
946       CC != CallingConv::X86_FastCall)
947     return false;
948
949   // Let SDISel handle vararg functions.
950   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
951   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
952   if (FTy->isVarArg())
953     return false;
954
955   // Handle *simple* calls for now.
956   const Type *RetTy = CS.getType();
957   MVT RetVT;
958   if (RetTy == Type::VoidTy)
959     RetVT = MVT::isVoid;
960   else if (!isTypeLegal(RetTy, RetVT, true))
961     return false;
962
963   // Materialize callee address in a register. FIXME: GV address can be
964   // handled with a CALLpcrel32 instead.
965   X86AddressMode CalleeAM;
966   if (!X86SelectAddress(Callee, CalleeAM, true))
967     return false;
968   unsigned CalleeOp = 0;
969   GlobalValue *GV = 0;
970   if (CalleeAM.Base.Reg != 0) {
971     assert(CalleeAM.GV == 0);
972     CalleeOp = CalleeAM.Base.Reg;
973   } else if (CalleeAM.GV != 0) {
974     assert(CalleeAM.GV != 0);
975     GV = CalleeAM.GV;
976   } else
977     return false;
978
979   // Allow calls which produce i1 results.
980   bool AndToI1 = false;
981   if (RetVT == MVT::i1) {
982     RetVT = MVT::i8;
983     AndToI1 = true;
984   }
985
986   // Deal with call operands first.
987   SmallVector<Value*, 8> ArgVals;
988   SmallVector<unsigned, 8> Args;
989   SmallVector<MVT, 8> ArgVTs;
990   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
991   Args.reserve(CS.arg_size());
992   ArgVals.reserve(CS.arg_size());
993   ArgVTs.reserve(CS.arg_size());
994   ArgFlags.reserve(CS.arg_size());
995   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
996        i != e; ++i) {
997     unsigned Arg = getRegForValue(*i);
998     if (Arg == 0)
999       return false;
1000     ISD::ArgFlagsTy Flags;
1001     unsigned AttrInd = i - CS.arg_begin() + 1;
1002     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1003       Flags.setSExt();
1004     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1005       Flags.setZExt();
1006
1007     // FIXME: Only handle *easy* calls for now.
1008     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1009         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1010         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1011         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1012       return false;
1013
1014     const Type *ArgTy = (*i)->getType();
1015     MVT ArgVT;
1016     if (!isTypeLegal(ArgTy, ArgVT))
1017       return false;
1018     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1019     Flags.setOrigAlign(OriginalAlignment);
1020
1021     Args.push_back(Arg);
1022     ArgVals.push_back(*i);
1023     ArgVTs.push_back(ArgVT);
1024     ArgFlags.push_back(Flags);
1025   }
1026
1027   // Analyze operands of the call, assigning locations to each operand.
1028   SmallVector<CCValAssign, 16> ArgLocs;
1029   CCState CCInfo(CC, false, TM, ArgLocs);
1030   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1031
1032   // Get a count of how many bytes are to be pushed on the stack.
1033   unsigned NumBytes = CCInfo.getNextStackOffset();
1034
1035   // Issue CALLSEQ_START
1036   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1037   BuildMI(MBB, TII.get(AdjStackDown)).addImm(NumBytes);
1038
1039   // Process argument: walk the register/memloc assignments, inserting
1040   // copies / loads.
1041   SmallVector<unsigned, 4> RegArgs;
1042   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1043     CCValAssign &VA = ArgLocs[i];
1044     unsigned Arg = Args[VA.getValNo()];
1045     MVT ArgVT = ArgVTs[VA.getValNo()];
1046   
1047     // Promote the value if needed.
1048     switch (VA.getLocInfo()) {
1049     default: assert(0 && "Unknown loc info!");
1050     case CCValAssign::Full: break;
1051     case CCValAssign::SExt: {
1052       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1053                                        Arg, ArgVT, Arg);
1054       assert(Emitted && "Failed to emit a sext!");
1055       ArgVT = VA.getLocVT();
1056       break;
1057     }
1058     case CCValAssign::ZExt: {
1059       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1060                                        Arg, ArgVT, Arg);
1061       assert(Emitted && "Failed to emit a zext!");
1062       ArgVT = VA.getLocVT();
1063       break;
1064     }
1065     case CCValAssign::AExt: {
1066       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1067                                        Arg, ArgVT, Arg);
1068       if (!Emitted)
1069         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1070                                     Arg, ArgVT, Arg);
1071       if (!Emitted)
1072         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1073                                     Arg, ArgVT, Arg);
1074       
1075       assert(Emitted && "Failed to emit a aext!");
1076       ArgVT = VA.getLocVT();
1077       break;
1078     }
1079     }
1080     
1081     if (VA.isRegLoc()) {
1082       TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1083       bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1084                                       Arg, RC, RC);
1085       assert(Emitted && "Failed to emit a copy instruction!");
1086       RegArgs.push_back(VA.getLocReg());
1087     } else {
1088       unsigned LocMemOffset = VA.getLocMemOffset();
1089       X86AddressMode AM;
1090       AM.Base.Reg = StackPtr;
1091       AM.Disp = LocMemOffset;
1092       Value *ArgVal = ArgVals[VA.getValNo()];
1093       
1094       // If this is a really simple value, emit this with the Value* version of
1095       // X86FastEmitStore.  If it isn't simple, we don't want to do this, as it
1096       // can cause us to reevaluate the argument.
1097       if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1098         X86FastEmitStore(ArgVT, ArgVal, AM);
1099       else
1100         X86FastEmitStore(ArgVT, Arg, AM);
1101     }
1102   }
1103
1104   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1105   // GOT pointer.  
1106   if (!Subtarget->is64Bit() &&
1107       TM.getRelocationModel() == Reloc::PIC_ &&
1108       Subtarget->isPICStyleGOT()) {
1109     TargetRegisterClass *RC = X86::GR32RegisterClass;
1110     unsigned Base = getInstrInfo()->getGlobalBaseReg(&MF);
1111     bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC);
1112     assert(Emitted && "Failed to emit a copy instruction!");
1113   }
1114
1115   // Issue the call.
1116   unsigned CallOpc = CalleeOp
1117     ? (Subtarget->is64Bit() ? X86::CALL64r       : X86::CALL32r)
1118     : (Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32);
1119   MachineInstrBuilder MIB = CalleeOp
1120     ? BuildMI(MBB, TII.get(CallOpc)).addReg(CalleeOp)
1121     : BuildMI(MBB, TII.get(CallOpc)).addGlobalAddress(GV);
1122
1123   // Add an implicit use GOT pointer in EBX.
1124   if (!Subtarget->is64Bit() &&
1125       TM.getRelocationModel() == Reloc::PIC_ &&
1126       Subtarget->isPICStyleGOT())
1127     MIB.addReg(X86::EBX);
1128
1129   // Add implicit physical register uses to the call.
1130   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1131     MIB.addReg(RegArgs[i]);
1132
1133   // Issue CALLSEQ_END
1134   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1135   BuildMI(MBB, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1136
1137   // Now handle call return value (if any).
1138   if (RetVT.getSimpleVT() != MVT::isVoid) {
1139     SmallVector<CCValAssign, 16> RVLocs;
1140     CCState CCInfo(CC, false, TM, RVLocs);
1141     CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1142
1143     // Copy all of the result registers out of their specified physreg.
1144     assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1145     MVT CopyVT = RVLocs[0].getValVT();
1146     TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1147     TargetRegisterClass *SrcRC = DstRC;
1148     
1149     // If this is a call to a function that returns an fp value on the x87 fp
1150     // stack, but where we prefer to use the value in xmm registers, copy it
1151     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1152     if ((RVLocs[0].getLocReg() == X86::ST0 ||
1153          RVLocs[0].getLocReg() == X86::ST1) &&
1154         isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1155       CopyVT = MVT::f80;
1156       SrcRC = X86::RSTRegisterClass;
1157       DstRC = X86::RFP80RegisterClass;
1158     }
1159
1160     unsigned ResultReg = createResultReg(DstRC);
1161     bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1162                                     RVLocs[0].getLocReg(), DstRC, SrcRC);
1163     assert(Emitted && "Failed to emit a copy instruction!");
1164     if (CopyVT != RVLocs[0].getValVT()) {
1165       // Round the F80 the right size, which also moves to the appropriate xmm
1166       // register. This is accomplished by storing the F80 value in memory and
1167       // then loading it back. Ewww...
1168       MVT ResVT = RVLocs[0].getValVT();
1169       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1170       unsigned MemSize = ResVT.getSizeInBits()/8;
1171       int FI = MFI.CreateStackObject(MemSize, MemSize);
1172       addFrameReference(BuildMI(MBB, TII.get(Opc)), FI).addReg(ResultReg);
1173       DstRC = ResVT == MVT::f32
1174         ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1175       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1176       ResultReg = createResultReg(DstRC);
1177       addFrameReference(BuildMI(MBB, TII.get(Opc), ResultReg), FI);
1178     }
1179
1180     if (AndToI1) {
1181       // Mask out all but lowest bit for some call which produces an i1.
1182       unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1183       BuildMI(MBB, TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1184       ResultReg = AndResult;
1185     }
1186
1187     UpdateValueMap(I, ResultReg);
1188   }
1189
1190   return true;
1191 }
1192
1193
1194 bool
1195 X86FastISel::TargetSelectInstruction(Instruction *I)  {
1196   switch (I->getOpcode()) {
1197   default: break;
1198   case Instruction::Load:
1199     return X86SelectLoad(I);
1200   case Instruction::Store:
1201     return X86SelectStore(I);
1202   case Instruction::ICmp:
1203   case Instruction::FCmp:
1204     return X86SelectCmp(I);
1205   case Instruction::ZExt:
1206     return X86SelectZExt(I);
1207   case Instruction::Br:
1208     return X86SelectBranch(I);
1209   case Instruction::Call:
1210     return X86SelectCall(I);
1211   case Instruction::LShr:
1212   case Instruction::AShr:
1213   case Instruction::Shl:
1214     return X86SelectShift(I);
1215   case Instruction::Select:
1216     return X86SelectSelect(I);
1217   case Instruction::Trunc:
1218     return X86SelectTrunc(I);
1219   case Instruction::FPExt:
1220     return X86SelectFPExt(I);
1221   case Instruction::FPTrunc:
1222     return X86SelectFPTrunc(I);
1223   }
1224
1225   return false;
1226 }
1227
1228 unsigned X86FastISel::TargetMaterializeConstant(Constant *C) {
1229   MVT VT;
1230   if (!isTypeLegal(C->getType(), VT))
1231     return false;
1232   
1233   // Get opcode and regclass of the output for the given load instruction.
1234   unsigned Opc = 0;
1235   const TargetRegisterClass *RC = NULL;
1236   switch (VT.getSimpleVT()) {
1237   default: return false;
1238   case MVT::i8:
1239     Opc = X86::MOV8rm;
1240     RC  = X86::GR8RegisterClass;
1241     break;
1242   case MVT::i16:
1243     Opc = X86::MOV16rm;
1244     RC  = X86::GR16RegisterClass;
1245     break;
1246   case MVT::i32:
1247     Opc = X86::MOV32rm;
1248     RC  = X86::GR32RegisterClass;
1249     break;
1250   case MVT::i64:
1251     // Must be in x86-64 mode.
1252     Opc = X86::MOV64rm;
1253     RC  = X86::GR64RegisterClass;
1254     break;
1255   case MVT::f32:
1256     if (Subtarget->hasSSE1()) {
1257       Opc = X86::MOVSSrm;
1258       RC  = X86::FR32RegisterClass;
1259     } else {
1260       Opc = X86::LD_Fp32m;
1261       RC  = X86::RFP32RegisterClass;
1262     }
1263     break;
1264   case MVT::f64:
1265     if (Subtarget->hasSSE2()) {
1266       Opc = X86::MOVSDrm;
1267       RC  = X86::FR64RegisterClass;
1268     } else {
1269       Opc = X86::LD_Fp64m;
1270       RC  = X86::RFP64RegisterClass;
1271     }
1272     break;
1273   case MVT::f80:
1274     // No f80 support yet.
1275     return false;
1276   }
1277   
1278   // Materialize addresses with LEA instructions.
1279   if (isa<GlobalValue>(C)) {
1280     X86AddressMode AM;
1281     if (X86SelectAddress(C, AM, false)) {
1282       if (TLI.getPointerTy() == MVT::i32)
1283         Opc = X86::LEA32r;
1284       else
1285         Opc = X86::LEA64r;
1286       unsigned ResultReg = createResultReg(RC);
1287       addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
1288       return ResultReg;
1289     }
1290     return 0;
1291   }
1292   
1293   // MachineConstantPool wants an explicit alignment.
1294   unsigned Align = TD.getPreferredTypeAlignmentShift(C->getType());
1295   if (Align == 0) {
1296     // Alignment of vector types.  FIXME!
1297     Align = TD.getABITypeSize(C->getType());
1298     Align = Log2_64(Align);
1299   }
1300   
1301   // x86-32 PIC requires a PIC base register for constant pools.
1302   unsigned PICBase = 0;
1303   if (TM.getRelocationModel() == Reloc::PIC_ &&
1304       !Subtarget->is64Bit())
1305     PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1306
1307   // Create the load from the constant pool.
1308   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1309   unsigned ResultReg = createResultReg(RC);
1310   addConstantPoolReference(BuildMI(MBB, TII.get(Opc), ResultReg), MCPOffset,
1311                            PICBase);
1312
1313   return ResultReg;
1314 }
1315
1316 unsigned X86FastISel::TargetMaterializeAlloca(AllocaInst *C) {
1317   // Fail on dynamic allocas. At this point, getRegForValue has already
1318   // checked its CSE maps, so if we're here trying to handle a dynamic
1319   // alloca, we're not going to succeed. X86SelectAddress has a
1320   // check for dynamic allocas, because it's called directly from
1321   // various places, but TargetMaterializeAlloca also needs a check
1322   // in order to avoid recursion between getRegForValue,
1323   // X86SelectAddrss, and TargetMaterializeAlloca.
1324   if (!StaticAllocaMap.count(C))
1325     return 0;
1326
1327   X86AddressMode AM;
1328   if (!X86SelectAddress(C, AM, false))
1329     return 0;
1330   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1331   TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1332   unsigned ResultReg = createResultReg(RC);
1333   addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
1334   return ResultReg;
1335 }
1336
1337 namespace llvm {
1338   llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1339                         MachineModuleInfo *mmi,
1340                         DenseMap<const Value *, unsigned> &vm,
1341                         DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
1342                         DenseMap<const AllocaInst *, int> &am
1343 #ifndef NDEBUG
1344                         , SmallSet<Instruction*, 8> &cil
1345 #endif
1346                         ) {
1347     return new X86FastISel(mf, mmi, vm, bm, am
1348 #ifndef NDEBUG
1349                            , cil
1350 #endif
1351                            );
1352   }
1353 }