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