Revert 132404 to appease a buildbot. rdar://problem/5993888
[oota-llvm.git] / lib / Target / X86 / X86FastISel.cpp
1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/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 X86VisitIntrinsicCall(const IntrinsicInst &I);
112   bool X86SelectCall(const Instruction *I);
113
114   const X86InstrInfo *getInstrInfo() const {
115     return getTargetMachine()->getInstrInfo();
116   }
117   const X86TargetMachine *getTargetMachine() const {
118     return static_cast<const X86TargetMachine *>(&TM);
119   }
120
121   unsigned TargetMaterializeConstant(const Constant *C);
122
123   unsigned TargetMaterializeAlloca(const AllocaInst *C);
124
125   unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
126
127   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
128   /// computed in an SSE register, not on the X87 floating point stack.
129   bool isScalarFPTypeInSSEReg(EVT VT) const {
130     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
131       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
132   }
133
134   bool isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1 = false);
135
136   bool IsMemcpySmall(uint64_t Len);
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
728     // The calling-convention tables for x87 returns don't tell
729     // the whole story.
730     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
731       return false;
732
733     unsigned SrcReg = Reg + VA.getValNo();
734     EVT SrcVT = TLI.getValueType(RV->getType());
735     EVT DstVT = VA.getValVT();
736     // Special handling for extended integers.
737     if (SrcVT != DstVT) {
738       if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
739         return false;
740
741       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
742         return false;
743
744       assert(DstVT == MVT::i32 && "X86 should always ext to i32");
745
746       if (SrcVT == MVT::i1) {
747         if (Outs[0].Flags.isSExt())
748           return false;
749         SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
750         SrcVT = MVT::i8;
751       }
752       unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
753                                              ISD::SIGN_EXTEND;
754       SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
755                           SrcReg, /*TODO: Kill=*/false);
756     }
757
758     // Make the copy.
759     unsigned DstReg = VA.getLocReg();
760     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
761     // Avoid a cross-class copy. This is very unlikely.
762     if (!SrcRC->contains(DstReg))
763       return false;
764     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
765             DstReg).addReg(SrcReg);
766
767     // Mark the register as live out of the function.
768     MRI.addLiveOut(VA.getLocReg());
769   }
770
771   // Now emit the RET.
772   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
773   return true;
774 }
775
776 /// X86SelectLoad - Select and emit code to implement load instructions.
777 ///
778 bool X86FastISel::X86SelectLoad(const Instruction *I)  {
779   MVT VT;
780   if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
781     return false;
782
783   X86AddressMode AM;
784   if (!X86SelectAddress(I->getOperand(0), AM))
785     return false;
786
787   unsigned ResultReg = 0;
788   if (X86FastEmitLoad(VT, AM, ResultReg)) {
789     UpdateValueMap(I, ResultReg);
790     return true;
791   }
792   return false;
793 }
794
795 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
796   switch (VT.getSimpleVT().SimpleTy) {
797   default:       return 0;
798   case MVT::i8:  return X86::CMP8rr;
799   case MVT::i16: return X86::CMP16rr;
800   case MVT::i32: return X86::CMP32rr;
801   case MVT::i64: return X86::CMP64rr;
802   case MVT::f32: return Subtarget->hasSSE1() ? X86::UCOMISSrr : 0;
803   case MVT::f64: return Subtarget->hasSSE2() ? X86::UCOMISDrr : 0;
804   }
805 }
806
807 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
808 /// of the comparison, return an opcode that works for the compare (e.g.
809 /// CMP32ri) otherwise return 0.
810 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
811   switch (VT.getSimpleVT().SimpleTy) {
812   // Otherwise, we can't fold the immediate into this comparison.
813   default: return 0;
814   case MVT::i8: return X86::CMP8ri;
815   case MVT::i16: return X86::CMP16ri;
816   case MVT::i32: return X86::CMP32ri;
817   case MVT::i64:
818     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
819     // field.
820     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
821       return X86::CMP64ri32;
822     return 0;
823   }
824 }
825
826 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
827                                      EVT VT) {
828   unsigned Op0Reg = getRegForValue(Op0);
829   if (Op0Reg == 0) return false;
830
831   // Handle 'null' like i32/i64 0.
832   if (isa<ConstantPointerNull>(Op1))
833     Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
834
835   // We have two options: compare with register or immediate.  If the RHS of
836   // the compare is an immediate that we can fold into this compare, use
837   // CMPri, otherwise use CMPrr.
838   if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
839     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
840       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
841         .addReg(Op0Reg)
842         .addImm(Op1C->getSExtValue());
843       return true;
844     }
845   }
846
847   unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
848   if (CompareOpc == 0) return false;
849
850   unsigned Op1Reg = getRegForValue(Op1);
851   if (Op1Reg == 0) return false;
852   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
853     .addReg(Op0Reg)
854     .addReg(Op1Reg);
855
856   return true;
857 }
858
859 bool X86FastISel::X86SelectCmp(const Instruction *I) {
860   const CmpInst *CI = cast<CmpInst>(I);
861
862   MVT VT;
863   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
864     return false;
865
866   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
867   unsigned SetCCOpc;
868   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
869   switch (CI->getPredicate()) {
870   case CmpInst::FCMP_OEQ: {
871     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
872       return false;
873
874     unsigned EReg = createResultReg(&X86::GR8RegClass);
875     unsigned NPReg = createResultReg(&X86::GR8RegClass);
876     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
877     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
878             TII.get(X86::SETNPr), NPReg);
879     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
880             TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
881     UpdateValueMap(I, ResultReg);
882     return true;
883   }
884   case CmpInst::FCMP_UNE: {
885     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
886       return false;
887
888     unsigned NEReg = createResultReg(&X86::GR8RegClass);
889     unsigned PReg = createResultReg(&X86::GR8RegClass);
890     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
891     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
892     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
893       .addReg(PReg).addReg(NEReg);
894     UpdateValueMap(I, ResultReg);
895     return true;
896   }
897   case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
898   case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
899   case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
900   case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
901   case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
902   case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
903   case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
904   case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
905   case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
906   case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
907   case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
908   case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
909
910   case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
911   case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
912   case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
913   case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
914   case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
915   case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
916   case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
917   case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
918   case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
919   case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
920   default:
921     return false;
922   }
923
924   const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
925   if (SwapArgs)
926     std::swap(Op0, Op1);
927
928   // Emit a compare of Op0/Op1.
929   if (!X86FastEmitCompare(Op0, Op1, VT))
930     return false;
931
932   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
933   UpdateValueMap(I, ResultReg);
934   return true;
935 }
936
937 bool X86FastISel::X86SelectZExt(const Instruction *I) {
938   // Handle zero-extension from i1 to i8, which is common.
939   if (!I->getOperand(0)->getType()->isIntegerTy(1)) 
940     return false;
941
942   EVT DstVT = TLI.getValueType(I->getType());
943   if (!TLI.isTypeLegal(DstVT))
944     return false;
945
946   unsigned ResultReg = getRegForValue(I->getOperand(0));
947   if (ResultReg == 0)
948     return false;
949
950   // Set the high bits to zero.
951   ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
952   if (ResultReg == 0)
953     return false;
954
955   if (DstVT != MVT::i8) {
956     ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
957                            ResultReg, /*Kill=*/true);
958     if (ResultReg == 0)
959       return false;
960   }
961
962   UpdateValueMap(I, ResultReg);
963   return true;
964 }
965
966
967 bool X86FastISel::X86SelectBranch(const Instruction *I) {
968   // Unconditional branches are selected by tablegen-generated code.
969   // Handle a conditional branch.
970   const BranchInst *BI = cast<BranchInst>(I);
971   MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
972   MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
973
974   // Fold the common case of a conditional branch with a comparison
975   // in the same block (values defined on other blocks may not have
976   // initialized registers).
977   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
978     if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
979       EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
980
981       // Try to take advantage of fallthrough opportunities.
982       CmpInst::Predicate Predicate = CI->getPredicate();
983       if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
984         std::swap(TrueMBB, FalseMBB);
985         Predicate = CmpInst::getInversePredicate(Predicate);
986       }
987
988       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
989       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
990
991       switch (Predicate) {
992       case CmpInst::FCMP_OEQ:
993         std::swap(TrueMBB, FalseMBB);
994         Predicate = CmpInst::FCMP_UNE;
995         // FALL THROUGH
996       case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
997       case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
998       case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
999       case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA_4;  break;
1000       case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE_4; break;
1001       case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1002       case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1003       case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4;  break;
1004       case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4;  break;
1005       case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB_4;  break;
1006       case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE_4; break;
1007       case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1008       case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1009
1010       case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE_4;  break;
1011       case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE_4; break;
1012       case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
1013       case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1014       case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
1015       case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1016       case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4;  break;
1017       case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1018       case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4;  break;
1019       case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1020       default:
1021         return false;
1022       }
1023
1024       const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1025       if (SwapArgs)
1026         std::swap(Op0, Op1);
1027
1028       // Emit a compare of the LHS and RHS, setting the flags.
1029       if (!X86FastEmitCompare(Op0, Op1, VT))
1030         return false;
1031
1032       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1033         .addMBB(TrueMBB);
1034
1035       if (Predicate == CmpInst::FCMP_UNE) {
1036         // X86 requires a second branch to handle UNE (and OEQ,
1037         // which is mapped to UNE above).
1038         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1039           .addMBB(TrueMBB);
1040       }
1041
1042       FastEmitBranch(FalseMBB, DL);
1043       FuncInfo.MBB->addSuccessor(TrueMBB);
1044       return true;
1045     }
1046   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1047     // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1048     // typically happen for _Bool and C++ bools.
1049     MVT SourceVT;
1050     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1051         isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1052       unsigned TestOpc = 0;
1053       switch (SourceVT.SimpleTy) {
1054       default: break;
1055       case MVT::i8:  TestOpc = X86::TEST8ri; break;
1056       case MVT::i16: TestOpc = X86::TEST16ri; break;
1057       case MVT::i32: TestOpc = X86::TEST32ri; break;
1058       case MVT::i64: TestOpc = X86::TEST64ri32; break;
1059       }
1060       if (TestOpc) {
1061         unsigned OpReg = getRegForValue(TI->getOperand(0));
1062         if (OpReg == 0) return false;
1063         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1064           .addReg(OpReg).addImm(1);
1065         
1066         unsigned JmpOpc = X86::JNE_4;
1067         if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1068           std::swap(TrueMBB, FalseMBB);
1069           JmpOpc = X86::JE_4;
1070         }
1071         
1072         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1073           .addMBB(TrueMBB);
1074         FastEmitBranch(FalseMBB, DL);
1075         FuncInfo.MBB->addSuccessor(TrueMBB);
1076         return true;
1077       }
1078     }
1079   }
1080
1081   // Otherwise do a clumsy setcc and re-test it.
1082   // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1083   // in an explicit cast, so make sure to handle that correctly.
1084   unsigned OpReg = getRegForValue(BI->getCondition());
1085   if (OpReg == 0) return false;
1086
1087   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1088     .addReg(OpReg).addImm(1);
1089   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1090     .addMBB(TrueMBB);
1091   FastEmitBranch(FalseMBB, DL);
1092   FuncInfo.MBB->addSuccessor(TrueMBB);
1093   return true;
1094 }
1095
1096 bool X86FastISel::X86SelectShift(const Instruction *I) {
1097   unsigned CReg = 0, OpReg = 0;
1098   const TargetRegisterClass *RC = NULL;
1099   if (I->getType()->isIntegerTy(8)) {
1100     CReg = X86::CL;
1101     RC = &X86::GR8RegClass;
1102     switch (I->getOpcode()) {
1103     case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1104     case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1105     case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
1106     default: return false;
1107     }
1108   } else if (I->getType()->isIntegerTy(16)) {
1109     CReg = X86::CX;
1110     RC = &X86::GR16RegClass;
1111     switch (I->getOpcode()) {
1112     case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1113     case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1114     case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
1115     default: return false;
1116     }
1117   } else if (I->getType()->isIntegerTy(32)) {
1118     CReg = X86::ECX;
1119     RC = &X86::GR32RegClass;
1120     switch (I->getOpcode()) {
1121     case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1122     case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1123     case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
1124     default: return false;
1125     }
1126   } else if (I->getType()->isIntegerTy(64)) {
1127     CReg = X86::RCX;
1128     RC = &X86::GR64RegClass;
1129     switch (I->getOpcode()) {
1130     case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1131     case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1132     case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
1133     default: return false;
1134     }
1135   } else {
1136     return false;
1137   }
1138
1139   MVT VT;
1140   if (!isTypeLegal(I->getType(), VT))
1141     return false;
1142
1143   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1144   if (Op0Reg == 0) return false;
1145
1146   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1147   if (Op1Reg == 0) return false;
1148   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1149           CReg).addReg(Op1Reg);
1150
1151   // The shift instruction uses X86::CL. If we defined a super-register
1152   // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1153   if (CReg != X86::CL)
1154     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1155             TII.get(TargetOpcode::KILL), X86::CL)
1156       .addReg(CReg, RegState::Kill);
1157
1158   unsigned ResultReg = createResultReg(RC);
1159   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1160     .addReg(Op0Reg);
1161   UpdateValueMap(I, ResultReg);
1162   return true;
1163 }
1164
1165 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1166   MVT VT;
1167   if (!isTypeLegal(I->getType(), VT))
1168     return false;
1169
1170   // We only use cmov here, if we don't have a cmov instruction bail.
1171   if (!Subtarget->hasCMov()) return false;
1172
1173   unsigned Opc = 0;
1174   const TargetRegisterClass *RC = NULL;
1175   if (VT == MVT::i16) {
1176     Opc = X86::CMOVE16rr;
1177     RC = &X86::GR16RegClass;
1178   } else if (VT == MVT::i32) {
1179     Opc = X86::CMOVE32rr;
1180     RC = &X86::GR32RegClass;
1181   } else if (VT == MVT::i64) {
1182     Opc = X86::CMOVE64rr;
1183     RC = &X86::GR64RegClass;
1184   } else {
1185     return false;
1186   }
1187
1188   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1189   if (Op0Reg == 0) return false;
1190   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1191   if (Op1Reg == 0) return false;
1192   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1193   if (Op2Reg == 0) return false;
1194
1195   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1196     .addReg(Op0Reg).addReg(Op0Reg);
1197   unsigned ResultReg = createResultReg(RC);
1198   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1199     .addReg(Op1Reg).addReg(Op2Reg);
1200   UpdateValueMap(I, ResultReg);
1201   return true;
1202 }
1203
1204 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1205   // fpext from float to double.
1206   if (Subtarget->hasSSE2() &&
1207       I->getType()->isDoubleTy()) {
1208     const Value *V = I->getOperand(0);
1209     if (V->getType()->isFloatTy()) {
1210       unsigned OpReg = getRegForValue(V);
1211       if (OpReg == 0) return false;
1212       unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1213       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1214               TII.get(X86::CVTSS2SDrr), ResultReg)
1215         .addReg(OpReg);
1216       UpdateValueMap(I, ResultReg);
1217       return true;
1218     }
1219   }
1220
1221   return false;
1222 }
1223
1224 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1225   if (Subtarget->hasSSE2()) {
1226     if (I->getType()->isFloatTy()) {
1227       const Value *V = I->getOperand(0);
1228       if (V->getType()->isDoubleTy()) {
1229         unsigned OpReg = getRegForValue(V);
1230         if (OpReg == 0) return false;
1231         unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1232         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1233                 TII.get(X86::CVTSD2SSrr), ResultReg)
1234           .addReg(OpReg);
1235         UpdateValueMap(I, ResultReg);
1236         return true;
1237       }
1238     }
1239   }
1240
1241   return false;
1242 }
1243
1244 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1245   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1246   EVT DstVT = TLI.getValueType(I->getType());
1247
1248   // This code only handles truncation to byte.
1249   if (DstVT != MVT::i8 && DstVT != MVT::i1)
1250     return false;
1251   if (!TLI.isTypeLegal(SrcVT))
1252     return false;
1253
1254   unsigned InputReg = getRegForValue(I->getOperand(0));
1255   if (!InputReg)
1256     // Unhandled operand.  Halt "fast" selection and bail.
1257     return false;
1258
1259   if (SrcVT == MVT::i8) {
1260     // Truncate from i8 to i1; no code needed.
1261     UpdateValueMap(I, InputReg);
1262     return true;
1263   }
1264
1265   if (!Subtarget->is64Bit()) {
1266     // If we're on x86-32; we can't extract an i8 from a general register.
1267     // First issue a copy to GR16_ABCD or GR32_ABCD.
1268     const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1269       ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1270     unsigned CopyReg = createResultReg(CopyRC);
1271     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1272             CopyReg).addReg(InputReg);
1273     InputReg = CopyReg;
1274   }
1275
1276   // Issue an extract_subreg.
1277   unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1278                                                   InputReg, /*Kill=*/true,
1279                                                   X86::sub_8bit);
1280   if (!ResultReg)
1281     return false;
1282
1283   UpdateValueMap(I, ResultReg);
1284   return true;
1285 }
1286
1287 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1288   return Len <= (Subtarget->is64Bit() ? 32 : 16);
1289 }
1290
1291 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1292                                      X86AddressMode SrcAM, uint64_t Len) {
1293
1294   // Make sure we don't bloat code by inlining very large memcpy's.
1295   if (!IsMemcpySmall(Len))
1296     return false;
1297
1298   bool i64Legal = Subtarget->is64Bit();
1299
1300   // We don't care about alignment here since we just emit integer accesses.
1301   while (Len) {
1302     MVT VT;
1303     if (Len >= 8 && i64Legal)
1304       VT = MVT::i64;
1305     else if (Len >= 4)
1306       VT = MVT::i32;
1307     else if (Len >= 2)
1308       VT = MVT::i16;
1309     else {
1310       assert(Len == 1);
1311       VT = MVT::i8;
1312     }
1313
1314     unsigned Reg;
1315     bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1316     RV &= X86FastEmitStore(VT, Reg, DestAM);
1317     assert(RV && "Failed to emit load or store??");
1318
1319     unsigned Size = VT.getSizeInBits()/8;
1320     Len -= Size;
1321     DestAM.Disp += Size;
1322     SrcAM.Disp += Size;
1323   }
1324
1325   return true;
1326 }
1327
1328 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1329   // FIXME: Handle more intrinsics.
1330   switch (I.getIntrinsicID()) {
1331   default: return false;
1332   case Intrinsic::memcpy: {
1333     const MemCpyInst &MCI = cast<MemCpyInst>(I);
1334     // Don't handle volatile or variable length memcpys.
1335     if (MCI.isVolatile() || !isa<ConstantInt>(MCI.getLength()))
1336       return false;
1337
1338     uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1339     
1340     // Get the address of the dest and source addresses.
1341     X86AddressMode DestAM, SrcAM;
1342     if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1343         !X86SelectAddress(MCI.getRawSource(), SrcAM))
1344       return false;
1345
1346     return TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1347   }
1348       
1349   case Intrinsic::stackprotector: {
1350     // Emit code inline code to store the stack guard onto the stack.
1351     EVT PtrTy = TLI.getPointerTy();
1352
1353     const Value *Op1 = I.getArgOperand(0); // The guard's value.
1354     const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1355
1356     // Grab the frame index.
1357     X86AddressMode AM;
1358     if (!X86SelectAddress(Slot, AM)) return false;
1359     if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1360     return true;
1361   }
1362   case Intrinsic::dbg_declare: {
1363     const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1364     X86AddressMode AM;
1365     assert(DI->getAddress() && "Null address should be checked earlier!");
1366     if (!X86SelectAddress(DI->getAddress(), AM))
1367       return false;
1368     const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1369     // FIXME may need to add RegState::Debug to any registers produced,
1370     // although ESP/EBP should be the only ones at the moment.
1371     addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1372       addImm(0).addMetadata(DI->getVariable());
1373     return true;
1374   }
1375   case Intrinsic::trap: {
1376     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1377     return true;
1378   }
1379   case Intrinsic::sadd_with_overflow:
1380   case Intrinsic::uadd_with_overflow: {
1381     // FIXME: Should fold immediates.
1382     
1383     // Replace "add with overflow" intrinsics with an "add" instruction followed
1384     // by a seto/setc instruction.
1385     const Function *Callee = I.getCalledFunction();
1386     const Type *RetTy =
1387       cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1388
1389     MVT VT;
1390     if (!isTypeLegal(RetTy, VT))
1391       return false;
1392
1393     const Value *Op1 = I.getArgOperand(0);
1394     const Value *Op2 = I.getArgOperand(1);
1395     unsigned Reg1 = getRegForValue(Op1);
1396     unsigned Reg2 = getRegForValue(Op2);
1397
1398     if (Reg1 == 0 || Reg2 == 0)
1399       // FIXME: Handle values *not* in registers.
1400       return false;
1401
1402     unsigned OpC = 0;
1403     if (VT == MVT::i32)
1404       OpC = X86::ADD32rr;
1405     else if (VT == MVT::i64)
1406       OpC = X86::ADD64rr;
1407     else
1408       return false;
1409
1410     // The call to CreateRegs builds two sequential registers, to store the
1411     // both the the returned values.
1412     unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1413     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1414       .addReg(Reg1).addReg(Reg2);
1415
1416     unsigned Opc = X86::SETBr;
1417     if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1418       Opc = X86::SETOr;
1419     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1420
1421     UpdateValueMap(&I, ResultReg, 2);
1422     return true;
1423   }
1424   }
1425 }
1426
1427 bool X86FastISel::X86SelectCall(const Instruction *I) {
1428   const CallInst *CI = cast<CallInst>(I);
1429   const Value *Callee = CI->getCalledValue();
1430
1431   // Can't handle inline asm yet.
1432   if (isa<InlineAsm>(Callee))
1433     return false;
1434
1435   // Handle intrinsic calls.
1436   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1437     return X86VisitIntrinsicCall(*II);
1438
1439   // Handle only C and fastcc calling conventions for now.
1440   ImmutableCallSite CS(CI);
1441   CallingConv::ID CC = CS.getCallingConv();
1442   if (CC != CallingConv::C && CC != CallingConv::Fast &&
1443       CC != CallingConv::X86_FastCall)
1444     return false;
1445
1446   // fastcc with -tailcallopt is intended to provide a guaranteed
1447   // tail call optimization. Fastisel doesn't know how to do that.
1448   if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1449     return false;
1450
1451   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1452   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1453   bool isVarArg = FTy->isVarArg();
1454
1455   // Don't know how to handle Win64 varargs yet.  Nothing special needed for
1456   // x86-32.  Special handling for x86-64 is implemented.
1457   if (isVarArg && Subtarget->isTargetWin64())
1458     return false;
1459
1460   // Fast-isel doesn't know about callee-pop yet.
1461   if (Subtarget->IsCalleePop(isVarArg, CC))
1462     return false;
1463
1464   // Check whether the function can return without sret-demotion.
1465   SmallVector<ISD::OutputArg, 4> Outs;
1466   SmallVector<uint64_t, 4> Offsets;
1467   GetReturnInfo(I->getType(), CS.getAttributes().getRetAttributes(),
1468                 Outs, TLI, &Offsets);
1469   bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1470                         FTy->isVarArg(), Outs, FTy->getContext());
1471   if (!CanLowerReturn)
1472     return false;
1473
1474   // Materialize callee address in a register. FIXME: GV address can be
1475   // handled with a CALLpcrel32 instead.
1476   X86AddressMode CalleeAM;
1477   if (!X86SelectCallAddress(Callee, CalleeAM))
1478     return false;
1479   unsigned CalleeOp = 0;
1480   const GlobalValue *GV = 0;
1481   if (CalleeAM.GV != 0) {
1482     GV = CalleeAM.GV;
1483   } else if (CalleeAM.Base.Reg != 0) {
1484     CalleeOp = CalleeAM.Base.Reg;
1485   } else
1486     return false;
1487
1488   // Deal with call operands first.
1489   SmallVector<const Value *, 8> ArgVals;
1490   SmallVector<unsigned, 8> Args;
1491   SmallVector<MVT, 8> ArgVTs;
1492   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1493   Args.reserve(CS.arg_size());
1494   ArgVals.reserve(CS.arg_size());
1495   ArgVTs.reserve(CS.arg_size());
1496   ArgFlags.reserve(CS.arg_size());
1497   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1498        i != e; ++i) {
1499     Value *ArgVal = *i;
1500     ISD::ArgFlagsTy Flags;
1501     unsigned AttrInd = i - CS.arg_begin() + 1;
1502     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1503       Flags.setSExt();
1504     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1505       Flags.setZExt();
1506
1507     if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1508       const PointerType *Ty = cast<PointerType>(ArgVal->getType());
1509       const Type *ElementTy = Ty->getElementType();
1510       unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1511       unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1512       if (!FrameAlign)
1513         FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1514       Flags.setByVal();
1515       Flags.setByValSize(FrameSize);
1516       Flags.setByValAlign(FrameAlign);
1517       if (!IsMemcpySmall(FrameSize))
1518         return false;
1519     }
1520
1521     if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1522       Flags.setInReg();
1523     if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1524       Flags.setNest();
1525
1526     // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1527     // instruction.  This is safe because it is common to all fastisel supported
1528     // calling conventions on x86.
1529     if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1530       if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1531           CI->getBitWidth() == 16) {
1532         if (Flags.isSExt())
1533           ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1534         else
1535           ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1536       }
1537     }
1538     
1539     unsigned ArgReg;
1540     
1541     // Passing bools around ends up doing a trunc to i1 and passing it.
1542     // Codegen this as an argument + "and 1".
1543     if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1544         cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1545         ArgVal->hasOneUse()) {
1546       ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1547       ArgReg = getRegForValue(ArgVal);
1548       if (ArgReg == 0) return false;
1549       
1550       MVT ArgVT;
1551       if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1552       
1553       ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1554                            ArgVal->hasOneUse(), 1);
1555     } else {
1556       ArgReg = getRegForValue(ArgVal);
1557     }
1558
1559     if (ArgReg == 0) return false;
1560
1561     const Type *ArgTy = ArgVal->getType();
1562     MVT ArgVT;
1563     if (!isTypeLegal(ArgTy, ArgVT))
1564       return false;
1565     if (ArgVT == MVT::x86mmx)
1566       return false;
1567     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1568     Flags.setOrigAlign(OriginalAlignment);
1569
1570     Args.push_back(ArgReg);
1571     ArgVals.push_back(ArgVal);
1572     ArgVTs.push_back(ArgVT);
1573     ArgFlags.push_back(Flags);
1574   }
1575
1576   // Analyze operands of the call, assigning locations to each operand.
1577   SmallVector<CCValAssign, 16> ArgLocs;
1578   CCState CCInfo(CC, isVarArg, TM, ArgLocs, I->getParent()->getContext());
1579
1580   // Allocate shadow area for Win64
1581   if (Subtarget->isTargetWin64())
1582     CCInfo.AllocateStack(32, 8);
1583
1584   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1585
1586   // Get a count of how many bytes are to be pushed on the stack.
1587   unsigned NumBytes = CCInfo.getNextStackOffset();
1588
1589   // Issue CALLSEQ_START
1590   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1591   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1592     .addImm(NumBytes);
1593
1594   // Process argument: walk the register/memloc assignments, inserting
1595   // copies / loads.
1596   SmallVector<unsigned, 4> RegArgs;
1597   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1598     CCValAssign &VA = ArgLocs[i];
1599     unsigned Arg = Args[VA.getValNo()];
1600     EVT ArgVT = ArgVTs[VA.getValNo()];
1601
1602     // Promote the value if needed.
1603     switch (VA.getLocInfo()) {
1604     default: llvm_unreachable("Unknown loc info!");
1605     case CCValAssign::Full: break;
1606     case CCValAssign::SExt: {
1607       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1608              "Unexpected extend");
1609       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1610                                        Arg, ArgVT, Arg);
1611       assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1612       ArgVT = VA.getLocVT();
1613       break;
1614     }
1615     case CCValAssign::ZExt: {
1616       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1617              "Unexpected extend");
1618       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1619                                        Arg, ArgVT, Arg);
1620       assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1621       ArgVT = VA.getLocVT();
1622       break;
1623     }
1624     case CCValAssign::AExt: {
1625       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1626              "Unexpected extend");
1627       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1628                                        Arg, ArgVT, Arg);
1629       if (!Emitted)
1630         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1631                                     Arg, ArgVT, Arg);
1632       if (!Emitted)
1633         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1634                                     Arg, ArgVT, Arg);
1635
1636       assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1637       ArgVT = VA.getLocVT();
1638       break;
1639     }
1640     case CCValAssign::BCvt: {
1641       unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1642                                ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1643       assert(BC != 0 && "Failed to emit a bitcast!");
1644       Arg = BC;
1645       ArgVT = VA.getLocVT();
1646       break;
1647     }
1648     }
1649
1650     if (VA.isRegLoc()) {
1651       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1652               VA.getLocReg()).addReg(Arg);
1653       RegArgs.push_back(VA.getLocReg());
1654     } else {
1655       unsigned LocMemOffset = VA.getLocMemOffset();
1656       X86AddressMode AM;
1657       AM.Base.Reg = StackPtr;
1658       AM.Disp = LocMemOffset;
1659       const Value *ArgVal = ArgVals[VA.getValNo()];
1660       ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1661
1662       if (Flags.isByVal()) {
1663         X86AddressMode SrcAM;
1664         SrcAM.Base.Reg = Arg;
1665         bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
1666         assert(Res && "memcpy length already checked!"); (void)Res;
1667       } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
1668         // If this is a really simple value, emit this with the Value* version
1669         //of X86FastEmitStore.  If it isn't simple, we don't want to do this,
1670         // as it can cause us to reevaluate the argument.
1671         X86FastEmitStore(ArgVT, ArgVal, AM);
1672       } else {
1673         X86FastEmitStore(ArgVT, Arg, AM);
1674       }
1675     }
1676   }
1677
1678   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1679   // GOT pointer.
1680   if (Subtarget->isPICStyleGOT()) {
1681     unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1682     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1683             X86::EBX).addReg(Base);
1684   }
1685
1686   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1687     // Count the number of XMM registers allocated.
1688     static const unsigned XMMArgRegs[] = {
1689       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1690       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1691     };
1692     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1693     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1694             X86::AL).addImm(NumXMMRegs);
1695   }
1696
1697   // Issue the call.
1698   MachineInstrBuilder MIB;
1699   if (CalleeOp) {
1700     // Register-indirect call.
1701     unsigned CallOpc;
1702     if (Subtarget->isTargetWin64())
1703       CallOpc = X86::WINCALL64r;
1704     else if (Subtarget->is64Bit())
1705       CallOpc = X86::CALL64r;
1706     else
1707       CallOpc = X86::CALL32r;
1708     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1709       .addReg(CalleeOp);
1710
1711   } else {
1712     // Direct call.
1713     assert(GV && "Not a direct call");
1714     unsigned CallOpc;
1715     if (Subtarget->isTargetWin64())
1716       CallOpc = X86::WINCALL64pcrel32;
1717     else if (Subtarget->is64Bit())
1718       CallOpc = X86::CALL64pcrel32;
1719     else
1720       CallOpc = X86::CALLpcrel32;
1721
1722     // See if we need any target-specific flags on the GV operand.
1723     unsigned char OpFlags = 0;
1724
1725     // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1726     // external symbols most go through the PLT in PIC mode.  If the symbol
1727     // has hidden or protected visibility, or if it is static or local, then
1728     // we don't need to use the PLT - we can directly call it.
1729     if (Subtarget->isTargetELF() &&
1730         TM.getRelocationModel() == Reloc::PIC_ &&
1731         GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1732       OpFlags = X86II::MO_PLT;
1733     } else if (Subtarget->isPICStyleStubAny() &&
1734                (GV->isDeclaration() || GV->isWeakForLinker()) &&
1735                (!Subtarget->getTargetTriple().isMacOSX() ||
1736                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1737       // PC-relative references to external symbols should go through $stub,
1738       // unless we're building with the leopard linker or later, which
1739       // automatically synthesizes these stubs.
1740       OpFlags = X86II::MO_DARWIN_STUB;
1741     }
1742
1743
1744     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1745       .addGlobalAddress(GV, 0, OpFlags);
1746   }
1747
1748   // Add an implicit use GOT pointer in EBX.
1749   if (Subtarget->isPICStyleGOT())
1750     MIB.addReg(X86::EBX);
1751
1752   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1753     MIB.addReg(X86::AL);
1754
1755   // Add implicit physical register uses to the call.
1756   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1757     MIB.addReg(RegArgs[i]);
1758
1759   // Issue CALLSEQ_END
1760   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1761   unsigned NumBytesCallee = 0;
1762   if (!Subtarget->is64Bit() && CS.paramHasAttr(1, Attribute::StructRet))
1763     NumBytesCallee = 4;
1764   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1765     .addImm(NumBytes).addImm(NumBytesCallee);
1766
1767   // Build info for return calling conv lowering code.
1768   // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
1769   SmallVector<ISD::InputArg, 32> Ins;
1770   SmallVector<EVT, 4> RetTys;
1771   ComputeValueVTs(TLI, I->getType(), RetTys);
1772   for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
1773     EVT VT = RetTys[i];
1774     EVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
1775     unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
1776     for (unsigned j = 0; j != NumRegs; ++j) {
1777       ISD::InputArg MyFlags;
1778       MyFlags.VT = RegisterVT.getSimpleVT();
1779       MyFlags.Used = !CS.getInstruction()->use_empty();
1780       if (CS.paramHasAttr(0, Attribute::SExt))
1781         MyFlags.Flags.setSExt();
1782       if (CS.paramHasAttr(0, Attribute::ZExt))
1783         MyFlags.Flags.setZExt();
1784       if (CS.paramHasAttr(0, Attribute::InReg))
1785         MyFlags.Flags.setInReg();
1786       Ins.push_back(MyFlags);
1787     }
1788   }
1789
1790   // Now handle call return values.
1791   SmallVector<unsigned, 4> UsedRegs;
1792   SmallVector<CCValAssign, 16> RVLocs;
1793   CCState CCRetInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1794   unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
1795   CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
1796   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1797     EVT CopyVT = RVLocs[i].getValVT();
1798     unsigned CopyReg = ResultReg + i;
1799
1800     // If this is a call to a function that returns an fp value on the x87 fp
1801     // stack, but where we prefer to use the value in xmm registers, copy it
1802     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1803     if ((RVLocs[i].getLocReg() == X86::ST0 ||
1804          RVLocs[i].getLocReg() == X86::ST1) &&
1805         isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1806       CopyVT = MVT::f80;
1807       CopyReg = createResultReg(X86::RFP80RegisterClass);
1808     }
1809
1810     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1811             CopyReg).addReg(RVLocs[i].getLocReg());
1812     UsedRegs.push_back(RVLocs[i].getLocReg());
1813
1814     if (CopyVT != RVLocs[i].getValVT()) {
1815       // Round the F80 the right size, which also moves to the appropriate xmm
1816       // register. This is accomplished by storing the F80 value in memory and
1817       // then loading it back. Ewww...
1818       EVT ResVT = RVLocs[i].getValVT();
1819       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1820       unsigned MemSize = ResVT.getSizeInBits()/8;
1821       int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1822       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1823                                 TII.get(Opc)), FI)
1824         .addReg(CopyReg);
1825       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1826       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1827                                 TII.get(Opc), ResultReg + i), FI);
1828     }
1829   }
1830
1831   if (RVLocs.size())
1832     UpdateValueMap(I, ResultReg, RVLocs.size());
1833
1834   // Set all unused physreg defs as dead.
1835   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1836
1837   return true;
1838 }
1839
1840
1841 bool
1842 X86FastISel::TargetSelectInstruction(const Instruction *I)  {
1843   switch (I->getOpcode()) {
1844   default: break;
1845   case Instruction::Load:
1846     return X86SelectLoad(I);
1847   case Instruction::Store:
1848     return X86SelectStore(I);
1849   case Instruction::Ret:
1850     return X86SelectRet(I);
1851   case Instruction::ICmp:
1852   case Instruction::FCmp:
1853     return X86SelectCmp(I);
1854   case Instruction::ZExt:
1855     return X86SelectZExt(I);
1856   case Instruction::Br:
1857     return X86SelectBranch(I);
1858   case Instruction::Call:
1859     return X86SelectCall(I);
1860   case Instruction::LShr:
1861   case Instruction::AShr:
1862   case Instruction::Shl:
1863     return X86SelectShift(I);
1864   case Instruction::Select:
1865     return X86SelectSelect(I);
1866   case Instruction::Trunc:
1867     return X86SelectTrunc(I);
1868   case Instruction::FPExt:
1869     return X86SelectFPExt(I);
1870   case Instruction::FPTrunc:
1871     return X86SelectFPTrunc(I);
1872   case Instruction::IntToPtr: // Deliberate fall-through.
1873   case Instruction::PtrToInt: {
1874     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1875     EVT DstVT = TLI.getValueType(I->getType());
1876     if (DstVT.bitsGT(SrcVT))
1877       return X86SelectZExt(I);
1878     if (DstVT.bitsLT(SrcVT))
1879       return X86SelectTrunc(I);
1880     unsigned Reg = getRegForValue(I->getOperand(0));
1881     if (Reg == 0) return false;
1882     UpdateValueMap(I, Reg);
1883     return true;
1884   }
1885   }
1886
1887   return false;
1888 }
1889
1890 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
1891   MVT VT;
1892   if (!isTypeLegal(C->getType(), VT))
1893     return false;
1894
1895   // Get opcode and regclass of the output for the given load instruction.
1896   unsigned Opc = 0;
1897   const TargetRegisterClass *RC = NULL;
1898   switch (VT.SimpleTy) {
1899   default: return false;
1900   case MVT::i8:
1901     Opc = X86::MOV8rm;
1902     RC  = X86::GR8RegisterClass;
1903     break;
1904   case MVT::i16:
1905     Opc = X86::MOV16rm;
1906     RC  = X86::GR16RegisterClass;
1907     break;
1908   case MVT::i32:
1909     Opc = X86::MOV32rm;
1910     RC  = X86::GR32RegisterClass;
1911     break;
1912   case MVT::i64:
1913     // Must be in x86-64 mode.
1914     Opc = X86::MOV64rm;
1915     RC  = X86::GR64RegisterClass;
1916     break;
1917   case MVT::f32:
1918     if (Subtarget->hasSSE1()) {
1919       Opc = X86::MOVSSrm;
1920       RC  = X86::FR32RegisterClass;
1921     } else {
1922       Opc = X86::LD_Fp32m;
1923       RC  = X86::RFP32RegisterClass;
1924     }
1925     break;
1926   case MVT::f64:
1927     if (Subtarget->hasSSE2()) {
1928       Opc = X86::MOVSDrm;
1929       RC  = X86::FR64RegisterClass;
1930     } else {
1931       Opc = X86::LD_Fp64m;
1932       RC  = X86::RFP64RegisterClass;
1933     }
1934     break;
1935   case MVT::f80:
1936     // No f80 support yet.
1937     return false;
1938   }
1939
1940   // Materialize addresses with LEA instructions.
1941   if (isa<GlobalValue>(C)) {
1942     X86AddressMode AM;
1943     if (X86SelectAddress(C, AM)) {
1944       // If the expression is just a basereg, then we're done, otherwise we need
1945       // to emit an LEA.
1946       if (AM.BaseType == X86AddressMode::RegBase &&
1947           AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
1948         return AM.Base.Reg;
1949       
1950       Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
1951       unsigned ResultReg = createResultReg(RC);
1952       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1953                              TII.get(Opc), ResultReg), AM);
1954       return ResultReg;
1955     }
1956     return 0;
1957   }
1958
1959   // MachineConstantPool wants an explicit alignment.
1960   unsigned Align = TD.getPrefTypeAlignment(C->getType());
1961   if (Align == 0) {
1962     // Alignment of vector types.  FIXME!
1963     Align = TD.getTypeAllocSize(C->getType());
1964   }
1965
1966   // x86-32 PIC requires a PIC base register for constant pools.
1967   unsigned PICBase = 0;
1968   unsigned char OpFlag = 0;
1969   if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
1970     OpFlag = X86II::MO_PIC_BASE_OFFSET;
1971     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1972   } else if (Subtarget->isPICStyleGOT()) {
1973     OpFlag = X86II::MO_GOTOFF;
1974     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1975   } else if (Subtarget->isPICStyleRIPRel() &&
1976              TM.getCodeModel() == CodeModel::Small) {
1977     PICBase = X86::RIP;
1978   }
1979
1980   // Create the load from the constant pool.
1981   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1982   unsigned ResultReg = createResultReg(RC);
1983   addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1984                                    TII.get(Opc), ResultReg),
1985                            MCPOffset, PICBase, OpFlag);
1986
1987   return ResultReg;
1988 }
1989
1990 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
1991   // Fail on dynamic allocas. At this point, getRegForValue has already
1992   // checked its CSE maps, so if we're here trying to handle a dynamic
1993   // alloca, we're not going to succeed. X86SelectAddress has a
1994   // check for dynamic allocas, because it's called directly from
1995   // various places, but TargetMaterializeAlloca also needs a check
1996   // in order to avoid recursion between getRegForValue,
1997   // X86SelectAddrss, and TargetMaterializeAlloca.
1998   if (!FuncInfo.StaticAllocaMap.count(C))
1999     return 0;
2000
2001   X86AddressMode AM;
2002   if (!X86SelectAddress(C, AM))
2003     return 0;
2004   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2005   TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2006   unsigned ResultReg = createResultReg(RC);
2007   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2008                          TII.get(Opc), ResultReg), AM);
2009   return ResultReg;
2010 }
2011
2012 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2013   MVT VT;
2014   if (!isTypeLegal(CF->getType(), VT))
2015     return false;
2016
2017   // Get opcode and regclass for the given zero.
2018   unsigned Opc = 0;
2019   const TargetRegisterClass *RC = NULL;
2020   switch (VT.SimpleTy) {
2021     default: return false;
2022     case MVT::f32:
2023       if (Subtarget->hasSSE1()) {
2024         Opc = X86::FsFLD0SS;
2025         RC  = X86::FR32RegisterClass;
2026       } else {
2027         Opc = X86::LD_Fp032;
2028         RC  = X86::RFP32RegisterClass;
2029       }
2030       break;
2031     case MVT::f64:
2032       if (Subtarget->hasSSE2()) {
2033         Opc = X86::FsFLD0SD;
2034         RC  = X86::FR64RegisterClass;
2035       } else {
2036         Opc = X86::LD_Fp064;
2037         RC  = X86::RFP64RegisterClass;
2038       }
2039       break;
2040     case MVT::f80:
2041       // No f80 support yet.
2042       return false;
2043   }
2044
2045   unsigned ResultReg = createResultReg(RC);
2046   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2047   return ResultReg;
2048 }
2049
2050
2051 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2052 /// vreg is being provided by the specified load instruction.  If possible,
2053 /// try to fold the load as an operand to the instruction, returning true if
2054 /// possible.
2055 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2056                                 const LoadInst *LI) {
2057   X86AddressMode AM;
2058   if (!X86SelectAddress(LI->getOperand(0), AM))
2059     return false;
2060
2061   X86InstrInfo &XII = (X86InstrInfo&)TII;
2062
2063   unsigned Size = TD.getTypeAllocSize(LI->getType());
2064   unsigned Alignment = LI->getAlignment();
2065
2066   SmallVector<MachineOperand, 8> AddrOps;
2067   AM.getFullAddress(AddrOps);
2068
2069   MachineInstr *Result =
2070     XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2071   if (Result == 0) return false;
2072
2073   FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2074   MI->eraseFromParent();
2075   return true;
2076 }
2077
2078
2079 namespace llvm {
2080   llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
2081     return new X86FastISel(funcInfo);
2082   }
2083 }