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