X86: use sub-register sequences for MOV*r0 operations
[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   /// \brief 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 tryToFoldLoadIntoMI(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   MVT VT;
697   if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
698     return false;
699
700   X86AddressMode AM;
701   if (!X86SelectAddress(I->getOperand(1), AM))
702     return false;
703
704   return X86FastEmitStore(VT, I->getOperand(0), AM);
705 }
706
707 /// X86SelectRet - Select and emit code to implement ret instructions.
708 bool X86FastISel::X86SelectRet(const Instruction *I) {
709   const ReturnInst *Ret = cast<ReturnInst>(I);
710   const Function &F = *I->getParent()->getParent();
711   const X86MachineFunctionInfo *X86MFInfo =
712       FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
713
714   if (!FuncInfo.CanLowerReturn)
715     return false;
716
717   CallingConv::ID CC = F.getCallingConv();
718   if (CC != CallingConv::C &&
719       CC != CallingConv::Fast &&
720       CC != CallingConv::X86_FastCall)
721     return false;
722
723   if (Subtarget->isTargetWin64())
724     return false;
725
726   // Don't handle popping bytes on return for now.
727   if (X86MFInfo->getBytesToPopOnReturn() != 0)
728     return false;
729
730   // fastcc with -tailcallopt is intended to provide a guaranteed
731   // tail call optimization. Fastisel doesn't know how to do that.
732   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
733     return false;
734
735   // Let SDISel handle vararg functions.
736   if (F.isVarArg())
737     return false;
738
739   // Build a list of return value registers.
740   SmallVector<unsigned, 4> RetRegs;
741
742   if (Ret->getNumOperands() > 0) {
743     SmallVector<ISD::OutputArg, 4> Outs;
744     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
745
746     // Analyze operands of the call, assigning locations to each operand.
747     SmallVector<CCValAssign, 16> ValLocs;
748     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
749                    I->getContext());
750     CCInfo.AnalyzeReturn(Outs, RetCC_X86);
751
752     const Value *RV = Ret->getOperand(0);
753     unsigned Reg = getRegForValue(RV);
754     if (Reg == 0)
755       return false;
756
757     // Only handle a single return value for now.
758     if (ValLocs.size() != 1)
759       return false;
760
761     CCValAssign &VA = ValLocs[0];
762
763     // Don't bother handling odd stuff for now.
764     if (VA.getLocInfo() != CCValAssign::Full)
765       return false;
766     // Only handle register returns for now.
767     if (!VA.isRegLoc())
768       return false;
769
770     // The calling-convention tables for x87 returns don't tell
771     // the whole story.
772     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
773       return false;
774
775     unsigned SrcReg = Reg + VA.getValNo();
776     EVT SrcVT = TLI.getValueType(RV->getType());
777     EVT DstVT = VA.getValVT();
778     // Special handling for extended integers.
779     if (SrcVT != DstVT) {
780       if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
781         return false;
782
783       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
784         return false;
785
786       assert(DstVT == MVT::i32 && "X86 should always ext to i32");
787
788       if (SrcVT == MVT::i1) {
789         if (Outs[0].Flags.isSExt())
790           return false;
791         SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
792         SrcVT = MVT::i8;
793       }
794       unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
795                                              ISD::SIGN_EXTEND;
796       SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
797                           SrcReg, /*TODO: Kill=*/false);
798     }
799
800     // Make the copy.
801     unsigned DstReg = VA.getLocReg();
802     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
803     // Avoid a cross-class copy. This is very unlikely.
804     if (!SrcRC->contains(DstReg))
805       return false;
806     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
807             DstReg).addReg(SrcReg);
808
809     // Add register to return instruction.
810     RetRegs.push_back(VA.getLocReg());
811   }
812
813   // The x86-64 ABI for returning structs by value requires that we copy
814   // the sret argument into %rax for the return. We saved the argument into
815   // a virtual register in the entry block, so now we copy the value out
816   // and into %rax. We also do the same with %eax for Win32.
817   if (F.hasStructRetAttr() &&
818       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
819     unsigned Reg = X86MFInfo->getSRetReturnReg();
820     assert(Reg &&
821            "SRetReturnReg should have been set in LowerFormalArguments()!");
822     unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
823     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
824             RetReg).addReg(Reg);
825     RetRegs.push_back(RetReg);
826   }
827
828   // Now emit the RET.
829   MachineInstrBuilder MIB =
830     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
831   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
832     MIB.addReg(RetRegs[i], RegState::Implicit);
833   return true;
834 }
835
836 /// X86SelectLoad - Select and emit code to implement load instructions.
837 ///
838 bool X86FastISel::X86SelectLoad(const Instruction *I)  {
839   // Atomic loads need special handling.
840   if (cast<LoadInst>(I)->isAtomic())
841     return false;
842
843   MVT VT;
844   if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
845     return false;
846
847   X86AddressMode AM;
848   if (!X86SelectAddress(I->getOperand(0), AM))
849     return false;
850
851   unsigned ResultReg = 0;
852   if (X86FastEmitLoad(VT, AM, ResultReg)) {
853     UpdateValueMap(I, ResultReg);
854     return true;
855   }
856   return false;
857 }
858
859 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
860   bool HasAVX = Subtarget->hasAVX();
861   bool X86ScalarSSEf32 = Subtarget->hasSSE1();
862   bool X86ScalarSSEf64 = Subtarget->hasSSE2();
863
864   switch (VT.getSimpleVT().SimpleTy) {
865   default:       return 0;
866   case MVT::i8:  return X86::CMP8rr;
867   case MVT::i16: return X86::CMP16rr;
868   case MVT::i32: return X86::CMP32rr;
869   case MVT::i64: return X86::CMP64rr;
870   case MVT::f32:
871     return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
872   case MVT::f64:
873     return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
874   }
875 }
876
877 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
878 /// of the comparison, return an opcode that works for the compare (e.g.
879 /// CMP32ri) otherwise return 0.
880 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
881   switch (VT.getSimpleVT().SimpleTy) {
882   // Otherwise, we can't fold the immediate into this comparison.
883   default: return 0;
884   case MVT::i8: return X86::CMP8ri;
885   case MVT::i16: return X86::CMP16ri;
886   case MVT::i32: return X86::CMP32ri;
887   case MVT::i64:
888     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
889     // field.
890     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
891       return X86::CMP64ri32;
892     return 0;
893   }
894 }
895
896 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
897                                      EVT VT) {
898   unsigned Op0Reg = getRegForValue(Op0);
899   if (Op0Reg == 0) return false;
900
901   // Handle 'null' like i32/i64 0.
902   if (isa<ConstantPointerNull>(Op1))
903     Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
904
905   // We have two options: compare with register or immediate.  If the RHS of
906   // the compare is an immediate that we can fold into this compare, use
907   // CMPri, otherwise use CMPrr.
908   if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
909     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
910       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
911         .addReg(Op0Reg)
912         .addImm(Op1C->getSExtValue());
913       return true;
914     }
915   }
916
917   unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
918   if (CompareOpc == 0) return false;
919
920   unsigned Op1Reg = getRegForValue(Op1);
921   if (Op1Reg == 0) return false;
922   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
923     .addReg(Op0Reg)
924     .addReg(Op1Reg);
925
926   return true;
927 }
928
929 bool X86FastISel::X86SelectCmp(const Instruction *I) {
930   const CmpInst *CI = cast<CmpInst>(I);
931
932   MVT VT;
933   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
934     return false;
935
936   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
937   unsigned SetCCOpc;
938   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
939   switch (CI->getPredicate()) {
940   case CmpInst::FCMP_OEQ: {
941     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
942       return false;
943
944     unsigned EReg = createResultReg(&X86::GR8RegClass);
945     unsigned NPReg = createResultReg(&X86::GR8RegClass);
946     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
947     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
948             TII.get(X86::SETNPr), NPReg);
949     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
950             TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
951     UpdateValueMap(I, ResultReg);
952     return true;
953   }
954   case CmpInst::FCMP_UNE: {
955     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
956       return false;
957
958     unsigned NEReg = createResultReg(&X86::GR8RegClass);
959     unsigned PReg = createResultReg(&X86::GR8RegClass);
960     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
961     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
962     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
963       .addReg(PReg).addReg(NEReg);
964     UpdateValueMap(I, ResultReg);
965     return true;
966   }
967   case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
968   case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
969   case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
970   case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
971   case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
972   case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
973   case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
974   case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
975   case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
976   case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
977   case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
978   case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
979
980   case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
981   case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
982   case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
983   case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
984   case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
985   case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
986   case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
987   case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
988   case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
989   case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
990   default:
991     return false;
992   }
993
994   const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
995   if (SwapArgs)
996     std::swap(Op0, Op1);
997
998   // Emit a compare of Op0/Op1.
999   if (!X86FastEmitCompare(Op0, Op1, VT))
1000     return false;
1001
1002   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
1003   UpdateValueMap(I, ResultReg);
1004   return true;
1005 }
1006
1007 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1008   EVT DstVT = TLI.getValueType(I->getType());
1009   if (!TLI.isTypeLegal(DstVT))
1010     return false;
1011
1012   unsigned ResultReg = getRegForValue(I->getOperand(0));
1013   if (ResultReg == 0)
1014     return false;
1015
1016   // Handle zero-extension from i1 to i8, which is common.
1017   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()).getSimpleVT();
1018   if (SrcVT.SimpleTy == MVT::i1) {
1019     // Set the high bits to zero.
1020     ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1021     SrcVT = MVT::i8;
1022
1023     if (ResultReg == 0)
1024       return false;
1025   }
1026
1027   if (DstVT == MVT::i64) {
1028     // Handle extension to 64-bits via sub-register shenanigans.
1029     unsigned MovInst;
1030
1031     switch (SrcVT.SimpleTy) {
1032     case MVT::i8:  MovInst = X86::MOVZX32rr8;  break;
1033     case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1034     case MVT::i32: MovInst = X86::MOV32rr;     break;
1035     default: llvm_unreachable("Unexpected zext to i64 source type");
1036     }
1037
1038     unsigned Result32 = createResultReg(&X86::GR32RegClass);
1039     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32)
1040       .addReg(ResultReg);
1041
1042     ResultReg = createResultReg(&X86::GR64RegClass);
1043     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG),
1044             ResultReg)
1045       .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1046   } else if (DstVT != MVT::i8) {
1047     ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1048                            ResultReg, /*Kill=*/true);
1049     if (ResultReg == 0)
1050       return false;
1051   }
1052
1053   UpdateValueMap(I, ResultReg);
1054   return true;
1055 }
1056
1057
1058 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1059   // Unconditional branches are selected by tablegen-generated code.
1060   // Handle a conditional branch.
1061   const BranchInst *BI = cast<BranchInst>(I);
1062   MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1063   MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1064
1065   // Fold the common case of a conditional branch with a comparison
1066   // in the same block (values defined on other blocks may not have
1067   // initialized registers).
1068   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1069     if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1070       EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1071
1072       // Try to take advantage of fallthrough opportunities.
1073       CmpInst::Predicate Predicate = CI->getPredicate();
1074       if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1075         std::swap(TrueMBB, FalseMBB);
1076         Predicate = CmpInst::getInversePredicate(Predicate);
1077       }
1078
1079       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
1080       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1081
1082       switch (Predicate) {
1083       case CmpInst::FCMP_OEQ:
1084         std::swap(TrueMBB, FalseMBB);
1085         Predicate = CmpInst::FCMP_UNE;
1086         // FALL THROUGH
1087       case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1088       case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1089       case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1090       case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA_4;  break;
1091       case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE_4; break;
1092       case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1093       case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1094       case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4;  break;
1095       case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4;  break;
1096       case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB_4;  break;
1097       case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE_4; break;
1098       case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1099       case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1100
1101       case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE_4;  break;
1102       case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE_4; break;
1103       case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1104       case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1105       case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1106       case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1107       case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4;  break;
1108       case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1109       case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4;  break;
1110       case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1111       default:
1112         return false;
1113       }
1114
1115       const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1116       if (SwapArgs)
1117         std::swap(Op0, Op1);
1118
1119       // Emit a compare of the LHS and RHS, setting the flags.
1120       if (!X86FastEmitCompare(Op0, Op1, VT))
1121         return false;
1122
1123       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1124         .addMBB(TrueMBB);
1125
1126       if (Predicate == CmpInst::FCMP_UNE) {
1127         // X86 requires a second branch to handle UNE (and OEQ,
1128         // which is mapped to UNE above).
1129         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1130           .addMBB(TrueMBB);
1131       }
1132
1133       FastEmitBranch(FalseMBB, DL);
1134       FuncInfo.MBB->addSuccessor(TrueMBB);
1135       return true;
1136     }
1137   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1138     // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1139     // typically happen for _Bool and C++ bools.
1140     MVT SourceVT;
1141     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1142         isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1143       unsigned TestOpc = 0;
1144       switch (SourceVT.SimpleTy) {
1145       default: break;
1146       case MVT::i8:  TestOpc = X86::TEST8ri; break;
1147       case MVT::i16: TestOpc = X86::TEST16ri; break;
1148       case MVT::i32: TestOpc = X86::TEST32ri; break;
1149       case MVT::i64: TestOpc = X86::TEST64ri32; break;
1150       }
1151       if (TestOpc) {
1152         unsigned OpReg = getRegForValue(TI->getOperand(0));
1153         if (OpReg == 0) return false;
1154         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1155           .addReg(OpReg).addImm(1);
1156
1157         unsigned JmpOpc = X86::JNE_4;
1158         if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1159           std::swap(TrueMBB, FalseMBB);
1160           JmpOpc = X86::JE_4;
1161         }
1162
1163         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1164           .addMBB(TrueMBB);
1165         FastEmitBranch(FalseMBB, DL);
1166         FuncInfo.MBB->addSuccessor(TrueMBB);
1167         return true;
1168       }
1169     }
1170   }
1171
1172   // Otherwise do a clumsy setcc and re-test it.
1173   // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1174   // in an explicit cast, so make sure to handle that correctly.
1175   unsigned OpReg = getRegForValue(BI->getCondition());
1176   if (OpReg == 0) return false;
1177
1178   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1179     .addReg(OpReg).addImm(1);
1180   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1181     .addMBB(TrueMBB);
1182   FastEmitBranch(FalseMBB, DL);
1183   FuncInfo.MBB->addSuccessor(TrueMBB);
1184   return true;
1185 }
1186
1187 bool X86FastISel::X86SelectShift(const Instruction *I) {
1188   unsigned CReg = 0, OpReg = 0;
1189   const TargetRegisterClass *RC = NULL;
1190   if (I->getType()->isIntegerTy(8)) {
1191     CReg = X86::CL;
1192     RC = &X86::GR8RegClass;
1193     switch (I->getOpcode()) {
1194     case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1195     case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1196     case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
1197     default: return false;
1198     }
1199   } else if (I->getType()->isIntegerTy(16)) {
1200     CReg = X86::CX;
1201     RC = &X86::GR16RegClass;
1202     switch (I->getOpcode()) {
1203     case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1204     case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1205     case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
1206     default: return false;
1207     }
1208   } else if (I->getType()->isIntegerTy(32)) {
1209     CReg = X86::ECX;
1210     RC = &X86::GR32RegClass;
1211     switch (I->getOpcode()) {
1212     case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1213     case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1214     case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
1215     default: return false;
1216     }
1217   } else if (I->getType()->isIntegerTy(64)) {
1218     CReg = X86::RCX;
1219     RC = &X86::GR64RegClass;
1220     switch (I->getOpcode()) {
1221     case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1222     case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1223     case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
1224     default: return false;
1225     }
1226   } else {
1227     return false;
1228   }
1229
1230   MVT VT;
1231   if (!isTypeLegal(I->getType(), VT))
1232     return false;
1233
1234   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1235   if (Op0Reg == 0) return false;
1236
1237   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1238   if (Op1Reg == 0) return false;
1239   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1240           CReg).addReg(Op1Reg);
1241
1242   // The shift instruction uses X86::CL. If we defined a super-register
1243   // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1244   if (CReg != X86::CL)
1245     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1246             TII.get(TargetOpcode::KILL), X86::CL)
1247       .addReg(CReg, RegState::Kill);
1248
1249   unsigned ResultReg = createResultReg(RC);
1250   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1251     .addReg(Op0Reg);
1252   UpdateValueMap(I, ResultReg);
1253   return true;
1254 }
1255
1256 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1257   const static unsigned NumTypes = 4; // i8, i16, i32, i64
1258   const static unsigned NumOps   = 4; // SDiv, SRem, UDiv, URem
1259   const static bool S = true;  // IsSigned
1260   const static bool U = false; // !IsSigned
1261   const static unsigned Copy = TargetOpcode::COPY;
1262   // For the X86 DIV/IDIV instruction, in most cases the dividend
1263   // (numerator) must be in a specific register pair highreg:lowreg,
1264   // producing the quotient in lowreg and the remainder in highreg.
1265   // For most data types, to set up the instruction, the dividend is
1266   // copied into lowreg, and lowreg is sign-extended or zero-extended
1267   // into highreg.  The exception is i8, where the dividend is defined
1268   // as a single register rather than a register pair, and we
1269   // therefore directly sign-extend or zero-extend the dividend into
1270   // lowreg, instead of copying, and ignore the highreg.
1271   const static struct DivRemEntry {
1272     // The following portion depends only on the data type.
1273     const TargetRegisterClass *RC;
1274     unsigned LowInReg;  // low part of the register pair
1275     unsigned HighInReg; // high part of the register pair
1276     // The following portion depends on both the data type and the operation.
1277     struct DivRemResult {
1278     unsigned OpDivRem;        // The specific DIV/IDIV opcode to use.
1279     unsigned OpSignExtend;    // Opcode for sign-extending lowreg into
1280                               // highreg, or copying a zero into highreg.
1281     unsigned OpCopy;          // Opcode for copying dividend into lowreg, or
1282                               // zero/sign-extending into lowreg for i8.
1283     unsigned DivRemResultReg; // Register containing the desired result.
1284     bool IsOpSigned;          // Whether to use signed or unsigned form.
1285     } ResultTable[NumOps];
1286   } OpTable[NumTypes] = {
1287     { &X86::GR8RegClass,  X86::AX,  0, {
1288         { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AL,  S }, // SDiv
1289         { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AH,  S }, // SRem
1290         { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AL,  U }, // UDiv
1291         { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AH,  U }, // URem
1292       }
1293     }, // i8
1294     { &X86::GR16RegClass, X86::AX,  X86::DX, {
1295         { X86::IDIV16r, X86::CWD,     Copy,            X86::AX,  S }, // SDiv
1296         { X86::IDIV16r, X86::CWD,     Copy,            X86::DX,  S }, // SRem
1297         { X86::DIV16r,  X86::MOV32r0, Copy,            X86::AX,  U }, // UDiv
1298         { X86::DIV16r,  X86::MOV32r0, Copy,            X86::DX,  U }, // URem
1299       }
1300     }, // i16
1301     { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1302         { X86::IDIV32r, X86::CDQ,     Copy,            X86::EAX, S }, // SDiv
1303         { X86::IDIV32r, X86::CDQ,     Copy,            X86::EDX, S }, // SRem
1304         { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EAX, U }, // UDiv
1305         { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EDX, U }, // URem
1306       }
1307     }, // i32
1308     { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1309         { X86::IDIV64r, X86::CQO,     Copy,            X86::RAX, S }, // SDiv
1310         { X86::IDIV64r, X86::CQO,     Copy,            X86::RDX, S }, // SRem
1311         { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RAX, U }, // UDiv
1312         { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RDX, U }, // URem
1313       }
1314     }, // i64
1315   };
1316
1317   MVT VT;
1318   if (!isTypeLegal(I->getType(), VT))
1319     return false;
1320
1321   unsigned TypeIndex, OpIndex;
1322   switch (VT.SimpleTy) {
1323   default: return false;
1324   case MVT::i8:  TypeIndex = 0; break;
1325   case MVT::i16: TypeIndex = 1; break;
1326   case MVT::i32: TypeIndex = 2; break;
1327   case MVT::i64: TypeIndex = 3;
1328     if (!Subtarget->is64Bit())
1329       return false;
1330     break;
1331   }
1332
1333   switch (I->getOpcode()) {
1334   default: llvm_unreachable("Unexpected div/rem opcode");
1335   case Instruction::SDiv: OpIndex = 0; break;
1336   case Instruction::SRem: OpIndex = 1; break;
1337   case Instruction::UDiv: OpIndex = 2; break;
1338   case Instruction::URem: OpIndex = 3; break;
1339   }
1340
1341   const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1342   const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1343   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1344   if (Op0Reg == 0)
1345     return false;
1346   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1347   if (Op1Reg == 0)
1348     return false;
1349
1350   // Move op0 into low-order input register.
1351   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1352           TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1353   // Zero-extend or sign-extend into high-order input register.
1354   if (OpEntry.OpSignExtend) {
1355     if (OpEntry.IsOpSigned)
1356       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1357               TII.get(OpEntry.OpSignExtend));
1358     else {
1359       unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1360       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1361               TII.get(X86::MOV32r0), Zero32);
1362
1363       // Copy the zero into the appropriate sub/super/identical physical
1364       // register. Unfortunately the operations needed are not uniform enough to
1365       // fit neatly into the table above.
1366       if (VT.SimpleTy == MVT::i16) {
1367         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1368                 TII.get(TargetOpcode::COPY), TypeEntry.HighInReg)
1369           .addReg(Zero32, 0, X86::sub_16bit);
1370       } else if (VT.SimpleTy == MVT::i32) {
1371         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1372                 TII.get(TargetOpcode::COPY), TypeEntry.HighInReg)
1373             .addReg(Zero32);
1374       } else if (VT.SimpleTy == MVT::i64) {
1375         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1376                 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1377             .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1378       }
1379     }
1380   }
1381   // Generate the DIV/IDIV instruction.
1382   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1383           TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1384   // Copy output register into result register.
1385   unsigned ResultReg = createResultReg(TypeEntry.RC);
1386   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1387           TII.get(Copy), ResultReg).addReg(OpEntry.DivRemResultReg);
1388   UpdateValueMap(I, ResultReg);
1389
1390   return true;
1391 }
1392
1393 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1394   MVT VT;
1395   if (!isTypeLegal(I->getType(), VT))
1396     return false;
1397
1398   // We only use cmov here, if we don't have a cmov instruction bail.
1399   if (!Subtarget->hasCMov()) return false;
1400
1401   unsigned Opc = 0;
1402   const TargetRegisterClass *RC = NULL;
1403   if (VT == MVT::i16) {
1404     Opc = X86::CMOVE16rr;
1405     RC = &X86::GR16RegClass;
1406   } else if (VT == MVT::i32) {
1407     Opc = X86::CMOVE32rr;
1408     RC = &X86::GR32RegClass;
1409   } else if (VT == MVT::i64) {
1410     Opc = X86::CMOVE64rr;
1411     RC = &X86::GR64RegClass;
1412   } else {
1413     return false;
1414   }
1415
1416   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1417   if (Op0Reg == 0) return false;
1418   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1419   if (Op1Reg == 0) return false;
1420   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1421   if (Op2Reg == 0) return false;
1422
1423   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1424     .addReg(Op0Reg).addReg(Op0Reg);
1425   unsigned ResultReg = createResultReg(RC);
1426   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1427     .addReg(Op1Reg).addReg(Op2Reg);
1428   UpdateValueMap(I, ResultReg);
1429   return true;
1430 }
1431
1432 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1433   // fpext from float to double.
1434   if (X86ScalarSSEf64 &&
1435       I->getType()->isDoubleTy()) {
1436     const Value *V = I->getOperand(0);
1437     if (V->getType()->isFloatTy()) {
1438       unsigned OpReg = getRegForValue(V);
1439       if (OpReg == 0) return false;
1440       unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1441       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1442               TII.get(X86::CVTSS2SDrr), ResultReg)
1443         .addReg(OpReg);
1444       UpdateValueMap(I, ResultReg);
1445       return true;
1446     }
1447   }
1448
1449   return false;
1450 }
1451
1452 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1453   if (X86ScalarSSEf64) {
1454     if (I->getType()->isFloatTy()) {
1455       const Value *V = I->getOperand(0);
1456       if (V->getType()->isDoubleTy()) {
1457         unsigned OpReg = getRegForValue(V);
1458         if (OpReg == 0) return false;
1459         unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1460         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1461                 TII.get(X86::CVTSD2SSrr), ResultReg)
1462           .addReg(OpReg);
1463         UpdateValueMap(I, ResultReg);
1464         return true;
1465       }
1466     }
1467   }
1468
1469   return false;
1470 }
1471
1472 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1473   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1474   EVT DstVT = TLI.getValueType(I->getType());
1475
1476   // This code only handles truncation to byte.
1477   if (DstVT != MVT::i8 && DstVT != MVT::i1)
1478     return false;
1479   if (!TLI.isTypeLegal(SrcVT))
1480     return false;
1481
1482   unsigned InputReg = getRegForValue(I->getOperand(0));
1483   if (!InputReg)
1484     // Unhandled operand.  Halt "fast" selection and bail.
1485     return false;
1486
1487   if (SrcVT == MVT::i8) {
1488     // Truncate from i8 to i1; no code needed.
1489     UpdateValueMap(I, InputReg);
1490     return true;
1491   }
1492
1493   if (!Subtarget->is64Bit()) {
1494     // If we're on x86-32; we can't extract an i8 from a general register.
1495     // First issue a copy to GR16_ABCD or GR32_ABCD.
1496     const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1497       (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1498       (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1499     unsigned CopyReg = createResultReg(CopyRC);
1500     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1501             CopyReg).addReg(InputReg);
1502     InputReg = CopyReg;
1503   }
1504
1505   // Issue an extract_subreg.
1506   unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1507                                                   InputReg, /*Kill=*/true,
1508                                                   X86::sub_8bit);
1509   if (!ResultReg)
1510     return false;
1511
1512   UpdateValueMap(I, ResultReg);
1513   return true;
1514 }
1515
1516 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1517   return Len <= (Subtarget->is64Bit() ? 32 : 16);
1518 }
1519
1520 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1521                                      X86AddressMode SrcAM, uint64_t Len) {
1522
1523   // Make sure we don't bloat code by inlining very large memcpy's.
1524   if (!IsMemcpySmall(Len))
1525     return false;
1526
1527   bool i64Legal = Subtarget->is64Bit();
1528
1529   // We don't care about alignment here since we just emit integer accesses.
1530   while (Len) {
1531     MVT VT;
1532     if (Len >= 8 && i64Legal)
1533       VT = MVT::i64;
1534     else if (Len >= 4)
1535       VT = MVT::i32;
1536     else if (Len >= 2)
1537       VT = MVT::i16;
1538     else {
1539       VT = MVT::i8;
1540     }
1541
1542     unsigned Reg;
1543     bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1544     RV &= X86FastEmitStore(VT, Reg, DestAM);
1545     assert(RV && "Failed to emit load or store??");
1546
1547     unsigned Size = VT.getSizeInBits()/8;
1548     Len -= Size;
1549     DestAM.Disp += Size;
1550     SrcAM.Disp += Size;
1551   }
1552
1553   return true;
1554 }
1555
1556 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1557   // FIXME: Handle more intrinsics.
1558   switch (I.getIntrinsicID()) {
1559   default: return false;
1560   case Intrinsic::memcpy: {
1561     const MemCpyInst &MCI = cast<MemCpyInst>(I);
1562     // Don't handle volatile or variable length memcpys.
1563     if (MCI.isVolatile())
1564       return false;
1565
1566     if (isa<ConstantInt>(MCI.getLength())) {
1567       // Small memcpy's are common enough that we want to do them
1568       // without a call if possible.
1569       uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1570       if (IsMemcpySmall(Len)) {
1571         X86AddressMode DestAM, SrcAM;
1572         if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1573             !X86SelectAddress(MCI.getRawSource(), SrcAM))
1574           return false;
1575         TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1576         return true;
1577       }
1578     }
1579
1580     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1581     if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1582       return false;
1583
1584     if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1585       return false;
1586
1587     return DoSelectCall(&I, "memcpy");
1588   }
1589   case Intrinsic::memset: {
1590     const MemSetInst &MSI = cast<MemSetInst>(I);
1591
1592     if (MSI.isVolatile())
1593       return false;
1594
1595     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1596     if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1597       return false;
1598
1599     if (MSI.getDestAddressSpace() > 255)
1600       return false;
1601
1602     return DoSelectCall(&I, "memset");
1603   }
1604   case Intrinsic::stackprotector: {
1605     // Emit code to store the stack guard onto the stack.
1606     EVT PtrTy = TLI.getPointerTy();
1607
1608     const Value *Op1 = I.getArgOperand(0); // The guard's value.
1609     const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1610
1611     // Grab the frame index.
1612     X86AddressMode AM;
1613     if (!X86SelectAddress(Slot, AM)) return false;
1614     if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1615     return true;
1616   }
1617   case Intrinsic::dbg_declare: {
1618     const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1619     X86AddressMode AM;
1620     assert(DI->getAddress() && "Null address should be checked earlier!");
1621     if (!X86SelectAddress(DI->getAddress(), AM))
1622       return false;
1623     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1624     // FIXME may need to add RegState::Debug to any registers produced,
1625     // although ESP/EBP should be the only ones at the moment.
1626     addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1627       addImm(0).addMetadata(DI->getVariable());
1628     return true;
1629   }
1630   case Intrinsic::trap: {
1631     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1632     return true;
1633   }
1634   case Intrinsic::sadd_with_overflow:
1635   case Intrinsic::uadd_with_overflow: {
1636     // FIXME: Should fold immediates.
1637
1638     // Replace "add with overflow" intrinsics with an "add" instruction followed
1639     // by a seto/setc instruction.
1640     const Function *Callee = I.getCalledFunction();
1641     Type *RetTy =
1642       cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1643
1644     MVT VT;
1645     if (!isTypeLegal(RetTy, VT))
1646       return false;
1647
1648     const Value *Op1 = I.getArgOperand(0);
1649     const Value *Op2 = I.getArgOperand(1);
1650     unsigned Reg1 = getRegForValue(Op1);
1651     unsigned Reg2 = getRegForValue(Op2);
1652
1653     if (Reg1 == 0 || Reg2 == 0)
1654       // FIXME: Handle values *not* in registers.
1655       return false;
1656
1657     unsigned OpC = 0;
1658     if (VT == MVT::i32)
1659       OpC = X86::ADD32rr;
1660     else if (VT == MVT::i64)
1661       OpC = X86::ADD64rr;
1662     else
1663       return false;
1664
1665     // The call to CreateRegs builds two sequential registers, to store the
1666     // both the returned values.
1667     unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1668     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1669       .addReg(Reg1).addReg(Reg2);
1670
1671     unsigned Opc = X86::SETBr;
1672     if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1673       Opc = X86::SETOr;
1674     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1675
1676     UpdateValueMap(&I, ResultReg, 2);
1677     return true;
1678   }
1679   }
1680 }
1681
1682 bool X86FastISel::FastLowerArguments() {
1683   if (!FuncInfo.CanLowerReturn)
1684     return false;
1685
1686   if (Subtarget->isTargetWin64())
1687     return false;
1688
1689   const Function *F = FuncInfo.Fn;
1690   if (F->isVarArg())
1691     return false;
1692
1693   CallingConv::ID CC = F->getCallingConv();
1694   if (CC != CallingConv::C)
1695     return false;
1696   
1697   if (!Subtarget->is64Bit())
1698     return false;
1699   
1700   // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1701   unsigned Idx = 1;
1702   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1703        I != E; ++I, ++Idx) {
1704     if (Idx > 6)
1705       return false;
1706
1707     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1708         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1709         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1710         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1711       return false;
1712
1713     Type *ArgTy = I->getType();
1714     if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1715       return false;
1716
1717     EVT ArgVT = TLI.getValueType(ArgTy);
1718     if (!ArgVT.isSimple()) return false;
1719     switch (ArgVT.getSimpleVT().SimpleTy) {
1720     case MVT::i32:
1721     case MVT::i64:
1722       break;
1723     default:
1724       return false;
1725     }
1726   }
1727
1728   static const uint16_t GPR32ArgRegs[] = {
1729     X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1730   };
1731   static const uint16_t GPR64ArgRegs[] = {
1732     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1733   };
1734
1735   Idx = 0;
1736   const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1737   const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1738   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1739        I != E; ++I, ++Idx) {
1740     if (I->use_empty())
1741       continue;
1742     bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1743     const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1744     unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1745     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1746     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1747     // Without this, EmitLiveInCopies may eliminate the livein if its only
1748     // use is a bitcast (which isn't turned into an instruction).
1749     unsigned ResultReg = createResultReg(RC);
1750     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1751             ResultReg).addReg(DstReg, getKillRegState(true));
1752     UpdateValueMap(I, ResultReg);
1753   }
1754   return true;
1755 }
1756
1757 bool X86FastISel::X86SelectCall(const Instruction *I) {
1758   const CallInst *CI = cast<CallInst>(I);
1759   const Value *Callee = CI->getCalledValue();
1760
1761   // Can't handle inline asm yet.
1762   if (isa<InlineAsm>(Callee))
1763     return false;
1764
1765   // Handle intrinsic calls.
1766   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1767     return X86VisitIntrinsicCall(*II);
1768
1769   // Allow SelectionDAG isel to handle tail calls.
1770   if (cast<CallInst>(I)->isTailCall())
1771     return false;
1772
1773   return DoSelectCall(I, 0);
1774 }
1775
1776 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1777                                            const ImmutableCallSite &CS) {
1778   if (Subtarget.is64Bit())
1779     return 0;
1780   if (Subtarget.isTargetWindows())
1781     return 0;
1782   CallingConv::ID CC = CS.getCallingConv();
1783   if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1784     return 0;
1785   if (!CS.paramHasAttr(1, Attribute::StructRet))
1786     return 0;
1787   if (CS.paramHasAttr(1, Attribute::InReg))
1788     return 0;
1789   return 4;
1790 }
1791
1792 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1793 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1794   const CallInst *CI = cast<CallInst>(I);
1795   const Value *Callee = CI->getCalledValue();
1796
1797   // Handle only C and fastcc calling conventions for now.
1798   ImmutableCallSite CS(CI);
1799   CallingConv::ID CC = CS.getCallingConv();
1800   if (CC != CallingConv::C && CC != CallingConv::Fast &&
1801       CC != CallingConv::X86_FastCall)
1802     return false;
1803
1804   // fastcc with -tailcallopt is intended to provide a guaranteed
1805   // tail call optimization. Fastisel doesn't know how to do that.
1806   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1807     return false;
1808
1809   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1810   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1811   bool isVarArg = FTy->isVarArg();
1812
1813   // Don't know how to handle Win64 varargs yet.  Nothing special needed for
1814   // x86-32.  Special handling for x86-64 is implemented.
1815   if (isVarArg && Subtarget->isTargetWin64())
1816     return false;
1817
1818   // Fast-isel doesn't know about callee-pop yet.
1819   if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1820                        TM.Options.GuaranteedTailCallOpt))
1821     return false;
1822
1823   // Check whether the function can return without sret-demotion.
1824   SmallVector<ISD::OutputArg, 4> Outs;
1825   GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1826   bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1827                                            *FuncInfo.MF, FTy->isVarArg(),
1828                                            Outs, FTy->getContext());
1829   if (!CanLowerReturn)
1830     return false;
1831
1832   // Materialize callee address in a register. FIXME: GV address can be
1833   // handled with a CALLpcrel32 instead.
1834   X86AddressMode CalleeAM;
1835   if (!X86SelectCallAddress(Callee, CalleeAM))
1836     return false;
1837   unsigned CalleeOp = 0;
1838   const GlobalValue *GV = 0;
1839   if (CalleeAM.GV != 0) {
1840     GV = CalleeAM.GV;
1841   } else if (CalleeAM.Base.Reg != 0) {
1842     CalleeOp = CalleeAM.Base.Reg;
1843   } else
1844     return false;
1845
1846   // Deal with call operands first.
1847   SmallVector<const Value *, 8> ArgVals;
1848   SmallVector<unsigned, 8> Args;
1849   SmallVector<MVT, 8> ArgVTs;
1850   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1851   unsigned arg_size = CS.arg_size();
1852   Args.reserve(arg_size);
1853   ArgVals.reserve(arg_size);
1854   ArgVTs.reserve(arg_size);
1855   ArgFlags.reserve(arg_size);
1856   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1857        i != e; ++i) {
1858     // If we're lowering a mem intrinsic instead of a regular call, skip the
1859     // last two arguments, which should not passed to the underlying functions.
1860     if (MemIntName && e-i <= 2)
1861       break;
1862     Value *ArgVal = *i;
1863     ISD::ArgFlagsTy Flags;
1864     unsigned AttrInd = i - CS.arg_begin() + 1;
1865     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1866       Flags.setSExt();
1867     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1868       Flags.setZExt();
1869
1870     if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1871       PointerType *Ty = cast<PointerType>(ArgVal->getType());
1872       Type *ElementTy = Ty->getElementType();
1873       unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1874       unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1875       if (!FrameAlign)
1876         FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1877       Flags.setByVal();
1878       Flags.setByValSize(FrameSize);
1879       Flags.setByValAlign(FrameAlign);
1880       if (!IsMemcpySmall(FrameSize))
1881         return false;
1882     }
1883
1884     if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1885       Flags.setInReg();
1886     if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1887       Flags.setNest();
1888
1889     // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1890     // instruction.  This is safe because it is common to all fastisel supported
1891     // calling conventions on x86.
1892     if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1893       if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1894           CI->getBitWidth() == 16) {
1895         if (Flags.isSExt())
1896           ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1897         else
1898           ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1899       }
1900     }
1901
1902     unsigned ArgReg;
1903
1904     // Passing bools around ends up doing a trunc to i1 and passing it.
1905     // Codegen this as an argument + "and 1".
1906     if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1907         cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1908         ArgVal->hasOneUse()) {
1909       ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1910       ArgReg = getRegForValue(ArgVal);
1911       if (ArgReg == 0) return false;
1912
1913       MVT ArgVT;
1914       if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1915
1916       ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1917                            ArgVal->hasOneUse(), 1);
1918     } else {
1919       ArgReg = getRegForValue(ArgVal);
1920     }
1921
1922     if (ArgReg == 0) return false;
1923
1924     Type *ArgTy = ArgVal->getType();
1925     MVT ArgVT;
1926     if (!isTypeLegal(ArgTy, ArgVT))
1927       return false;
1928     if (ArgVT == MVT::x86mmx)
1929       return false;
1930     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1931     Flags.setOrigAlign(OriginalAlignment);
1932
1933     Args.push_back(ArgReg);
1934     ArgVals.push_back(ArgVal);
1935     ArgVTs.push_back(ArgVT);
1936     ArgFlags.push_back(Flags);
1937   }
1938
1939   // Analyze operands of the call, assigning locations to each operand.
1940   SmallVector<CCValAssign, 16> ArgLocs;
1941   CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1942                  I->getParent()->getContext());
1943
1944   // Allocate shadow area for Win64
1945   if (Subtarget->isTargetWin64())
1946     CCInfo.AllocateStack(32, 8);
1947
1948   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1949
1950   // Get a count of how many bytes are to be pushed on the stack.
1951   unsigned NumBytes = CCInfo.getNextStackOffset();
1952
1953   // Issue CALLSEQ_START
1954   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1955   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1956     .addImm(NumBytes);
1957
1958   // Process argument: walk the register/memloc assignments, inserting
1959   // copies / loads.
1960   SmallVector<unsigned, 4> RegArgs;
1961   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1962     CCValAssign &VA = ArgLocs[i];
1963     unsigned Arg = Args[VA.getValNo()];
1964     EVT ArgVT = ArgVTs[VA.getValNo()];
1965
1966     // Promote the value if needed.
1967     switch (VA.getLocInfo()) {
1968     case CCValAssign::Full: break;
1969     case CCValAssign::SExt: {
1970       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1971              "Unexpected extend");
1972       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1973                                        Arg, ArgVT, Arg);
1974       assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1975       ArgVT = VA.getLocVT();
1976       break;
1977     }
1978     case CCValAssign::ZExt: {
1979       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1980              "Unexpected extend");
1981       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1982                                        Arg, ArgVT, Arg);
1983       assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1984       ArgVT = VA.getLocVT();
1985       break;
1986     }
1987     case CCValAssign::AExt: {
1988       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1989              "Unexpected extend");
1990       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1991                                        Arg, ArgVT, Arg);
1992       if (!Emitted)
1993         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1994                                     Arg, ArgVT, Arg);
1995       if (!Emitted)
1996         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1997                                     Arg, ArgVT, Arg);
1998
1999       assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2000       ArgVT = VA.getLocVT();
2001       break;
2002     }
2003     case CCValAssign::BCvt: {
2004       unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2005                                ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2006       assert(BC != 0 && "Failed to emit a bitcast!");
2007       Arg = BC;
2008       ArgVT = VA.getLocVT();
2009       break;
2010     }
2011     case CCValAssign::VExt: 
2012       // VExt has not been implemented, so this should be impossible to reach
2013       // for now.  However, fallback to Selection DAG isel once implemented.
2014       return false;
2015     case CCValAssign::Indirect:
2016       // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2017       // support this.
2018       return false;
2019     }
2020
2021     if (VA.isRegLoc()) {
2022       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2023               VA.getLocReg()).addReg(Arg);
2024       RegArgs.push_back(VA.getLocReg());
2025     } else {
2026       unsigned LocMemOffset = VA.getLocMemOffset();
2027       X86AddressMode AM;
2028       AM.Base.Reg = RegInfo->getStackRegister();
2029       AM.Disp = LocMemOffset;
2030       const Value *ArgVal = ArgVals[VA.getValNo()];
2031       ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2032
2033       if (Flags.isByVal()) {
2034         X86AddressMode SrcAM;
2035         SrcAM.Base.Reg = Arg;
2036         bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2037         assert(Res && "memcpy length already checked!"); (void)Res;
2038       } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2039         // If this is a really simple value, emit this with the Value* version
2040         // of X86FastEmitStore.  If it isn't simple, we don't want to do this,
2041         // as it can cause us to reevaluate the argument.
2042         if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2043           return false;
2044       } else {
2045         if (!X86FastEmitStore(ArgVT, Arg, AM))
2046           return false;
2047       }
2048     }
2049   }
2050
2051   // ELF / PIC requires GOT in the EBX register before function calls via PLT
2052   // GOT pointer.
2053   if (Subtarget->isPICStyleGOT()) {
2054     unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2055     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2056             X86::EBX).addReg(Base);
2057   }
2058
2059   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
2060     // Count the number of XMM registers allocated.
2061     static const uint16_t XMMArgRegs[] = {
2062       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2063       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2064     };
2065     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2066     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2067             X86::AL).addImm(NumXMMRegs);
2068   }
2069
2070   // Issue the call.
2071   MachineInstrBuilder MIB;
2072   if (CalleeOp) {
2073     // Register-indirect call.
2074     unsigned CallOpc;
2075     if (Subtarget->is64Bit())
2076       CallOpc = X86::CALL64r;
2077     else
2078       CallOpc = X86::CALL32r;
2079     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2080       .addReg(CalleeOp);
2081
2082   } else {
2083     // Direct call.
2084     assert(GV && "Not a direct call");
2085     unsigned CallOpc;
2086     if (Subtarget->is64Bit())
2087       CallOpc = X86::CALL64pcrel32;
2088     else
2089       CallOpc = X86::CALLpcrel32;
2090
2091     // See if we need any target-specific flags on the GV operand.
2092     unsigned char OpFlags = 0;
2093
2094     // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2095     // external symbols most go through the PLT in PIC mode.  If the symbol
2096     // has hidden or protected visibility, or if it is static or local, then
2097     // we don't need to use the PLT - we can directly call it.
2098     if (Subtarget->isTargetELF() &&
2099         TM.getRelocationModel() == Reloc::PIC_ &&
2100         GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2101       OpFlags = X86II::MO_PLT;
2102     } else if (Subtarget->isPICStyleStubAny() &&
2103                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2104                (!Subtarget->getTargetTriple().isMacOSX() ||
2105                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2106       // PC-relative references to external symbols should go through $stub,
2107       // unless we're building with the leopard linker or later, which
2108       // automatically synthesizes these stubs.
2109       OpFlags = X86II::MO_DARWIN_STUB;
2110     }
2111
2112
2113     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2114     if (MemIntName)
2115       MIB.addExternalSymbol(MemIntName, OpFlags);
2116     else
2117       MIB.addGlobalAddress(GV, 0, OpFlags);
2118   }
2119
2120   // Add a register mask with the call-preserved registers.
2121   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2122   MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2123
2124   // Add an implicit use GOT pointer in EBX.
2125   if (Subtarget->isPICStyleGOT())
2126     MIB.addReg(X86::EBX, RegState::Implicit);
2127
2128   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
2129     MIB.addReg(X86::AL, RegState::Implicit);
2130
2131   // Add implicit physical register uses to the call.
2132   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2133     MIB.addReg(RegArgs[i], RegState::Implicit);
2134
2135   // Issue CALLSEQ_END
2136   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2137   const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2138   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2139     .addImm(NumBytes).addImm(NumBytesCallee);
2140
2141   // Build info for return calling conv lowering code.
2142   // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2143   SmallVector<ISD::InputArg, 32> Ins;
2144   SmallVector<EVT, 4> RetTys;
2145   ComputeValueVTs(TLI, I->getType(), RetTys);
2146   for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2147     EVT VT = RetTys[i];
2148     MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2149     unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2150     for (unsigned j = 0; j != NumRegs; ++j) {
2151       ISD::InputArg MyFlags;
2152       MyFlags.VT = RegisterVT;
2153       MyFlags.Used = !CS.getInstruction()->use_empty();
2154       if (CS.paramHasAttr(0, Attribute::SExt))
2155         MyFlags.Flags.setSExt();
2156       if (CS.paramHasAttr(0, Attribute::ZExt))
2157         MyFlags.Flags.setZExt();
2158       if (CS.paramHasAttr(0, Attribute::InReg))
2159         MyFlags.Flags.setInReg();
2160       Ins.push_back(MyFlags);
2161     }
2162   }
2163
2164   // Now handle call return values.
2165   SmallVector<unsigned, 4> UsedRegs;
2166   SmallVector<CCValAssign, 16> RVLocs;
2167   CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2168                     I->getParent()->getContext());
2169   unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2170   CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2171   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2172     EVT CopyVT = RVLocs[i].getValVT();
2173     unsigned CopyReg = ResultReg + i;
2174
2175     // If this is a call to a function that returns an fp value on the x87 fp
2176     // stack, but where we prefer to use the value in xmm registers, copy it
2177     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2178     if ((RVLocs[i].getLocReg() == X86::ST0 ||
2179          RVLocs[i].getLocReg() == X86::ST1)) {
2180       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2181         CopyVT = MVT::f80;
2182         CopyReg = createResultReg(&X86::RFP80RegClass);
2183       }
2184       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2185               CopyReg);
2186     } else {
2187       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2188               CopyReg).addReg(RVLocs[i].getLocReg());
2189       UsedRegs.push_back(RVLocs[i].getLocReg());
2190     }
2191
2192     if (CopyVT != RVLocs[i].getValVT()) {
2193       // Round the F80 the right size, which also moves to the appropriate xmm
2194       // register. This is accomplished by storing the F80 value in memory and
2195       // then loading it back. Ewww...
2196       EVT ResVT = RVLocs[i].getValVT();
2197       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2198       unsigned MemSize = ResVT.getSizeInBits()/8;
2199       int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2200       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2201                                 TII.get(Opc)), FI)
2202         .addReg(CopyReg);
2203       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2204       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2205                                 TII.get(Opc), ResultReg + i), FI);
2206     }
2207   }
2208
2209   if (RVLocs.size())
2210     UpdateValueMap(I, ResultReg, RVLocs.size());
2211
2212   // Set all unused physreg defs as dead.
2213   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2214
2215   return true;
2216 }
2217
2218
2219 bool
2220 X86FastISel::TargetSelectInstruction(const Instruction *I)  {
2221   switch (I->getOpcode()) {
2222   default: break;
2223   case Instruction::Load:
2224     return X86SelectLoad(I);
2225   case Instruction::Store:
2226     return X86SelectStore(I);
2227   case Instruction::Ret:
2228     return X86SelectRet(I);
2229   case Instruction::ICmp:
2230   case Instruction::FCmp:
2231     return X86SelectCmp(I);
2232   case Instruction::ZExt:
2233     return X86SelectZExt(I);
2234   case Instruction::Br:
2235     return X86SelectBranch(I);
2236   case Instruction::Call:
2237     return X86SelectCall(I);
2238   case Instruction::LShr:
2239   case Instruction::AShr:
2240   case Instruction::Shl:
2241     return X86SelectShift(I);
2242   case Instruction::SDiv:
2243   case Instruction::UDiv:
2244   case Instruction::SRem:
2245   case Instruction::URem:
2246     return X86SelectDivRem(I);
2247   case Instruction::Select:
2248     return X86SelectSelect(I);
2249   case Instruction::Trunc:
2250     return X86SelectTrunc(I);
2251   case Instruction::FPExt:
2252     return X86SelectFPExt(I);
2253   case Instruction::FPTrunc:
2254     return X86SelectFPTrunc(I);
2255   case Instruction::IntToPtr: // Deliberate fall-through.
2256   case Instruction::PtrToInt: {
2257     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2258     EVT DstVT = TLI.getValueType(I->getType());
2259     if (DstVT.bitsGT(SrcVT))
2260       return X86SelectZExt(I);
2261     if (DstVT.bitsLT(SrcVT))
2262       return X86SelectTrunc(I);
2263     unsigned Reg = getRegForValue(I->getOperand(0));
2264     if (Reg == 0) return false;
2265     UpdateValueMap(I, Reg);
2266     return true;
2267   }
2268   }
2269
2270   return false;
2271 }
2272
2273 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2274   MVT VT;
2275   if (!isTypeLegal(C->getType(), VT))
2276     return 0;
2277
2278   // Can't handle alternate code models yet.
2279   if (TM.getCodeModel() != CodeModel::Small)
2280     return 0;
2281
2282   // Get opcode and regclass of the output for the given load instruction.
2283   unsigned Opc = 0;
2284   const TargetRegisterClass *RC = NULL;
2285   switch (VT.SimpleTy) {
2286   default: return 0;
2287   case MVT::i8:
2288     Opc = X86::MOV8rm;
2289     RC  = &X86::GR8RegClass;
2290     break;
2291   case MVT::i16:
2292     Opc = X86::MOV16rm;
2293     RC  = &X86::GR16RegClass;
2294     break;
2295   case MVT::i32:
2296     Opc = X86::MOV32rm;
2297     RC  = &X86::GR32RegClass;
2298     break;
2299   case MVT::i64:
2300     // Must be in x86-64 mode.
2301     Opc = X86::MOV64rm;
2302     RC  = &X86::GR64RegClass;
2303     break;
2304   case MVT::f32:
2305     if (X86ScalarSSEf32) {
2306       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2307       RC  = &X86::FR32RegClass;
2308     } else {
2309       Opc = X86::LD_Fp32m;
2310       RC  = &X86::RFP32RegClass;
2311     }
2312     break;
2313   case MVT::f64:
2314     if (X86ScalarSSEf64) {
2315       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2316       RC  = &X86::FR64RegClass;
2317     } else {
2318       Opc = X86::LD_Fp64m;
2319       RC  = &X86::RFP64RegClass;
2320     }
2321     break;
2322   case MVT::f80:
2323     // No f80 support yet.
2324     return 0;
2325   }
2326
2327   // Materialize addresses with LEA instructions.
2328   if (isa<GlobalValue>(C)) {
2329     X86AddressMode AM;
2330     if (X86SelectAddress(C, AM)) {
2331       // If the expression is just a basereg, then we're done, otherwise we need
2332       // to emit an LEA.
2333       if (AM.BaseType == X86AddressMode::RegBase &&
2334           AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2335         return AM.Base.Reg;
2336
2337       Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2338       unsigned ResultReg = createResultReg(RC);
2339       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2340                              TII.get(Opc), ResultReg), AM);
2341       return ResultReg;
2342     }
2343     return 0;
2344   }
2345
2346   // MachineConstantPool wants an explicit alignment.
2347   unsigned Align = TD.getPrefTypeAlignment(C->getType());
2348   if (Align == 0) {
2349     // Alignment of vector types.  FIXME!
2350     Align = TD.getTypeAllocSize(C->getType());
2351   }
2352
2353   // x86-32 PIC requires a PIC base register for constant pools.
2354   unsigned PICBase = 0;
2355   unsigned char OpFlag = 0;
2356   if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2357     OpFlag = X86II::MO_PIC_BASE_OFFSET;
2358     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2359   } else if (Subtarget->isPICStyleGOT()) {
2360     OpFlag = X86II::MO_GOTOFF;
2361     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2362   } else if (Subtarget->isPICStyleRIPRel() &&
2363              TM.getCodeModel() == CodeModel::Small) {
2364     PICBase = X86::RIP;
2365   }
2366
2367   // Create the load from the constant pool.
2368   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2369   unsigned ResultReg = createResultReg(RC);
2370   addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2371                                    TII.get(Opc), ResultReg),
2372                            MCPOffset, PICBase, OpFlag);
2373
2374   return ResultReg;
2375 }
2376
2377 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2378   // Fail on dynamic allocas. At this point, getRegForValue has already
2379   // checked its CSE maps, so if we're here trying to handle a dynamic
2380   // alloca, we're not going to succeed. X86SelectAddress has a
2381   // check for dynamic allocas, because it's called directly from
2382   // various places, but TargetMaterializeAlloca also needs a check
2383   // in order to avoid recursion between getRegForValue,
2384   // X86SelectAddrss, and TargetMaterializeAlloca.
2385   if (!FuncInfo.StaticAllocaMap.count(C))
2386     return 0;
2387
2388   X86AddressMode AM;
2389   if (!X86SelectAddress(C, AM))
2390     return 0;
2391   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2392   const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2393   unsigned ResultReg = createResultReg(RC);
2394   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2395                          TII.get(Opc), ResultReg), AM);
2396   return ResultReg;
2397 }
2398
2399 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2400   MVT VT;
2401   if (!isTypeLegal(CF->getType(), VT))
2402     return 0;
2403
2404   // Get opcode and regclass for the given zero.
2405   unsigned Opc = 0;
2406   const TargetRegisterClass *RC = NULL;
2407   switch (VT.SimpleTy) {
2408   default: return 0;
2409   case MVT::f32:
2410     if (X86ScalarSSEf32) {
2411       Opc = X86::FsFLD0SS;
2412       RC  = &X86::FR32RegClass;
2413     } else {
2414       Opc = X86::LD_Fp032;
2415       RC  = &X86::RFP32RegClass;
2416     }
2417     break;
2418   case MVT::f64:
2419     if (X86ScalarSSEf64) {
2420       Opc = X86::FsFLD0SD;
2421       RC  = &X86::FR64RegClass;
2422     } else {
2423       Opc = X86::LD_Fp064;
2424       RC  = &X86::RFP64RegClass;
2425     }
2426     break;
2427   case MVT::f80:
2428     // No f80 support yet.
2429     return 0;
2430   }
2431
2432   unsigned ResultReg = createResultReg(RC);
2433   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2434   return ResultReg;
2435 }
2436
2437
2438 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2439                                       const LoadInst *LI) {
2440   X86AddressMode AM;
2441   if (!X86SelectAddress(LI->getOperand(0), AM))
2442     return false;
2443
2444   const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2445
2446   unsigned Size = TD.getTypeAllocSize(LI->getType());
2447   unsigned Alignment = LI->getAlignment();
2448
2449   SmallVector<MachineOperand, 8> AddrOps;
2450   AM.getFullAddress(AddrOps);
2451
2452   MachineInstr *Result =
2453     XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2454   if (Result == 0) return false;
2455
2456   FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2457   MI->eraseFromParent();
2458   return true;
2459 }
2460
2461
2462 namespace llvm {
2463   FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2464                                 const TargetLibraryInfo *libInfo) {
2465     return new X86FastISel(funcInfo, libInfo);
2466   }
2467 }