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