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