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