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