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