X86 fast-isel: Avoid explicit AH subreg reference for [SU]Rem.
[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 "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm;
40
41 namespace {
42
43 class X86FastISel : public FastISel {
44   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
45   /// make the right decision when generating code for different targets.
46   const X86Subtarget *Subtarget;
47
48   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
49   /// floating point ops.
50   /// When SSE is available, use it for f32 operations.
51   /// When SSE2 is available, use it for f64 operations.
52   bool X86ScalarSSEf64;
53   bool X86ScalarSSEf32;
54
55 public:
56   explicit X86FastISel(FunctionLoweringInfo &funcInfo,
57                        const TargetLibraryInfo *libInfo)
58     : FastISel(funcInfo, libInfo) {
59     Subtarget = &TM.getSubtarget<X86Subtarget>();
60     X86ScalarSSEf64 = Subtarget->hasSSE2();
61     X86ScalarSSEf32 = Subtarget->hasSSE1();
62   }
63
64   virtual bool TargetSelectInstruction(const Instruction *I);
65
66   /// \brief 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 tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
71                                    const LoadInst *LI);
72
73   virtual bool FastLowerArguments();
74
75 #include "X86GenFastISel.inc"
76
77 private:
78   bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
79
80   bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
81
82   bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
83   bool X86FastEmitStore(EVT VT, unsigned Val, 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 X86SelectDivRem(const Instruction *I);
106
107   bool X86SelectSelect(const Instruction *I);
108
109   bool X86SelectTrunc(const Instruction *I);
110
111   bool X86SelectFPExt(const Instruction *I);
112   bool X86SelectFPTrunc(const Instruction *I);
113
114   bool X86VisitIntrinsicCall(const IntrinsicInst &I);
115   bool X86SelectCall(const Instruction *I);
116
117   bool DoSelectCall(const Instruction *I, const char *MemIntName);
118
119   const X86InstrInfo *getInstrInfo() const {
120     return getTargetMachine()->getInstrInfo();
121   }
122   const X86TargetMachine *getTargetMachine() const {
123     return static_cast<const X86TargetMachine *>(&TM);
124   }
125
126   unsigned TargetMaterializeConstant(const Constant *C);
127
128   unsigned TargetMaterializeAlloca(const AllocaInst *C);
129
130   unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
131
132   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
133   /// computed in an SSE register, not on the X87 floating point stack.
134   bool isScalarFPTypeInSSEReg(EVT VT) const {
135     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
136       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
137   }
138
139   bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
140
141   bool IsMemcpySmall(uint64_t Len);
142
143   bool TryEmitSmallMemcpy(X86AddressMode DestAM,
144                           X86AddressMode SrcAM, uint64_t Len);
145 };
146
147 } // end anonymous namespace.
148
149 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
150   EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
151   if (evt == MVT::Other || !evt.isSimple())
152     // Unhandled type. Halt "fast" selection and bail.
153     return false;
154
155   VT = evt.getSimpleVT();
156   // For now, require SSE/SSE2 for performing floating-point operations,
157   // since x87 requires additional work.
158   if (VT == MVT::f64 && !X86ScalarSSEf64)
159     return false;
160   if (VT == MVT::f32 && !X86ScalarSSEf32)
161     return false;
162   // Similarly, no f80 support yet.
163   if (VT == MVT::f80)
164     return false;
165   // We only handle legal types. For example, on x86-32 the instruction
166   // selector contains all of the 64-bit instructions from x86-64,
167   // under the assumption that i64 won't be used if the target doesn't
168   // support it.
169   return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
170 }
171
172 #include "X86GenCallingConv.inc"
173
174 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
175 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
176 /// Return true and the result register by reference if it is possible.
177 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
178                                   unsigned &ResultReg) {
179   // Get opcode and regclass of the output for the given load instruction.
180   unsigned Opc = 0;
181   const TargetRegisterClass *RC = NULL;
182   switch (VT.getSimpleVT().SimpleTy) {
183   default: return false;
184   case MVT::i1:
185   case MVT::i8:
186     Opc = X86::MOV8rm;
187     RC  = &X86::GR8RegClass;
188     break;
189   case MVT::i16:
190     Opc = X86::MOV16rm;
191     RC  = &X86::GR16RegClass;
192     break;
193   case MVT::i32:
194     Opc = X86::MOV32rm;
195     RC  = &X86::GR32RegClass;
196     break;
197   case MVT::i64:
198     // Must be in x86-64 mode.
199     Opc = X86::MOV64rm;
200     RC  = &X86::GR64RegClass;
201     break;
202   case MVT::f32:
203     if (X86ScalarSSEf32) {
204       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
205       RC  = &X86::FR32RegClass;
206     } else {
207       Opc = X86::LD_Fp32m;
208       RC  = &X86::RFP32RegClass;
209     }
210     break;
211   case MVT::f64:
212     if (X86ScalarSSEf64) {
213       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
214       RC  = &X86::FR64RegClass;
215     } else {
216       Opc = X86::LD_Fp64m;
217       RC  = &X86::RFP64RegClass;
218     }
219     break;
220   case MVT::f80:
221     // No f80 support yet.
222     return false;
223   }
224
225   ResultReg = createResultReg(RC);
226   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
227                          DL, TII.get(Opc), ResultReg), AM);
228   return true;
229 }
230
231 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
232 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
233 /// and a displacement offset, or a GlobalAddress,
234 /// i.e. V. Return true if it is possible.
235 bool
236 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
237   // Get opcode and regclass of the output for the given store instruction.
238   unsigned Opc = 0;
239   switch (VT.getSimpleVT().SimpleTy) {
240   case MVT::f80: // No f80 support yet.
241   default: return false;
242   case MVT::i1: {
243     // Mask out all but lowest bit.
244     unsigned AndResult = createResultReg(&X86::GR8RegClass);
245     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
246             TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
247     Val = AndResult;
248   }
249   // FALLTHROUGH, handling i1 as i8.
250   case MVT::i8:  Opc = X86::MOV8mr;  break;
251   case MVT::i16: Opc = X86::MOV16mr; break;
252   case MVT::i32: Opc = X86::MOV32mr; break;
253   case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
254   case MVT::f32:
255     Opc = X86ScalarSSEf32 ?
256           (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
257     break;
258   case MVT::f64:
259     Opc = X86ScalarSSEf64 ?
260           (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
261     break;
262   case MVT::v4f32:
263     Opc = X86::MOVAPSmr;
264     break;
265   case MVT::v2f64:
266     Opc = X86::MOVAPDmr;
267     break;
268   case MVT::v4i32:
269   case MVT::v2i64:
270   case MVT::v8i16:
271   case MVT::v16i8:
272     Opc = X86::MOVDQAmr;
273     break;
274   }
275
276   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
277                          DL, TII.get(Opc)), AM).addReg(Val);
278   return true;
279 }
280
281 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
282                                    const X86AddressMode &AM) {
283   // Handle 'null' like i32/i64 0.
284   if (isa<ConstantPointerNull>(Val))
285     Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
286
287   // If this is a store of a simple constant, fold the constant into the store.
288   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
289     unsigned Opc = 0;
290     bool Signed = true;
291     switch (VT.getSimpleVT().SimpleTy) {
292     default: break;
293     case MVT::i1:  Signed = false;     // FALLTHROUGH to handle as i8.
294     case MVT::i8:  Opc = X86::MOV8mi;  break;
295     case MVT::i16: Opc = X86::MOV16mi; break;
296     case MVT::i32: Opc = X86::MOV32mi; break;
297     case MVT::i64:
298       // Must be a 32-bit sign extended value.
299       if (isInt<32>(CI->getSExtValue()))
300         Opc = X86::MOV64mi32;
301       break;
302     }
303
304     if (Opc) {
305       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
306                              DL, TII.get(Opc)), AM)
307                              .addImm(Signed ? (uint64_t) CI->getSExtValue() :
308                                               CI->getZExtValue());
309       return true;
310     }
311   }
312
313   unsigned ValReg = getRegForValue(Val);
314   if (ValReg == 0)
315     return false;
316
317   return X86FastEmitStore(VT, ValReg, AM);
318 }
319
320 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
321 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
322 /// ISD::SIGN_EXTEND).
323 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
324                                     unsigned Src, EVT SrcVT,
325                                     unsigned &ResultReg) {
326   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
327                            Src, /*TODO: Kill=*/false);
328   if (RR == 0)
329     return false;
330
331   ResultReg = RR;
332   return true;
333 }
334
335 /// X86SelectAddress - Attempt to fill in an address from the given value.
336 ///
337 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
338   const User *U = NULL;
339   unsigned Opcode = Instruction::UserOp1;
340   if (const Instruction *I = dyn_cast<Instruction>(V)) {
341     // Don't walk into other basic blocks; it's possible we haven't
342     // visited them yet, so the instructions may not yet be assigned
343     // virtual registers.
344     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
345         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
346       Opcode = I->getOpcode();
347       U = I;
348     }
349   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
350     Opcode = C->getOpcode();
351     U = C;
352   }
353
354   if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
355     if (Ty->getAddressSpace() > 255)
356       // Fast instruction selection doesn't support the special
357       // address spaces.
358       return false;
359
360   switch (Opcode) {
361   default: break;
362   case Instruction::BitCast:
363     // Look past bitcasts.
364     return X86SelectAddress(U->getOperand(0), AM);
365
366   case Instruction::IntToPtr:
367     // Look past no-op inttoptrs.
368     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
369       return X86SelectAddress(U->getOperand(0), AM);
370     break;
371
372   case Instruction::PtrToInt:
373     // Look past no-op ptrtoints.
374     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
375       return X86SelectAddress(U->getOperand(0), AM);
376     break;
377
378   case Instruction::Alloca: {
379     // Do static allocas.
380     const AllocaInst *A = cast<AllocaInst>(V);
381     DenseMap<const AllocaInst*, int>::iterator SI =
382       FuncInfo.StaticAllocaMap.find(A);
383     if (SI != FuncInfo.StaticAllocaMap.end()) {
384       AM.BaseType = X86AddressMode::FrameIndexBase;
385       AM.Base.FrameIndex = SI->second;
386       return true;
387     }
388     break;
389   }
390
391   case Instruction::Add: {
392     // Adds of constants are common and easy enough.
393     if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
394       uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
395       // They have to fit in the 32-bit signed displacement field though.
396       if (isInt<32>(Disp)) {
397         AM.Disp = (uint32_t)Disp;
398         return X86SelectAddress(U->getOperand(0), AM);
399       }
400     }
401     break;
402   }
403
404   case Instruction::GetElementPtr: {
405     X86AddressMode SavedAM = AM;
406
407     // Pattern-match simple GEPs.
408     uint64_t Disp = (int32_t)AM.Disp;
409     unsigned IndexReg = AM.IndexReg;
410     unsigned Scale = AM.Scale;
411     gep_type_iterator GTI = gep_type_begin(U);
412     // Iterate through the indices, folding what we can. Constants can be
413     // folded, and one dynamic index can be handled, if the scale is supported.
414     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
415          i != e; ++i, ++GTI) {
416       const Value *Op = *i;
417       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
418         const StructLayout *SL = TD.getStructLayout(STy);
419         Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
420         continue;
421       }
422
423       // A array/variable index is always of the form i*S where S is the
424       // constant scale size.  See if we can push the scale into immediates.
425       uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
426       for (;;) {
427         if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
428           // Constant-offset addressing.
429           Disp += CI->getSExtValue() * S;
430           break;
431         }
432         if (isa<AddOperator>(Op) &&
433             (!isa<Instruction>(Op) ||
434              FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
435                == FuncInfo.MBB) &&
436             isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
437           // An add (in the same block) with a constant operand. Fold the
438           // constant.
439           ConstantInt *CI =
440             cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
441           Disp += CI->getSExtValue() * S;
442           // Iterate on the other operand.
443           Op = cast<AddOperator>(Op)->getOperand(0);
444           continue;
445         }
446         if (IndexReg == 0 &&
447             (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
448             (S == 1 || S == 2 || S == 4 || S == 8)) {
449           // Scaled-index addressing.
450           Scale = S;
451           IndexReg = getRegForGEPIndex(Op).first;
452           if (IndexReg == 0)
453             return false;
454           break;
455         }
456         // Unsupported.
457         goto unsupported_gep;
458       }
459     }
460     // Check for displacement overflow.
461     if (!isInt<32>(Disp))
462       break;
463     // Ok, the GEP indices were covered by constant-offset and scaled-index
464     // addressing. Update the address state and move on to examining the base.
465     AM.IndexReg = IndexReg;
466     AM.Scale = Scale;
467     AM.Disp = (uint32_t)Disp;
468     if (X86SelectAddress(U->getOperand(0), AM))
469       return true;
470
471     // If we couldn't merge the gep value into this addr mode, revert back to
472     // our address and just match the value instead of completely failing.
473     AM = SavedAM;
474     break;
475   unsupported_gep:
476     // Ok, the GEP indices weren't all covered.
477     break;
478   }
479   }
480
481   // Handle constant address.
482   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
483     // Can't handle alternate code models yet.
484     if (TM.getCodeModel() != CodeModel::Small)
485       return false;
486
487     // Can't handle TLS yet.
488     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
489       if (GVar->isThreadLocal())
490         return false;
491
492     // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
493     // it works...).
494     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
495       if (const GlobalVariable *GVar =
496             dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
497         if (GVar->isThreadLocal())
498           return false;
499
500     // RIP-relative addresses can't have additional register operands, so if
501     // we've already folded stuff into the addressing mode, just force the
502     // global value into its own register, which we can use as the basereg.
503     if (!Subtarget->isPICStyleRIPRel() ||
504         (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
505       // Okay, we've committed to selecting this global. Set up the address.
506       AM.GV = GV;
507
508       // Allow the subtarget to classify the global.
509       unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
510
511       // If this reference is relative to the pic base, set it now.
512       if (isGlobalRelativeToPICBase(GVFlags)) {
513         // FIXME: How do we know Base.Reg is free??
514         AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
515       }
516
517       // Unless the ABI requires an extra load, return a direct reference to
518       // the global.
519       if (!isGlobalStubReference(GVFlags)) {
520         if (Subtarget->isPICStyleRIPRel()) {
521           // Use rip-relative addressing if we can.  Above we verified that the
522           // base and index registers are unused.
523           assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
524           AM.Base.Reg = X86::RIP;
525         }
526         AM.GVOpFlags = GVFlags;
527         return true;
528       }
529
530       // Ok, we need to do a load from a stub.  If we've already loaded from
531       // this stub, reuse the loaded pointer, otherwise emit the load now.
532       DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
533       unsigned LoadReg;
534       if (I != LocalValueMap.end() && I->second != 0) {
535         LoadReg = I->second;
536       } else {
537         // Issue load from stub.
538         unsigned Opc = 0;
539         const TargetRegisterClass *RC = NULL;
540         X86AddressMode StubAM;
541         StubAM.Base.Reg = AM.Base.Reg;
542         StubAM.GV = GV;
543         StubAM.GVOpFlags = GVFlags;
544
545         // Prepare for inserting code in the local-value area.
546         SavePoint SaveInsertPt = enterLocalValueArea();
547
548         if (TLI.getPointerTy() == MVT::i64) {
549           Opc = X86::MOV64rm;
550           RC  = &X86::GR64RegClass;
551
552           if (Subtarget->isPICStyleRIPRel())
553             StubAM.Base.Reg = X86::RIP;
554         } else {
555           Opc = X86::MOV32rm;
556           RC  = &X86::GR32RegClass;
557         }
558
559         LoadReg = createResultReg(RC);
560         MachineInstrBuilder LoadMI =
561           BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
562         addFullAddress(LoadMI, StubAM);
563
564         // Ok, back to normal mode.
565         leaveLocalValueArea(SaveInsertPt);
566
567         // Prevent loading GV stub multiple times in same MBB.
568         LocalValueMap[V] = LoadReg;
569       }
570
571       // Now construct the final address. Note that the Disp, Scale,
572       // and Index values may already be set here.
573       AM.Base.Reg = LoadReg;
574       AM.GV = 0;
575       return true;
576     }
577   }
578
579   // If all else fails, try to materialize the value in a register.
580   if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
581     if (AM.Base.Reg == 0) {
582       AM.Base.Reg = getRegForValue(V);
583       return AM.Base.Reg != 0;
584     }
585     if (AM.IndexReg == 0) {
586       assert(AM.Scale == 1 && "Scale with no index!");
587       AM.IndexReg = getRegForValue(V);
588       return AM.IndexReg != 0;
589     }
590   }
591
592   return false;
593 }
594
595 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
596 ///
597 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
598   const User *U = NULL;
599   unsigned Opcode = Instruction::UserOp1;
600   if (const Instruction *I = dyn_cast<Instruction>(V)) {
601     Opcode = I->getOpcode();
602     U = I;
603   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
604     Opcode = C->getOpcode();
605     U = C;
606   }
607
608   switch (Opcode) {
609   default: break;
610   case Instruction::BitCast:
611     // Look past bitcasts.
612     return X86SelectCallAddress(U->getOperand(0), AM);
613
614   case Instruction::IntToPtr:
615     // Look past no-op inttoptrs.
616     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
617       return X86SelectCallAddress(U->getOperand(0), AM);
618     break;
619
620   case Instruction::PtrToInt:
621     // Look past no-op ptrtoints.
622     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
623       return X86SelectCallAddress(U->getOperand(0), AM);
624     break;
625   }
626
627   // Handle constant address.
628   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
629     // Can't handle alternate code models yet.
630     if (TM.getCodeModel() != CodeModel::Small)
631       return false;
632
633     // RIP-relative addresses can't have additional register operands.
634     if (Subtarget->isPICStyleRIPRel() &&
635         (AM.Base.Reg != 0 || AM.IndexReg != 0))
636       return false;
637
638     // Can't handle DLLImport.
639     if (GV->hasDLLImportLinkage())
640       return false;
641
642     // Can't handle TLS.
643     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
644       if (GVar->isThreadLocal())
645         return false;
646
647     // Okay, we've committed to selecting this global. Set up the basic address.
648     AM.GV = GV;
649
650     // No ABI requires an extra load for anything other than DLLImport, which
651     // we rejected above. Return a direct reference to the global.
652     if (Subtarget->isPICStyleRIPRel()) {
653       // Use rip-relative addressing if we can.  Above we verified that the
654       // base and index registers are unused.
655       assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
656       AM.Base.Reg = X86::RIP;
657     } else if (Subtarget->isPICStyleStubPIC()) {
658       AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
659     } else if (Subtarget->isPICStyleGOT()) {
660       AM.GVOpFlags = X86II::MO_GOTOFF;
661     }
662
663     return true;
664   }
665
666   // If all else fails, try to materialize the value in a register.
667   if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
668     if (AM.Base.Reg == 0) {
669       AM.Base.Reg = getRegForValue(V);
670       return AM.Base.Reg != 0;
671     }
672     if (AM.IndexReg == 0) {
673       assert(AM.Scale == 1 && "Scale with no index!");
674       AM.IndexReg = getRegForValue(V);
675       return AM.IndexReg != 0;
676     }
677   }
678
679   return false;
680 }
681
682
683 /// X86SelectStore - Select and emit code to implement store instructions.
684 bool X86FastISel::X86SelectStore(const Instruction *I) {
685   // Atomic stores need special handling.
686   const StoreInst *S = cast<StoreInst>(I);
687
688   if (S->isAtomic())
689     return false;
690
691   MVT VT;
692   if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
693     return false;
694
695   X86AddressMode AM;
696   if (!X86SelectAddress(I->getOperand(1), AM))
697     return false;
698
699   return X86FastEmitStore(VT, I->getOperand(0), AM);
700 }
701
702 /// X86SelectRet - Select and emit code to implement ret instructions.
703 bool X86FastISel::X86SelectRet(const Instruction *I) {
704   const ReturnInst *Ret = cast<ReturnInst>(I);
705   const Function &F = *I->getParent()->getParent();
706   const X86MachineFunctionInfo *X86MFInfo =
707       FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
708
709   if (!FuncInfo.CanLowerReturn)
710     return false;
711
712   CallingConv::ID CC = F.getCallingConv();
713   if (CC != CallingConv::C &&
714       CC != CallingConv::Fast &&
715       CC != CallingConv::X86_FastCall)
716     return false;
717
718   if (Subtarget->isTargetWin64())
719     return false;
720
721   // Don't handle popping bytes on return for now.
722   if (X86MFInfo->getBytesToPopOnReturn() != 0)
723     return false;
724
725   // fastcc with -tailcallopt is intended to provide a guaranteed
726   // tail call optimization. Fastisel doesn't know how to do that.
727   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
728     return false;
729
730   // Let SDISel handle vararg functions.
731   if (F.isVarArg())
732     return false;
733
734   // Build a list of return value registers.
735   SmallVector<unsigned, 4> RetRegs;
736
737   if (Ret->getNumOperands() > 0) {
738     SmallVector<ISD::OutputArg, 4> Outs;
739     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
740
741     // Analyze operands of the call, assigning locations to each operand.
742     SmallVector<CCValAssign, 16> ValLocs;
743     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
744                    I->getContext());
745     CCInfo.AnalyzeReturn(Outs, RetCC_X86);
746
747     const Value *RV = Ret->getOperand(0);
748     unsigned Reg = getRegForValue(RV);
749     if (Reg == 0)
750       return false;
751
752     // Only handle a single return value for now.
753     if (ValLocs.size() != 1)
754       return false;
755
756     CCValAssign &VA = ValLocs[0];
757
758     // Don't bother handling odd stuff for now.
759     if (VA.getLocInfo() != CCValAssign::Full)
760       return false;
761     // Only handle register returns for now.
762     if (!VA.isRegLoc())
763       return false;
764
765     // The calling-convention tables for x87 returns don't tell
766     // the whole story.
767     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
768       return false;
769
770     unsigned SrcReg = Reg + VA.getValNo();
771     EVT SrcVT = TLI.getValueType(RV->getType());
772     EVT DstVT = VA.getValVT();
773     // Special handling for extended integers.
774     if (SrcVT != DstVT) {
775       if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
776         return false;
777
778       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
779         return false;
780
781       assert(DstVT == MVT::i32 && "X86 should always ext to i32");
782
783       if (SrcVT == MVT::i1) {
784         if (Outs[0].Flags.isSExt())
785           return false;
786         SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
787         SrcVT = MVT::i8;
788       }
789       unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
790                                              ISD::SIGN_EXTEND;
791       SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
792                           SrcReg, /*TODO: Kill=*/false);
793     }
794
795     // Make the copy.
796     unsigned DstReg = VA.getLocReg();
797     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
798     // Avoid a cross-class copy. This is very unlikely.
799     if (!SrcRC->contains(DstReg))
800       return false;
801     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
802             DstReg).addReg(SrcReg);
803
804     // Add register to return instruction.
805     RetRegs.push_back(VA.getLocReg());
806   }
807
808   // The x86-64 ABI for returning structs by value requires that we copy
809   // the sret argument into %rax for the return. We saved the argument into
810   // a virtual register in the entry block, so now we copy the value out
811   // and into %rax. We also do the same with %eax for Win32.
812   if (F.hasStructRetAttr() &&
813       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
814     unsigned Reg = X86MFInfo->getSRetReturnReg();
815     assert(Reg &&
816            "SRetReturnReg should have been set in LowerFormalArguments()!");
817     unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
818     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
819             RetReg).addReg(Reg);
820     RetRegs.push_back(RetReg);
821   }
822
823   // Now emit the RET.
824   MachineInstrBuilder MIB =
825     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
826   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
827     MIB.addReg(RetRegs[i], RegState::Implicit);
828   return true;
829 }
830
831 /// X86SelectLoad - Select and emit code to implement load instructions.
832 ///
833 bool X86FastISel::X86SelectLoad(const Instruction *I)  {
834   // Atomic loads need special handling.
835   if (cast<LoadInst>(I)->isAtomic())
836     return false;
837
838   MVT VT;
839   if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
840     return false;
841
842   X86AddressMode AM;
843   if (!X86SelectAddress(I->getOperand(0), AM))
844     return false;
845
846   unsigned ResultReg = 0;
847   if (X86FastEmitLoad(VT, AM, ResultReg)) {
848     UpdateValueMap(I, ResultReg);
849     return true;
850   }
851   return false;
852 }
853
854 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
855   bool HasAVX = Subtarget->hasAVX();
856   bool X86ScalarSSEf32 = Subtarget->hasSSE1();
857   bool X86ScalarSSEf64 = Subtarget->hasSSE2();
858
859   switch (VT.getSimpleVT().SimpleTy) {
860   default:       return 0;
861   case MVT::i8:  return X86::CMP8rr;
862   case MVT::i16: return X86::CMP16rr;
863   case MVT::i32: return X86::CMP32rr;
864   case MVT::i64: return X86::CMP64rr;
865   case MVT::f32:
866     return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
867   case MVT::f64:
868     return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
869   }
870 }
871
872 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
873 /// of the comparison, return an opcode that works for the compare (e.g.
874 /// CMP32ri) otherwise return 0.
875 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
876   switch (VT.getSimpleVT().SimpleTy) {
877   // Otherwise, we can't fold the immediate into this comparison.
878   default: return 0;
879   case MVT::i8: return X86::CMP8ri;
880   case MVT::i16: return X86::CMP16ri;
881   case MVT::i32: return X86::CMP32ri;
882   case MVT::i64:
883     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
884     // field.
885     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
886       return X86::CMP64ri32;
887     return 0;
888   }
889 }
890
891 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
892                                      EVT VT) {
893   unsigned Op0Reg = getRegForValue(Op0);
894   if (Op0Reg == 0) return false;
895
896   // Handle 'null' like i32/i64 0.
897   if (isa<ConstantPointerNull>(Op1))
898     Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
899
900   // We have two options: compare with register or immediate.  If the RHS of
901   // the compare is an immediate that we can fold into this compare, use
902   // CMPri, otherwise use CMPrr.
903   if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
904     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
905       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
906         .addReg(Op0Reg)
907         .addImm(Op1C->getSExtValue());
908       return true;
909     }
910   }
911
912   unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
913   if (CompareOpc == 0) return false;
914
915   unsigned Op1Reg = getRegForValue(Op1);
916   if (Op1Reg == 0) return false;
917   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
918     .addReg(Op0Reg)
919     .addReg(Op1Reg);
920
921   return true;
922 }
923
924 bool X86FastISel::X86SelectCmp(const Instruction *I) {
925   const CmpInst *CI = cast<CmpInst>(I);
926
927   MVT VT;
928   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
929     return false;
930
931   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
932   unsigned SetCCOpc;
933   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
934   switch (CI->getPredicate()) {
935   case CmpInst::FCMP_OEQ: {
936     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
937       return false;
938
939     unsigned EReg = createResultReg(&X86::GR8RegClass);
940     unsigned NPReg = createResultReg(&X86::GR8RegClass);
941     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
942     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
943             TII.get(X86::SETNPr), NPReg);
944     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
945             TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
946     UpdateValueMap(I, ResultReg);
947     return true;
948   }
949   case CmpInst::FCMP_UNE: {
950     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
951       return false;
952
953     unsigned NEReg = createResultReg(&X86::GR8RegClass);
954     unsigned PReg = createResultReg(&X86::GR8RegClass);
955     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
956     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
957     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
958       .addReg(PReg).addReg(NEReg);
959     UpdateValueMap(I, ResultReg);
960     return true;
961   }
962   case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
963   case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
964   case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
965   case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
966   case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
967   case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
968   case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
969   case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
970   case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
971   case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
972   case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
973   case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
974
975   case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
976   case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
977   case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
978   case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
979   case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
980   case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
981   case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
982   case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
983   case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
984   case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; 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 Op0/Op1.
994   if (!X86FastEmitCompare(Op0, Op1, VT))
995     return false;
996
997   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
998   UpdateValueMap(I, ResultReg);
999   return true;
1000 }
1001
1002 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1003   EVT DstVT = TLI.getValueType(I->getType());
1004   if (!TLI.isTypeLegal(DstVT))
1005     return false;
1006
1007   unsigned ResultReg = getRegForValue(I->getOperand(0));
1008   if (ResultReg == 0)
1009     return false;
1010
1011   // Handle zero-extension from i1 to i8, which is common.
1012   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()).getSimpleVT();
1013   if (SrcVT.SimpleTy == MVT::i1) {
1014     // Set the high bits to zero.
1015     ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1016     SrcVT = MVT::i8;
1017
1018     if (ResultReg == 0)
1019       return false;
1020   }
1021
1022   if (DstVT == MVT::i64) {
1023     // Handle extension to 64-bits via sub-register shenanigans.
1024     unsigned MovInst;
1025
1026     switch (SrcVT.SimpleTy) {
1027     case MVT::i8:  MovInst = X86::MOVZX32rr8;  break;
1028     case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1029     case MVT::i32: MovInst = X86::MOV32rr;     break;
1030     default: llvm_unreachable("Unexpected zext to i64 source type");
1031     }
1032
1033     unsigned Result32 = createResultReg(&X86::GR32RegClass);
1034     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32)
1035       .addReg(ResultReg);
1036
1037     ResultReg = createResultReg(&X86::GR64RegClass);
1038     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG),
1039             ResultReg)
1040       .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1041   } else if (DstVT != MVT::i8) {
1042     ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1043                            ResultReg, /*Kill=*/true);
1044     if (ResultReg == 0)
1045       return false;
1046   }
1047
1048   UpdateValueMap(I, ResultReg);
1049   return true;
1050 }
1051
1052
1053 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1054   // Unconditional branches are selected by tablegen-generated code.
1055   // Handle a conditional branch.
1056   const BranchInst *BI = cast<BranchInst>(I);
1057   MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1058   MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1059
1060   // Fold the common case of a conditional branch with a comparison
1061   // in the same block (values defined on other blocks may not have
1062   // initialized registers).
1063   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1064     if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1065       EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1066
1067       // Try to take advantage of fallthrough opportunities.
1068       CmpInst::Predicate Predicate = CI->getPredicate();
1069       if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1070         std::swap(TrueMBB, FalseMBB);
1071         Predicate = CmpInst::getInversePredicate(Predicate);
1072       }
1073
1074       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
1075       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1076
1077       switch (Predicate) {
1078       case CmpInst::FCMP_OEQ:
1079         std::swap(TrueMBB, FalseMBB);
1080         Predicate = CmpInst::FCMP_UNE;
1081         // FALL THROUGH
1082       case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1083       case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1084       case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1085       case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA_4;  break;
1086       case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE_4; break;
1087       case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1088       case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1089       case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4;  break;
1090       case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4;  break;
1091       case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB_4;  break;
1092       case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE_4; break;
1093       case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1094       case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1095
1096       case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE_4;  break;
1097       case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE_4; break;
1098       case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1099       case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1100       case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1101       case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1102       case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4;  break;
1103       case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1104       case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4;  break;
1105       case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1106       default:
1107         return false;
1108       }
1109
1110       const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1111       if (SwapArgs)
1112         std::swap(Op0, Op1);
1113
1114       // Emit a compare of the LHS and RHS, setting the flags.
1115       if (!X86FastEmitCompare(Op0, Op1, VT))
1116         return false;
1117
1118       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1119         .addMBB(TrueMBB);
1120
1121       if (Predicate == CmpInst::FCMP_UNE) {
1122         // X86 requires a second branch to handle UNE (and OEQ,
1123         // which is mapped to UNE above).
1124         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1125           .addMBB(TrueMBB);
1126       }
1127
1128       FastEmitBranch(FalseMBB, DL);
1129       FuncInfo.MBB->addSuccessor(TrueMBB);
1130       return true;
1131     }
1132   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1133     // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1134     // typically happen for _Bool and C++ bools.
1135     MVT SourceVT;
1136     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1137         isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1138       unsigned TestOpc = 0;
1139       switch (SourceVT.SimpleTy) {
1140       default: break;
1141       case MVT::i8:  TestOpc = X86::TEST8ri; break;
1142       case MVT::i16: TestOpc = X86::TEST16ri; break;
1143       case MVT::i32: TestOpc = X86::TEST32ri; break;
1144       case MVT::i64: TestOpc = X86::TEST64ri32; break;
1145       }
1146       if (TestOpc) {
1147         unsigned OpReg = getRegForValue(TI->getOperand(0));
1148         if (OpReg == 0) return false;
1149         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1150           .addReg(OpReg).addImm(1);
1151
1152         unsigned JmpOpc = X86::JNE_4;
1153         if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1154           std::swap(TrueMBB, FalseMBB);
1155           JmpOpc = X86::JE_4;
1156         }
1157
1158         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1159           .addMBB(TrueMBB);
1160         FastEmitBranch(FalseMBB, DL);
1161         FuncInfo.MBB->addSuccessor(TrueMBB);
1162         return true;
1163       }
1164     }
1165   }
1166
1167   // Otherwise do a clumsy setcc and re-test it.
1168   // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1169   // in an explicit cast, so make sure to handle that correctly.
1170   unsigned OpReg = getRegForValue(BI->getCondition());
1171   if (OpReg == 0) return false;
1172
1173   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1174     .addReg(OpReg).addImm(1);
1175   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1176     .addMBB(TrueMBB);
1177   FastEmitBranch(FalseMBB, DL);
1178   FuncInfo.MBB->addSuccessor(TrueMBB);
1179   return true;
1180 }
1181
1182 bool X86FastISel::X86SelectShift(const Instruction *I) {
1183   unsigned CReg = 0, OpReg = 0;
1184   const TargetRegisterClass *RC = NULL;
1185   if (I->getType()->isIntegerTy(8)) {
1186     CReg = X86::CL;
1187     RC = &X86::GR8RegClass;
1188     switch (I->getOpcode()) {
1189     case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1190     case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1191     case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
1192     default: return false;
1193     }
1194   } else if (I->getType()->isIntegerTy(16)) {
1195     CReg = X86::CX;
1196     RC = &X86::GR16RegClass;
1197     switch (I->getOpcode()) {
1198     case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1199     case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1200     case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
1201     default: return false;
1202     }
1203   } else if (I->getType()->isIntegerTy(32)) {
1204     CReg = X86::ECX;
1205     RC = &X86::GR32RegClass;
1206     switch (I->getOpcode()) {
1207     case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1208     case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1209     case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
1210     default: return false;
1211     }
1212   } else if (I->getType()->isIntegerTy(64)) {
1213     CReg = X86::RCX;
1214     RC = &X86::GR64RegClass;
1215     switch (I->getOpcode()) {
1216     case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1217     case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1218     case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
1219     default: return false;
1220     }
1221   } else {
1222     return false;
1223   }
1224
1225   MVT VT;
1226   if (!isTypeLegal(I->getType(), VT))
1227     return false;
1228
1229   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1230   if (Op0Reg == 0) return false;
1231
1232   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1233   if (Op1Reg == 0) return false;
1234   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1235           CReg).addReg(Op1Reg);
1236
1237   // The shift instruction uses X86::CL. If we defined a super-register
1238   // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1239   if (CReg != X86::CL)
1240     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1241             TII.get(TargetOpcode::KILL), X86::CL)
1242       .addReg(CReg, RegState::Kill);
1243
1244   unsigned ResultReg = createResultReg(RC);
1245   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1246     .addReg(Op0Reg);
1247   UpdateValueMap(I, ResultReg);
1248   return true;
1249 }
1250
1251 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1252   const static unsigned NumTypes = 4; // i8, i16, i32, i64
1253   const static unsigned NumOps   = 4; // SDiv, SRem, UDiv, URem
1254   const static bool S = true;  // IsSigned
1255   const static bool U = false; // !IsSigned
1256   const static unsigned Copy = TargetOpcode::COPY;
1257   // For the X86 DIV/IDIV instruction, in most cases the dividend
1258   // (numerator) must be in a specific register pair highreg:lowreg,
1259   // producing the quotient in lowreg and the remainder in highreg.
1260   // For most data types, to set up the instruction, the dividend is
1261   // copied into lowreg, and lowreg is sign-extended or zero-extended
1262   // into highreg.  The exception is i8, where the dividend is defined
1263   // as a single register rather than a register pair, and we
1264   // therefore directly sign-extend or zero-extend the dividend into
1265   // lowreg, instead of copying, and ignore the highreg.
1266   const static struct DivRemEntry {
1267     // The following portion depends only on the data type.
1268     const TargetRegisterClass *RC;
1269     unsigned LowInReg;  // low part of the register pair
1270     unsigned HighInReg; // high part of the register pair
1271     // The following portion depends on both the data type and the operation.
1272     struct DivRemResult {
1273     unsigned OpDivRem;        // The specific DIV/IDIV opcode to use.
1274     unsigned OpSignExtend;    // Opcode for sign-extending lowreg into
1275                               // highreg, or copying a zero into highreg.
1276     unsigned OpCopy;          // Opcode for copying dividend into lowreg, or
1277                               // zero/sign-extending into lowreg for i8.
1278     unsigned DivRemResultReg; // Register containing the desired result.
1279     bool IsOpSigned;          // Whether to use signed or unsigned form.
1280     } ResultTable[NumOps];
1281   } OpTable[NumTypes] = {
1282     { &X86::GR8RegClass,  X86::AX,  0, {
1283         { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AL,  S }, // SDiv
1284         { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AH,  S }, // SRem
1285         { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AL,  U }, // UDiv
1286         { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AH,  U }, // URem
1287       }
1288     }, // i8
1289     { &X86::GR16RegClass, X86::AX,  X86::DX, {
1290         { X86::IDIV16r, X86::CWD,     Copy,            X86::AX,  S }, // SDiv
1291         { X86::IDIV16r, X86::CWD,     Copy,            X86::DX,  S }, // SRem
1292         { X86::DIV16r,  X86::MOV32r0, Copy,            X86::AX,  U }, // UDiv
1293         { X86::DIV16r,  X86::MOV32r0, Copy,            X86::DX,  U }, // URem
1294       }
1295     }, // i16
1296     { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1297         { X86::IDIV32r, X86::CDQ,     Copy,            X86::EAX, S }, // SDiv
1298         { X86::IDIV32r, X86::CDQ,     Copy,            X86::EDX, S }, // SRem
1299         { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EAX, U }, // UDiv
1300         { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EDX, U }, // URem
1301       }
1302     }, // i32
1303     { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1304         { X86::IDIV64r, X86::CQO,     Copy,            X86::RAX, S }, // SDiv
1305         { X86::IDIV64r, X86::CQO,     Copy,            X86::RDX, S }, // SRem
1306         { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RAX, U }, // UDiv
1307         { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RDX, U }, // URem
1308       }
1309     }, // i64
1310   };
1311
1312   MVT VT;
1313   if (!isTypeLegal(I->getType(), VT))
1314     return false;
1315
1316   unsigned TypeIndex, OpIndex;
1317   switch (VT.SimpleTy) {
1318   default: return false;
1319   case MVT::i8:  TypeIndex = 0; break;
1320   case MVT::i16: TypeIndex = 1; break;
1321   case MVT::i32: TypeIndex = 2; break;
1322   case MVT::i64: TypeIndex = 3;
1323     if (!Subtarget->is64Bit())
1324       return false;
1325     break;
1326   }
1327
1328   switch (I->getOpcode()) {
1329   default: llvm_unreachable("Unexpected div/rem opcode");
1330   case Instruction::SDiv: OpIndex = 0; break;
1331   case Instruction::SRem: OpIndex = 1; break;
1332   case Instruction::UDiv: OpIndex = 2; break;
1333   case Instruction::URem: OpIndex = 3; break;
1334   }
1335
1336   const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1337   const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1338   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1339   if (Op0Reg == 0)
1340     return false;
1341   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1342   if (Op1Reg == 0)
1343     return false;
1344
1345   // Move op0 into low-order input register.
1346   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1347           TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1348   // Zero-extend or sign-extend into high-order input register.
1349   if (OpEntry.OpSignExtend) {
1350     if (OpEntry.IsOpSigned)
1351       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1352               TII.get(OpEntry.OpSignExtend));
1353     else {
1354       unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1355       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1356               TII.get(X86::MOV32r0), Zero32);
1357
1358       // Copy the zero into the appropriate sub/super/identical physical
1359       // register. Unfortunately the operations needed are not uniform enough to
1360       // fit neatly into the table above.
1361       if (VT.SimpleTy == MVT::i16) {
1362         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1363                 TII.get(Copy), TypeEntry.HighInReg)
1364           .addReg(Zero32, 0, X86::sub_16bit);
1365       } else if (VT.SimpleTy == MVT::i32) {
1366         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1367                 TII.get(Copy), TypeEntry.HighInReg)
1368             .addReg(Zero32);
1369       } else if (VT.SimpleTy == MVT::i64) {
1370         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1371                 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1372             .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1373       }
1374     }
1375   }
1376   // Generate the DIV/IDIV instruction.
1377   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1378           TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1379   // For i8 remainder, we can't reference AH directly, as we'll end
1380   // up with bogus copies like %R9B = COPY %AH. Reference AX
1381   // instead to prevent AH references in a REX instruction.
1382   //
1383   // The current assumption of the fast register allocator is that isel
1384   // won't generate explicit references to the GPR8_NOREX registers. If
1385   // the allocator and/or the backend get enhanced to be more robust in
1386   // that regard, this can be, and should be, removed.
1387   unsigned ResultReg = 0;
1388   if ((I->getOpcode() == Instruction::SRem ||
1389        I->getOpcode() == Instruction::URem) &&
1390       OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1391     unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1392     unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1393     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1394             TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1395
1396     // Shift AX right by 8 bits instead of using AH.
1397     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SHR16ri),
1398             ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1399
1400     // Now reference the 8-bit subreg of the result.
1401     ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1402                                            /*Kill=*/true, X86::sub_8bit);
1403   }
1404   // Copy the result out of the physreg if we haven't already.
1405   if (!ResultReg) {
1406     ResultReg = createResultReg(TypeEntry.RC);
1407     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Copy), ResultReg)
1408         .addReg(OpEntry.DivRemResultReg);
1409   }
1410   UpdateValueMap(I, ResultReg);
1411
1412   return true;
1413 }
1414
1415 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1416   MVT VT;
1417   if (!isTypeLegal(I->getType(), VT))
1418     return false;
1419
1420   // We only use cmov here, if we don't have a cmov instruction bail.
1421   if (!Subtarget->hasCMov()) return false;
1422
1423   unsigned Opc = 0;
1424   const TargetRegisterClass *RC = NULL;
1425   if (VT == MVT::i16) {
1426     Opc = X86::CMOVE16rr;
1427     RC = &X86::GR16RegClass;
1428   } else if (VT == MVT::i32) {
1429     Opc = X86::CMOVE32rr;
1430     RC = &X86::GR32RegClass;
1431   } else if (VT == MVT::i64) {
1432     Opc = X86::CMOVE64rr;
1433     RC = &X86::GR64RegClass;
1434   } else {
1435     return false;
1436   }
1437
1438   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1439   if (Op0Reg == 0) return false;
1440   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1441   if (Op1Reg == 0) return false;
1442   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1443   if (Op2Reg == 0) return false;
1444
1445   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1446     .addReg(Op0Reg).addReg(Op0Reg);
1447   unsigned ResultReg = createResultReg(RC);
1448   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1449     .addReg(Op1Reg).addReg(Op2Reg);
1450   UpdateValueMap(I, ResultReg);
1451   return true;
1452 }
1453
1454 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1455   // fpext from float to double.
1456   if (X86ScalarSSEf64 &&
1457       I->getType()->isDoubleTy()) {
1458     const Value *V = I->getOperand(0);
1459     if (V->getType()->isFloatTy()) {
1460       unsigned OpReg = getRegForValue(V);
1461       if (OpReg == 0) return false;
1462       unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1463       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1464               TII.get(X86::CVTSS2SDrr), ResultReg)
1465         .addReg(OpReg);
1466       UpdateValueMap(I, ResultReg);
1467       return true;
1468     }
1469   }
1470
1471   return false;
1472 }
1473
1474 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1475   if (X86ScalarSSEf64) {
1476     if (I->getType()->isFloatTy()) {
1477       const Value *V = I->getOperand(0);
1478       if (V->getType()->isDoubleTy()) {
1479         unsigned OpReg = getRegForValue(V);
1480         if (OpReg == 0) return false;
1481         unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1482         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1483                 TII.get(X86::CVTSD2SSrr), ResultReg)
1484           .addReg(OpReg);
1485         UpdateValueMap(I, ResultReg);
1486         return true;
1487       }
1488     }
1489   }
1490
1491   return false;
1492 }
1493
1494 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1495   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1496   EVT DstVT = TLI.getValueType(I->getType());
1497
1498   // This code only handles truncation to byte.
1499   if (DstVT != MVT::i8 && DstVT != MVT::i1)
1500     return false;
1501   if (!TLI.isTypeLegal(SrcVT))
1502     return false;
1503
1504   unsigned InputReg = getRegForValue(I->getOperand(0));
1505   if (!InputReg)
1506     // Unhandled operand.  Halt "fast" selection and bail.
1507     return false;
1508
1509   if (SrcVT == MVT::i8) {
1510     // Truncate from i8 to i1; no code needed.
1511     UpdateValueMap(I, InputReg);
1512     return true;
1513   }
1514
1515   if (!Subtarget->is64Bit()) {
1516     // If we're on x86-32; we can't extract an i8 from a general register.
1517     // First issue a copy to GR16_ABCD or GR32_ABCD.
1518     const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1519       (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1520       (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1521     unsigned CopyReg = createResultReg(CopyRC);
1522     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1523             CopyReg).addReg(InputReg);
1524     InputReg = CopyReg;
1525   }
1526
1527   // Issue an extract_subreg.
1528   unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1529                                                   InputReg, /*Kill=*/true,
1530                                                   X86::sub_8bit);
1531   if (!ResultReg)
1532     return false;
1533
1534   UpdateValueMap(I, ResultReg);
1535   return true;
1536 }
1537
1538 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1539   return Len <= (Subtarget->is64Bit() ? 32 : 16);
1540 }
1541
1542 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1543                                      X86AddressMode SrcAM, uint64_t Len) {
1544
1545   // Make sure we don't bloat code by inlining very large memcpy's.
1546   if (!IsMemcpySmall(Len))
1547     return false;
1548
1549   bool i64Legal = Subtarget->is64Bit();
1550
1551   // We don't care about alignment here since we just emit integer accesses.
1552   while (Len) {
1553     MVT VT;
1554     if (Len >= 8 && i64Legal)
1555       VT = MVT::i64;
1556     else if (Len >= 4)
1557       VT = MVT::i32;
1558     else if (Len >= 2)
1559       VT = MVT::i16;
1560     else {
1561       VT = MVT::i8;
1562     }
1563
1564     unsigned Reg;
1565     bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1566     RV &= X86FastEmitStore(VT, Reg, DestAM);
1567     assert(RV && "Failed to emit load or store??");
1568
1569     unsigned Size = VT.getSizeInBits()/8;
1570     Len -= Size;
1571     DestAM.Disp += Size;
1572     SrcAM.Disp += Size;
1573   }
1574
1575   return true;
1576 }
1577
1578 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1579   // FIXME: Handle more intrinsics.
1580   switch (I.getIntrinsicID()) {
1581   default: return false;
1582   case Intrinsic::memcpy: {
1583     const MemCpyInst &MCI = cast<MemCpyInst>(I);
1584     // Don't handle volatile or variable length memcpys.
1585     if (MCI.isVolatile())
1586       return false;
1587
1588     if (isa<ConstantInt>(MCI.getLength())) {
1589       // Small memcpy's are common enough that we want to do them
1590       // without a call if possible.
1591       uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1592       if (IsMemcpySmall(Len)) {
1593         X86AddressMode DestAM, SrcAM;
1594         if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1595             !X86SelectAddress(MCI.getRawSource(), SrcAM))
1596           return false;
1597         TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1598         return true;
1599       }
1600     }
1601
1602     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1603     if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1604       return false;
1605
1606     if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1607       return false;
1608
1609     return DoSelectCall(&I, "memcpy");
1610   }
1611   case Intrinsic::memset: {
1612     const MemSetInst &MSI = cast<MemSetInst>(I);
1613
1614     if (MSI.isVolatile())
1615       return false;
1616
1617     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1618     if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1619       return false;
1620
1621     if (MSI.getDestAddressSpace() > 255)
1622       return false;
1623
1624     return DoSelectCall(&I, "memset");
1625   }
1626   case Intrinsic::stackprotector: {
1627     // Emit code to store the stack guard onto the stack.
1628     EVT PtrTy = TLI.getPointerTy();
1629
1630     const Value *Op1 = I.getArgOperand(0); // The guard's value.
1631     const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1632
1633     // Grab the frame index.
1634     X86AddressMode AM;
1635     if (!X86SelectAddress(Slot, AM)) return false;
1636     if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1637     return true;
1638   }
1639   case Intrinsic::dbg_declare: {
1640     const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1641     X86AddressMode AM;
1642     assert(DI->getAddress() && "Null address should be checked earlier!");
1643     if (!X86SelectAddress(DI->getAddress(), AM))
1644       return false;
1645     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1646     // FIXME may need to add RegState::Debug to any registers produced,
1647     // although ESP/EBP should be the only ones at the moment.
1648     addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1649       addImm(0).addMetadata(DI->getVariable());
1650     return true;
1651   }
1652   case Intrinsic::trap: {
1653     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1654     return true;
1655   }
1656   case Intrinsic::sadd_with_overflow:
1657   case Intrinsic::uadd_with_overflow: {
1658     // FIXME: Should fold immediates.
1659
1660     // Replace "add with overflow" intrinsics with an "add" instruction followed
1661     // by a seto/setc instruction.
1662     const Function *Callee = I.getCalledFunction();
1663     Type *RetTy =
1664       cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1665
1666     MVT VT;
1667     if (!isTypeLegal(RetTy, VT))
1668       return false;
1669
1670     const Value *Op1 = I.getArgOperand(0);
1671     const Value *Op2 = I.getArgOperand(1);
1672     unsigned Reg1 = getRegForValue(Op1);
1673     unsigned Reg2 = getRegForValue(Op2);
1674
1675     if (Reg1 == 0 || Reg2 == 0)
1676       // FIXME: Handle values *not* in registers.
1677       return false;
1678
1679     unsigned OpC = 0;
1680     if (VT == MVT::i32)
1681       OpC = X86::ADD32rr;
1682     else if (VT == MVT::i64)
1683       OpC = X86::ADD64rr;
1684     else
1685       return false;
1686
1687     // The call to CreateRegs builds two sequential registers, to store the
1688     // both the returned values.
1689     unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1690     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1691       .addReg(Reg1).addReg(Reg2);
1692
1693     unsigned Opc = X86::SETBr;
1694     if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1695       Opc = X86::SETOr;
1696     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1697
1698     UpdateValueMap(&I, ResultReg, 2);
1699     return true;
1700   }
1701   }
1702 }
1703
1704 bool X86FastISel::FastLowerArguments() {
1705   if (!FuncInfo.CanLowerReturn)
1706     return false;
1707
1708   if (Subtarget->isTargetWin64())
1709     return false;
1710
1711   const Function *F = FuncInfo.Fn;
1712   if (F->isVarArg())
1713     return false;
1714
1715   CallingConv::ID CC = F->getCallingConv();
1716   if (CC != CallingConv::C)
1717     return false;
1718   
1719   if (!Subtarget->is64Bit())
1720     return false;
1721   
1722   // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1723   unsigned Idx = 1;
1724   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1725        I != E; ++I, ++Idx) {
1726     if (Idx > 6)
1727       return false;
1728
1729     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1730         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1731         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1732         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1733       return false;
1734
1735     Type *ArgTy = I->getType();
1736     if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1737       return false;
1738
1739     EVT ArgVT = TLI.getValueType(ArgTy);
1740     if (!ArgVT.isSimple()) return false;
1741     switch (ArgVT.getSimpleVT().SimpleTy) {
1742     case MVT::i32:
1743     case MVT::i64:
1744       break;
1745     default:
1746       return false;
1747     }
1748   }
1749
1750   static const uint16_t GPR32ArgRegs[] = {
1751     X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1752   };
1753   static const uint16_t GPR64ArgRegs[] = {
1754     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1755   };
1756
1757   Idx = 0;
1758   const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1759   const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1760   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1761        I != E; ++I, ++Idx) {
1762     bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1763     const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1764     unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1765     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1766     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1767     // Without this, EmitLiveInCopies may eliminate the livein if its only
1768     // use is a bitcast (which isn't turned into an instruction).
1769     unsigned ResultReg = createResultReg(RC);
1770     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1771             ResultReg).addReg(DstReg, getKillRegState(true));
1772     UpdateValueMap(I, ResultReg);
1773   }
1774   return true;
1775 }
1776
1777 bool X86FastISel::X86SelectCall(const Instruction *I) {
1778   const CallInst *CI = cast<CallInst>(I);
1779   const Value *Callee = CI->getCalledValue();
1780
1781   // Can't handle inline asm yet.
1782   if (isa<InlineAsm>(Callee))
1783     return false;
1784
1785   // Handle intrinsic calls.
1786   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1787     return X86VisitIntrinsicCall(*II);
1788
1789   // Allow SelectionDAG isel to handle tail calls.
1790   if (cast<CallInst>(I)->isTailCall())
1791     return false;
1792
1793   return DoSelectCall(I, 0);
1794 }
1795
1796 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1797                                            const ImmutableCallSite &CS) {
1798   if (Subtarget.is64Bit())
1799     return 0;
1800   if (Subtarget.isTargetWindows())
1801     return 0;
1802   CallingConv::ID CC = CS.getCallingConv();
1803   if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1804     return 0;
1805   if (!CS.paramHasAttr(1, Attribute::StructRet))
1806     return 0;
1807   if (CS.paramHasAttr(1, Attribute::InReg))
1808     return 0;
1809   return 4;
1810 }
1811
1812 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1813 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1814   const CallInst *CI = cast<CallInst>(I);
1815   const Value *Callee = CI->getCalledValue();
1816
1817   // Handle only C and fastcc calling conventions for now.
1818   ImmutableCallSite CS(CI);
1819   CallingConv::ID CC = CS.getCallingConv();
1820   if (CC != CallingConv::C && CC != CallingConv::Fast &&
1821       CC != CallingConv::X86_FastCall)
1822     return false;
1823
1824   // fastcc with -tailcallopt is intended to provide a guaranteed
1825   // tail call optimization. Fastisel doesn't know how to do that.
1826   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1827     return false;
1828
1829   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1830   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1831   bool isVarArg = FTy->isVarArg();
1832
1833   // Don't know how to handle Win64 varargs yet.  Nothing special needed for
1834   // x86-32.  Special handling for x86-64 is implemented.
1835   if (isVarArg && Subtarget->isTargetWin64())
1836     return false;
1837
1838   // Fast-isel doesn't know about callee-pop yet.
1839   if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1840                        TM.Options.GuaranteedTailCallOpt))
1841     return false;
1842
1843   // Check whether the function can return without sret-demotion.
1844   SmallVector<ISD::OutputArg, 4> Outs;
1845   GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1846   bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1847                                            *FuncInfo.MF, FTy->isVarArg(),
1848                                            Outs, FTy->getContext());
1849   if (!CanLowerReturn)
1850     return false;
1851
1852   // Materialize callee address in a register. FIXME: GV address can be
1853   // handled with a CALLpcrel32 instead.
1854   X86AddressMode CalleeAM;
1855   if (!X86SelectCallAddress(Callee, CalleeAM))
1856     return false;
1857   unsigned CalleeOp = 0;
1858   const GlobalValue *GV = 0;
1859   if (CalleeAM.GV != 0) {
1860     GV = CalleeAM.GV;
1861   } else if (CalleeAM.Base.Reg != 0) {
1862     CalleeOp = CalleeAM.Base.Reg;
1863   } else
1864     return false;
1865
1866   // Deal with call operands first.
1867   SmallVector<const Value *, 8> ArgVals;
1868   SmallVector<unsigned, 8> Args;
1869   SmallVector<MVT, 8> ArgVTs;
1870   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1871   unsigned arg_size = CS.arg_size();
1872   Args.reserve(arg_size);
1873   ArgVals.reserve(arg_size);
1874   ArgVTs.reserve(arg_size);
1875   ArgFlags.reserve(arg_size);
1876   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1877        i != e; ++i) {
1878     // If we're lowering a mem intrinsic instead of a regular call, skip the
1879     // last two arguments, which should not passed to the underlying functions.
1880     if (MemIntName && e-i <= 2)
1881       break;
1882     Value *ArgVal = *i;
1883     ISD::ArgFlagsTy Flags;
1884     unsigned AttrInd = i - CS.arg_begin() + 1;
1885     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1886       Flags.setSExt();
1887     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1888       Flags.setZExt();
1889
1890     if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1891       PointerType *Ty = cast<PointerType>(ArgVal->getType());
1892       Type *ElementTy = Ty->getElementType();
1893       unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1894       unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1895       if (!FrameAlign)
1896         FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1897       Flags.setByVal();
1898       Flags.setByValSize(FrameSize);
1899       Flags.setByValAlign(FrameAlign);
1900       if (!IsMemcpySmall(FrameSize))
1901         return false;
1902     }
1903
1904     if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1905       Flags.setInReg();
1906     if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1907       Flags.setNest();
1908
1909     // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1910     // instruction.  This is safe because it is common to all fastisel supported
1911     // calling conventions on x86.
1912     if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1913       if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1914           CI->getBitWidth() == 16) {
1915         if (Flags.isSExt())
1916           ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1917         else
1918           ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1919       }
1920     }
1921
1922     unsigned ArgReg;
1923
1924     // Passing bools around ends up doing a trunc to i1 and passing it.
1925     // Codegen this as an argument + "and 1".
1926     if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1927         cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1928         ArgVal->hasOneUse()) {
1929       ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1930       ArgReg = getRegForValue(ArgVal);
1931       if (ArgReg == 0) return false;
1932
1933       MVT ArgVT;
1934       if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1935
1936       ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1937                            ArgVal->hasOneUse(), 1);
1938     } else {
1939       ArgReg = getRegForValue(ArgVal);
1940     }
1941
1942     if (ArgReg == 0) return false;
1943
1944     Type *ArgTy = ArgVal->getType();
1945     MVT ArgVT;
1946     if (!isTypeLegal(ArgTy, ArgVT))
1947       return false;
1948     if (ArgVT == MVT::x86mmx)
1949       return false;
1950     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1951     Flags.setOrigAlign(OriginalAlignment);
1952
1953     Args.push_back(ArgReg);
1954     ArgVals.push_back(ArgVal);
1955     ArgVTs.push_back(ArgVT);
1956     ArgFlags.push_back(Flags);
1957   }
1958
1959   // Analyze operands of the call, assigning locations to each operand.
1960   SmallVector<CCValAssign, 16> ArgLocs;
1961   CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1962                  I->getParent()->getContext());
1963
1964   // Allocate shadow area for Win64
1965   if (Subtarget->isTargetWin64())
1966     CCInfo.AllocateStack(32, 8);
1967
1968   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1969
1970   // Get a count of how many bytes are to be pushed on the stack.
1971   unsigned NumBytes = CCInfo.getNextStackOffset();
1972
1973   // Issue CALLSEQ_START
1974   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1975   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1976     .addImm(NumBytes);
1977
1978   // Process argument: walk the register/memloc assignments, inserting
1979   // copies / loads.
1980   SmallVector<unsigned, 4> RegArgs;
1981   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1982     CCValAssign &VA = ArgLocs[i];
1983     unsigned Arg = Args[VA.getValNo()];
1984     EVT ArgVT = ArgVTs[VA.getValNo()];
1985
1986     // Promote the value if needed.
1987     switch (VA.getLocInfo()) {
1988     case CCValAssign::Full: break;
1989     case CCValAssign::SExt: {
1990       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1991              "Unexpected extend");
1992       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1993                                        Arg, ArgVT, Arg);
1994       assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1995       ArgVT = VA.getLocVT();
1996       break;
1997     }
1998     case CCValAssign::ZExt: {
1999       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2000              "Unexpected extend");
2001       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2002                                        Arg, ArgVT, Arg);
2003       assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2004       ArgVT = VA.getLocVT();
2005       break;
2006     }
2007     case CCValAssign::AExt: {
2008       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2009              "Unexpected extend");
2010       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2011                                        Arg, ArgVT, Arg);
2012       if (!Emitted)
2013         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2014                                     Arg, ArgVT, Arg);
2015       if (!Emitted)
2016         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2017                                     Arg, ArgVT, Arg);
2018
2019       assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2020       ArgVT = VA.getLocVT();
2021       break;
2022     }
2023     case CCValAssign::BCvt: {
2024       unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2025                                ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2026       assert(BC != 0 && "Failed to emit a bitcast!");
2027       Arg = BC;
2028       ArgVT = VA.getLocVT();
2029       break;
2030     }
2031     case CCValAssign::VExt: 
2032       // VExt has not been implemented, so this should be impossible to reach
2033       // for now.  However, fallback to Selection DAG isel once implemented.
2034       return false;
2035     case CCValAssign::Indirect:
2036       // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2037       // support this.
2038       return false;
2039     }
2040
2041     if (VA.isRegLoc()) {
2042       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2043               VA.getLocReg()).addReg(Arg);
2044       RegArgs.push_back(VA.getLocReg());
2045     } else {
2046       unsigned LocMemOffset = VA.getLocMemOffset();
2047       X86AddressMode AM;
2048       const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2049           getTargetMachine()->getRegisterInfo());
2050       AM.Base.Reg = RegInfo->getStackRegister();
2051       AM.Disp = LocMemOffset;
2052       const Value *ArgVal = ArgVals[VA.getValNo()];
2053       ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2054
2055       if (Flags.isByVal()) {
2056         X86AddressMode SrcAM;
2057         SrcAM.Base.Reg = Arg;
2058         bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2059         assert(Res && "memcpy length already checked!"); (void)Res;
2060       } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2061         // If this is a really simple value, emit this with the Value* version
2062         // of X86FastEmitStore.  If it isn't simple, we don't want to do this,
2063         // as it can cause us to reevaluate the argument.
2064         if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2065           return false;
2066       } else {
2067         if (!X86FastEmitStore(ArgVT, Arg, AM))
2068           return false;
2069       }
2070     }
2071   }
2072
2073   // ELF / PIC requires GOT in the EBX register before function calls via PLT
2074   // GOT pointer.
2075   if (Subtarget->isPICStyleGOT()) {
2076     unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2077     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2078             X86::EBX).addReg(Base);
2079   }
2080
2081   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
2082     // Count the number of XMM registers allocated.
2083     static const uint16_t XMMArgRegs[] = {
2084       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2085       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2086     };
2087     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2088     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2089             X86::AL).addImm(NumXMMRegs);
2090   }
2091
2092   // Issue the call.
2093   MachineInstrBuilder MIB;
2094   if (CalleeOp) {
2095     // Register-indirect call.
2096     unsigned CallOpc;
2097     if (Subtarget->is64Bit())
2098       CallOpc = X86::CALL64r;
2099     else
2100       CallOpc = X86::CALL32r;
2101     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2102       .addReg(CalleeOp);
2103
2104   } else {
2105     // Direct call.
2106     assert(GV && "Not a direct call");
2107     unsigned CallOpc;
2108     if (Subtarget->is64Bit())
2109       CallOpc = X86::CALL64pcrel32;
2110     else
2111       CallOpc = X86::CALLpcrel32;
2112
2113     // See if we need any target-specific flags on the GV operand.
2114     unsigned char OpFlags = 0;
2115
2116     // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2117     // external symbols most go through the PLT in PIC mode.  If the symbol
2118     // has hidden or protected visibility, or if it is static or local, then
2119     // we don't need to use the PLT - we can directly call it.
2120     if (Subtarget->isTargetELF() &&
2121         TM.getRelocationModel() == Reloc::PIC_ &&
2122         GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2123       OpFlags = X86II::MO_PLT;
2124     } else if (Subtarget->isPICStyleStubAny() &&
2125                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2126                (!Subtarget->getTargetTriple().isMacOSX() ||
2127                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2128       // PC-relative references to external symbols should go through $stub,
2129       // unless we're building with the leopard linker or later, which
2130       // automatically synthesizes these stubs.
2131       OpFlags = X86II::MO_DARWIN_STUB;
2132     }
2133
2134
2135     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2136     if (MemIntName)
2137       MIB.addExternalSymbol(MemIntName, OpFlags);
2138     else
2139       MIB.addGlobalAddress(GV, 0, OpFlags);
2140   }
2141
2142   // Add a register mask with the call-preserved registers.
2143   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2144   MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2145
2146   // Add an implicit use GOT pointer in EBX.
2147   if (Subtarget->isPICStyleGOT())
2148     MIB.addReg(X86::EBX, RegState::Implicit);
2149
2150   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
2151     MIB.addReg(X86::AL, RegState::Implicit);
2152
2153   // Add implicit physical register uses to the call.
2154   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2155     MIB.addReg(RegArgs[i], RegState::Implicit);
2156
2157   // Issue CALLSEQ_END
2158   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2159   const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2160   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2161     .addImm(NumBytes).addImm(NumBytesCallee);
2162
2163   // Build info for return calling conv lowering code.
2164   // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2165   SmallVector<ISD::InputArg, 32> Ins;
2166   SmallVector<EVT, 4> RetTys;
2167   ComputeValueVTs(TLI, I->getType(), RetTys);
2168   for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2169     EVT VT = RetTys[i];
2170     MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2171     unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2172     for (unsigned j = 0; j != NumRegs; ++j) {
2173       ISD::InputArg MyFlags;
2174       MyFlags.VT = RegisterVT;
2175       MyFlags.Used = !CS.getInstruction()->use_empty();
2176       if (CS.paramHasAttr(0, Attribute::SExt))
2177         MyFlags.Flags.setSExt();
2178       if (CS.paramHasAttr(0, Attribute::ZExt))
2179         MyFlags.Flags.setZExt();
2180       if (CS.paramHasAttr(0, Attribute::InReg))
2181         MyFlags.Flags.setInReg();
2182       Ins.push_back(MyFlags);
2183     }
2184   }
2185
2186   // Now handle call return values.
2187   SmallVector<unsigned, 4> UsedRegs;
2188   SmallVector<CCValAssign, 16> RVLocs;
2189   CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2190                     I->getParent()->getContext());
2191   unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2192   CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2193   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2194     EVT CopyVT = RVLocs[i].getValVT();
2195     unsigned CopyReg = ResultReg + i;
2196
2197     // If this is a call to a function that returns an fp value on the x87 fp
2198     // stack, but where we prefer to use the value in xmm registers, copy it
2199     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2200     if ((RVLocs[i].getLocReg() == X86::ST0 ||
2201          RVLocs[i].getLocReg() == X86::ST1)) {
2202       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2203         CopyVT = MVT::f80;
2204         CopyReg = createResultReg(&X86::RFP80RegClass);
2205       }
2206       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2207               CopyReg);
2208     } else {
2209       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2210               CopyReg).addReg(RVLocs[i].getLocReg());
2211       UsedRegs.push_back(RVLocs[i].getLocReg());
2212     }
2213
2214     if (CopyVT != RVLocs[i].getValVT()) {
2215       // Round the F80 the right size, which also moves to the appropriate xmm
2216       // register. This is accomplished by storing the F80 value in memory and
2217       // then loading it back. Ewww...
2218       EVT ResVT = RVLocs[i].getValVT();
2219       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2220       unsigned MemSize = ResVT.getSizeInBits()/8;
2221       int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2222       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2223                                 TII.get(Opc)), FI)
2224         .addReg(CopyReg);
2225       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2226       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2227                                 TII.get(Opc), ResultReg + i), FI);
2228     }
2229   }
2230
2231   if (RVLocs.size())
2232     UpdateValueMap(I, ResultReg, RVLocs.size());
2233
2234   // Set all unused physreg defs as dead.
2235   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2236
2237   return true;
2238 }
2239
2240
2241 bool
2242 X86FastISel::TargetSelectInstruction(const Instruction *I)  {
2243   switch (I->getOpcode()) {
2244   default: break;
2245   case Instruction::Load:
2246     return X86SelectLoad(I);
2247   case Instruction::Store:
2248     return X86SelectStore(I);
2249   case Instruction::Ret:
2250     return X86SelectRet(I);
2251   case Instruction::ICmp:
2252   case Instruction::FCmp:
2253     return X86SelectCmp(I);
2254   case Instruction::ZExt:
2255     return X86SelectZExt(I);
2256   case Instruction::Br:
2257     return X86SelectBranch(I);
2258   case Instruction::Call:
2259     return X86SelectCall(I);
2260   case Instruction::LShr:
2261   case Instruction::AShr:
2262   case Instruction::Shl:
2263     return X86SelectShift(I);
2264   case Instruction::SDiv:
2265   case Instruction::UDiv:
2266   case Instruction::SRem:
2267   case Instruction::URem:
2268     return X86SelectDivRem(I);
2269   case Instruction::Select:
2270     return X86SelectSelect(I);
2271   case Instruction::Trunc:
2272     return X86SelectTrunc(I);
2273   case Instruction::FPExt:
2274     return X86SelectFPExt(I);
2275   case Instruction::FPTrunc:
2276     return X86SelectFPTrunc(I);
2277   case Instruction::IntToPtr: // Deliberate fall-through.
2278   case Instruction::PtrToInt: {
2279     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2280     EVT DstVT = TLI.getValueType(I->getType());
2281     if (DstVT.bitsGT(SrcVT))
2282       return X86SelectZExt(I);
2283     if (DstVT.bitsLT(SrcVT))
2284       return X86SelectTrunc(I);
2285     unsigned Reg = getRegForValue(I->getOperand(0));
2286     if (Reg == 0) return false;
2287     UpdateValueMap(I, Reg);
2288     return true;
2289   }
2290   }
2291
2292   return false;
2293 }
2294
2295 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2296   MVT VT;
2297   if (!isTypeLegal(C->getType(), VT))
2298     return 0;
2299
2300   // Can't handle alternate code models yet.
2301   if (TM.getCodeModel() != CodeModel::Small)
2302     return 0;
2303
2304   // Get opcode and regclass of the output for the given load instruction.
2305   unsigned Opc = 0;
2306   const TargetRegisterClass *RC = NULL;
2307   switch (VT.SimpleTy) {
2308   default: return 0;
2309   case MVT::i8:
2310     Opc = X86::MOV8rm;
2311     RC  = &X86::GR8RegClass;
2312     break;
2313   case MVT::i16:
2314     Opc = X86::MOV16rm;
2315     RC  = &X86::GR16RegClass;
2316     break;
2317   case MVT::i32:
2318     Opc = X86::MOV32rm;
2319     RC  = &X86::GR32RegClass;
2320     break;
2321   case MVT::i64:
2322     // Must be in x86-64 mode.
2323     Opc = X86::MOV64rm;
2324     RC  = &X86::GR64RegClass;
2325     break;
2326   case MVT::f32:
2327     if (X86ScalarSSEf32) {
2328       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2329       RC  = &X86::FR32RegClass;
2330     } else {
2331       Opc = X86::LD_Fp32m;
2332       RC  = &X86::RFP32RegClass;
2333     }
2334     break;
2335   case MVT::f64:
2336     if (X86ScalarSSEf64) {
2337       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2338       RC  = &X86::FR64RegClass;
2339     } else {
2340       Opc = X86::LD_Fp64m;
2341       RC  = &X86::RFP64RegClass;
2342     }
2343     break;
2344   case MVT::f80:
2345     // No f80 support yet.
2346     return 0;
2347   }
2348
2349   // Materialize addresses with LEA instructions.
2350   if (isa<GlobalValue>(C)) {
2351     X86AddressMode AM;
2352     if (X86SelectAddress(C, AM)) {
2353       // If the expression is just a basereg, then we're done, otherwise we need
2354       // to emit an LEA.
2355       if (AM.BaseType == X86AddressMode::RegBase &&
2356           AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2357         return AM.Base.Reg;
2358
2359       Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2360       unsigned ResultReg = createResultReg(RC);
2361       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2362                              TII.get(Opc), ResultReg), AM);
2363       return ResultReg;
2364     }
2365     return 0;
2366   }
2367
2368   // MachineConstantPool wants an explicit alignment.
2369   unsigned Align = TD.getPrefTypeAlignment(C->getType());
2370   if (Align == 0) {
2371     // Alignment of vector types.  FIXME!
2372     Align = TD.getTypeAllocSize(C->getType());
2373   }
2374
2375   // x86-32 PIC requires a PIC base register for constant pools.
2376   unsigned PICBase = 0;
2377   unsigned char OpFlag = 0;
2378   if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2379     OpFlag = X86II::MO_PIC_BASE_OFFSET;
2380     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2381   } else if (Subtarget->isPICStyleGOT()) {
2382     OpFlag = X86II::MO_GOTOFF;
2383     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2384   } else if (Subtarget->isPICStyleRIPRel() &&
2385              TM.getCodeModel() == CodeModel::Small) {
2386     PICBase = X86::RIP;
2387   }
2388
2389   // Create the load from the constant pool.
2390   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2391   unsigned ResultReg = createResultReg(RC);
2392   addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2393                                    TII.get(Opc), ResultReg),
2394                            MCPOffset, PICBase, OpFlag);
2395
2396   return ResultReg;
2397 }
2398
2399 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2400   // Fail on dynamic allocas. At this point, getRegForValue has already
2401   // checked its CSE maps, so if we're here trying to handle a dynamic
2402   // alloca, we're not going to succeed. X86SelectAddress has a
2403   // check for dynamic allocas, because it's called directly from
2404   // various places, but TargetMaterializeAlloca also needs a check
2405   // in order to avoid recursion between getRegForValue,
2406   // X86SelectAddrss, and TargetMaterializeAlloca.
2407   if (!FuncInfo.StaticAllocaMap.count(C))
2408     return 0;
2409
2410   X86AddressMode AM;
2411   if (!X86SelectAddress(C, AM))
2412     return 0;
2413   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2414   const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2415   unsigned ResultReg = createResultReg(RC);
2416   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2417                          TII.get(Opc), ResultReg), AM);
2418   return ResultReg;
2419 }
2420
2421 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2422   MVT VT;
2423   if (!isTypeLegal(CF->getType(), VT))
2424     return 0;
2425
2426   // Get opcode and regclass for the given zero.
2427   unsigned Opc = 0;
2428   const TargetRegisterClass *RC = NULL;
2429   switch (VT.SimpleTy) {
2430   default: return 0;
2431   case MVT::f32:
2432     if (X86ScalarSSEf32) {
2433       Opc = X86::FsFLD0SS;
2434       RC  = &X86::FR32RegClass;
2435     } else {
2436       Opc = X86::LD_Fp032;
2437       RC  = &X86::RFP32RegClass;
2438     }
2439     break;
2440   case MVT::f64:
2441     if (X86ScalarSSEf64) {
2442       Opc = X86::FsFLD0SD;
2443       RC  = &X86::FR64RegClass;
2444     } else {
2445       Opc = X86::LD_Fp064;
2446       RC  = &X86::RFP64RegClass;
2447     }
2448     break;
2449   case MVT::f80:
2450     // No f80 support yet.
2451     return 0;
2452   }
2453
2454   unsigned ResultReg = createResultReg(RC);
2455   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2456   return ResultReg;
2457 }
2458
2459
2460 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2461                                       const LoadInst *LI) {
2462   X86AddressMode AM;
2463   if (!X86SelectAddress(LI->getOperand(0), AM))
2464     return false;
2465
2466   const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2467
2468   unsigned Size = TD.getTypeAllocSize(LI->getType());
2469   unsigned Alignment = LI->getAlignment();
2470
2471   SmallVector<MachineOperand, 8> AddrOps;
2472   AM.getFullAddress(AddrOps);
2473
2474   MachineInstr *Result =
2475     XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2476   if (Result == 0) return false;
2477
2478   FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2479   MI->eraseFromParent();
2480   return true;
2481 }
2482
2483
2484 namespace llvm {
2485   FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2486                                 const TargetLibraryInfo *libInfo) {
2487     return new X86FastISel(funcInfo, libInfo);
2488   }
2489 }