Fix an edge case involving branches in fast-isel on x86.
[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   // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1102   // in an explicit cast, so make sure to handle that correctly.
1103   unsigned OpReg = getRegForValue(BI->getCondition());
1104   if (OpReg == 0) return false;
1105
1106   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1107     .addReg(OpReg).addImm(1);
1108   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1109     .addMBB(TrueMBB);
1110   FastEmitBranch(FalseMBB, DL);
1111   FuncInfo.MBB->addSuccessor(TrueMBB);
1112   return true;
1113 }
1114
1115 bool X86FastISel::X86SelectShift(const Instruction *I) {
1116   unsigned CReg = 0, OpReg = 0;
1117   const TargetRegisterClass *RC = NULL;
1118   if (I->getType()->isIntegerTy(8)) {
1119     CReg = X86::CL;
1120     RC = &X86::GR8RegClass;
1121     switch (I->getOpcode()) {
1122     case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1123     case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1124     case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
1125     default: return false;
1126     }
1127   } else if (I->getType()->isIntegerTy(16)) {
1128     CReg = X86::CX;
1129     RC = &X86::GR16RegClass;
1130     switch (I->getOpcode()) {
1131     case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1132     case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1133     case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
1134     default: return false;
1135     }
1136   } else if (I->getType()->isIntegerTy(32)) {
1137     CReg = X86::ECX;
1138     RC = &X86::GR32RegClass;
1139     switch (I->getOpcode()) {
1140     case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1141     case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1142     case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
1143     default: return false;
1144     }
1145   } else if (I->getType()->isIntegerTy(64)) {
1146     CReg = X86::RCX;
1147     RC = &X86::GR64RegClass;
1148     switch (I->getOpcode()) {
1149     case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1150     case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1151     case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
1152     default: return false;
1153     }
1154   } else {
1155     return false;
1156   }
1157
1158   MVT VT;
1159   if (!isTypeLegal(I->getType(), VT))
1160     return false;
1161
1162   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1163   if (Op0Reg == 0) return false;
1164
1165   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1166   if (Op1Reg == 0) return false;
1167   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1168           CReg).addReg(Op1Reg);
1169
1170   // The shift instruction uses X86::CL. If we defined a super-register
1171   // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1172   if (CReg != X86::CL)
1173     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1174             TII.get(TargetOpcode::KILL), X86::CL)
1175       .addReg(CReg, RegState::Kill);
1176
1177   unsigned ResultReg = createResultReg(RC);
1178   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1179     .addReg(Op0Reg);
1180   UpdateValueMap(I, ResultReg);
1181   return true;
1182 }
1183
1184 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1185   MVT VT;
1186   if (!isTypeLegal(I->getType(), VT))
1187     return false;
1188
1189   // We only use cmov here, if we don't have a cmov instruction bail.
1190   if (!Subtarget->hasCMov()) return false;
1191
1192   unsigned Opc = 0;
1193   const TargetRegisterClass *RC = NULL;
1194   if (VT == MVT::i16) {
1195     Opc = X86::CMOVE16rr;
1196     RC = &X86::GR16RegClass;
1197   } else if (VT == MVT::i32) {
1198     Opc = X86::CMOVE32rr;
1199     RC = &X86::GR32RegClass;
1200   } else if (VT == MVT::i64) {
1201     Opc = X86::CMOVE64rr;
1202     RC = &X86::GR64RegClass;
1203   } else {
1204     return false;
1205   }
1206
1207   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1208   if (Op0Reg == 0) return false;
1209   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1210   if (Op1Reg == 0) return false;
1211   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1212   if (Op2Reg == 0) return false;
1213
1214   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1215     .addReg(Op0Reg).addReg(Op0Reg);
1216   unsigned ResultReg = createResultReg(RC);
1217   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1218     .addReg(Op1Reg).addReg(Op2Reg);
1219   UpdateValueMap(I, ResultReg);
1220   return true;
1221 }
1222
1223 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1224   // fpext from float to double.
1225   if (Subtarget->hasSSE2() &&
1226       I->getType()->isDoubleTy()) {
1227     const Value *V = I->getOperand(0);
1228     if (V->getType()->isFloatTy()) {
1229       unsigned OpReg = getRegForValue(V);
1230       if (OpReg == 0) return false;
1231       unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1232       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1233               TII.get(X86::CVTSS2SDrr), ResultReg)
1234         .addReg(OpReg);
1235       UpdateValueMap(I, ResultReg);
1236       return true;
1237     }
1238   }
1239
1240   return false;
1241 }
1242
1243 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1244   if (Subtarget->hasSSE2()) {
1245     if (I->getType()->isFloatTy()) {
1246       const Value *V = I->getOperand(0);
1247       if (V->getType()->isDoubleTy()) {
1248         unsigned OpReg = getRegForValue(V);
1249         if (OpReg == 0) return false;
1250         unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1251         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1252                 TII.get(X86::CVTSD2SSrr), ResultReg)
1253           .addReg(OpReg);
1254         UpdateValueMap(I, ResultReg);
1255         return true;
1256       }
1257     }
1258   }
1259
1260   return false;
1261 }
1262
1263 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1264   if (Subtarget->is64Bit())
1265     // All other cases should be handled by the tblgen generated code.
1266     return false;
1267   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1268   EVT DstVT = TLI.getValueType(I->getType());
1269
1270   // This code only handles truncation to byte right now.
1271   if (DstVT != MVT::i8 && DstVT != MVT::i1)
1272     // All other cases should be handled by the tblgen generated code.
1273     return false;
1274   if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
1275     // All other cases should be handled by the tblgen generated code.
1276     return false;
1277
1278   unsigned InputReg = getRegForValue(I->getOperand(0));
1279   if (!InputReg)
1280     // Unhandled operand.  Halt "fast" selection and bail.
1281     return false;
1282
1283   // First issue a copy to GR16_ABCD or GR32_ABCD.
1284   const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1285     ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1286   unsigned CopyReg = createResultReg(CopyRC);
1287   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1288           CopyReg).addReg(InputReg);
1289
1290   // Then issue an extract_subreg.
1291   unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1292                                                   CopyReg, /*Kill=*/true,
1293                                                   X86::sub_8bit);
1294   if (!ResultReg)
1295     return false;
1296
1297   UpdateValueMap(I, ResultReg);
1298   return true;
1299 }
1300
1301 bool X86FastISel::X86SelectExtractValue(const Instruction *I) {
1302   const ExtractValueInst *EI = cast<ExtractValueInst>(I);
1303   const Value *Agg = EI->getAggregateOperand();
1304
1305   if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Agg)) {
1306     switch (CI->getIntrinsicID()) {
1307     default: break;
1308     case Intrinsic::sadd_with_overflow:
1309     case Intrinsic::uadd_with_overflow: {
1310       // Cheat a little. We know that the registers for "add" and "seto" are
1311       // allocated sequentially. However, we only keep track of the register
1312       // for "add" in the value map. Use extractvalue's index to get the
1313       // correct register for "seto".
1314       unsigned OpReg = getRegForValue(Agg);
1315       if (OpReg == 0)
1316         return false;
1317       UpdateValueMap(I, OpReg + *EI->idx_begin());
1318       return true;
1319     }
1320     }
1321   }
1322
1323   return false;
1324 }
1325
1326 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1327   // FIXME: Handle more intrinsics.
1328   switch (I.getIntrinsicID()) {
1329   default: return false;
1330   case Intrinsic::memcpy: {
1331     const MemCpyInst &MCI = cast<MemCpyInst>(I);
1332     // Don't handle volatile or variable length memcpys.
1333     if (MCI.isVolatile() || !isa<ConstantInt>(MCI.getLength()))
1334       return false;
1335     
1336     // Don't inline super long memcpys.  We could lower these to a memcpy call,
1337     // but we might as well bail out.
1338     uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1339     bool i64Legal = TLI.isTypeLegal(MVT::i64);
1340     if (Len > (i64Legal ? 32 : 16)) return false;
1341     
1342     // Get the address of the dest and source addresses.
1343     X86AddressMode DestAM, SrcAM;
1344     if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1345         !X86SelectAddress(MCI.getRawSource(), SrcAM))
1346       return false;
1347     
1348     // We don't care about alignment here since we just emit integer accesses.
1349     while (Len) {
1350       MVT VT;
1351       if (Len >= 8 && i64Legal)
1352         VT = MVT::i64;
1353       else if (Len >= 4)
1354         VT = MVT::i32;
1355       else if (Len >= 2)
1356         VT = MVT::i16;
1357       else {
1358         assert(Len == 1);
1359         VT = MVT::i8;
1360       }
1361       
1362       unsigned Reg;
1363       bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1364       RV &= X86FastEmitStore(VT, Reg, DestAM);
1365       assert(RV && "Failed to emit load or store??");
1366       
1367       unsigned Size = VT.getSizeInBits()/8;
1368       Len -= Size;
1369       DestAM.Disp += Size;
1370       SrcAM.Disp += Size;
1371     }
1372     
1373     return true;
1374   }
1375       
1376   case Intrinsic::stackprotector: {
1377     // Emit code inline code to store the stack guard onto the stack.
1378     EVT PtrTy = TLI.getPointerTy();
1379
1380     const Value *Op1 = I.getArgOperand(0); // The guard's value.
1381     const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1382
1383     // Grab the frame index.
1384     X86AddressMode AM;
1385     if (!X86SelectAddress(Slot, AM)) return false;
1386     if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1387     return true;
1388   }
1389   case Intrinsic::objectsize: {
1390     // FIXME: This should be moved to generic code!
1391     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
1392     const Type *Ty = I.getCalledFunction()->getReturnType();
1393
1394     MVT VT;
1395     if (!isTypeLegal(Ty, VT))
1396       return false;
1397
1398     unsigned OpC = 0;
1399     if (VT == MVT::i32)
1400       OpC = X86::MOV32ri;
1401     else if (VT == MVT::i64)
1402       OpC = X86::MOV64ri;
1403     else
1404       return false;
1405
1406     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1407     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg).
1408                                   addImm(CI->isZero() ? -1ULL : 0);
1409     UpdateValueMap(&I, ResultReg);
1410     return true;
1411   }
1412   case Intrinsic::dbg_declare: {
1413     const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1414     X86AddressMode AM;
1415     assert(DI->getAddress() && "Null address should be checked earlier!");
1416     if (!X86SelectAddress(DI->getAddress(), AM))
1417       return false;
1418     const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1419     // FIXME may need to add RegState::Debug to any registers produced,
1420     // although ESP/EBP should be the only ones at the moment.
1421     addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1422       addImm(0).addMetadata(DI->getVariable());
1423     return true;
1424   }
1425   case Intrinsic::trap: {
1426     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1427     return true;
1428   }
1429   case Intrinsic::sadd_with_overflow:
1430   case Intrinsic::uadd_with_overflow: {
1431     // FIXME: Should fold immediates.
1432     
1433     // Replace "add with overflow" intrinsics with an "add" instruction followed
1434     // by a seto/setc instruction. Later on, when the "extractvalue"
1435     // instructions are encountered, we use the fact that two registers were
1436     // created sequentially to get the correct registers for the "sum" and the
1437     // "overflow bit".
1438     const Function *Callee = I.getCalledFunction();
1439     const Type *RetTy =
1440       cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1441
1442     MVT VT;
1443     if (!isTypeLegal(RetTy, VT))
1444       return false;
1445
1446     const Value *Op1 = I.getArgOperand(0);
1447     const Value *Op2 = I.getArgOperand(1);
1448     unsigned Reg1 = getRegForValue(Op1);
1449     unsigned Reg2 = getRegForValue(Op2);
1450
1451     if (Reg1 == 0 || Reg2 == 0)
1452       // FIXME: Handle values *not* in registers.
1453       return false;
1454
1455     unsigned OpC = 0;
1456     if (VT == MVT::i32)
1457       OpC = X86::ADD32rr;
1458     else if (VT == MVT::i64)
1459       OpC = X86::ADD64rr;
1460     else
1461       return false;
1462
1463     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1464     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1465       .addReg(Reg1).addReg(Reg2);
1466     unsigned DestReg1 = UpdateValueMap(&I, ResultReg);
1467
1468     // If the add with overflow is an intra-block value then we just want to
1469     // create temporaries for it like normal.  If it is a cross-block value then
1470     // UpdateValueMap will return the cross-block register used.  Since we
1471     // *really* want the value to be live in the register pair known by
1472     // UpdateValueMap, we have to use DestReg1+1 as the destination register in
1473     // the cross block case.  In the non-cross-block case, we should just make
1474     // another register for the value.
1475     if (DestReg1 != ResultReg)
1476       ResultReg = DestReg1+1;
1477     else
1478       ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1479
1480     unsigned Opc = X86::SETBr;
1481     if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1482       Opc = X86::SETOr;
1483     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
1484     return true;
1485   }
1486   }
1487 }
1488
1489 bool X86FastISel::X86SelectCall(const Instruction *I) {
1490   const CallInst *CI = cast<CallInst>(I);
1491   const Value *Callee = CI->getCalledValue();
1492
1493   // Can't handle inline asm yet.
1494   if (isa<InlineAsm>(Callee))
1495     return false;
1496
1497   // Handle intrinsic calls.
1498   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1499     return X86VisitIntrinsicCall(*II);
1500
1501   // Handle only C and fastcc calling conventions for now.
1502   ImmutableCallSite CS(CI);
1503   CallingConv::ID CC = CS.getCallingConv();
1504   if (CC != CallingConv::C && CC != CallingConv::Fast &&
1505       CC != CallingConv::X86_FastCall)
1506     return false;
1507
1508   // fastcc with -tailcallopt is intended to provide a guaranteed
1509   // tail call optimization. Fastisel doesn't know how to do that.
1510   if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1511     return false;
1512
1513   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1514   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1515   bool isVarArg = FTy->isVarArg();
1516
1517   // Don't know how to handle Win64 varargs yet.  Nothing special needed for
1518   // x86-32.  Special handling for x86-64 is implemented.
1519   if (isVarArg && Subtarget->isTargetWin64())
1520     return false;
1521
1522   // Fast-isel doesn't know about callee-pop yet.
1523   if (Subtarget->IsCalleePop(isVarArg, CC))
1524     return false;
1525
1526   // Handle *simple* calls for now.
1527   const Type *RetTy = CS.getType();
1528   MVT RetVT;
1529   if (RetTy->isVoidTy())
1530     RetVT = MVT::isVoid;
1531   else if (!isTypeLegal(RetTy, RetVT, true))
1532     return false;
1533
1534   // Materialize callee address in a register. FIXME: GV address can be
1535   // handled with a CALLpcrel32 instead.
1536   X86AddressMode CalleeAM;
1537   if (!X86SelectCallAddress(Callee, CalleeAM))
1538     return false;
1539   unsigned CalleeOp = 0;
1540   const GlobalValue *GV = 0;
1541   if (CalleeAM.GV != 0) {
1542     GV = CalleeAM.GV;
1543   } else if (CalleeAM.Base.Reg != 0) {
1544     CalleeOp = CalleeAM.Base.Reg;
1545   } else
1546     return false;
1547
1548   // Allow calls which produce i1 results.
1549   bool AndToI1 = false;
1550   if (RetVT == MVT::i1) {
1551     RetVT = MVT::i8;
1552     AndToI1 = true;
1553   }
1554
1555   // Deal with call operands first.
1556   SmallVector<const Value *, 8> ArgVals;
1557   SmallVector<unsigned, 8> Args;
1558   SmallVector<MVT, 8> ArgVTs;
1559   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1560   Args.reserve(CS.arg_size());
1561   ArgVals.reserve(CS.arg_size());
1562   ArgVTs.reserve(CS.arg_size());
1563   ArgFlags.reserve(CS.arg_size());
1564   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1565        i != e; ++i) {
1566     Value *ArgVal = *i;
1567     ISD::ArgFlagsTy Flags;
1568     unsigned AttrInd = i - CS.arg_begin() + 1;
1569     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1570       Flags.setSExt();
1571     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1572       Flags.setZExt();
1573
1574     // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1575     // instruction.  This is safe because it is common to all fastisel supported
1576     // calling conventions on x86.
1577     if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1578       if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1579           CI->getBitWidth() == 16) {
1580         if (Flags.isSExt())
1581           ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1582         else
1583           ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1584       }
1585     }
1586     
1587     unsigned ArgReg;
1588     
1589     // Passing bools around ends up doing a trunc to i1 and passing it.
1590     // Codegen this as an argument + "and 1".
1591     if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1592         cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1593         ArgVal->hasOneUse()) {
1594       ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1595       ArgReg = getRegForValue(ArgVal);
1596       if (ArgReg == 0) return false;
1597       
1598       MVT ArgVT;
1599       if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1600       
1601       ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1602                            ArgVal->hasOneUse(), 1);
1603     } else {
1604       ArgReg = getRegForValue(ArgVal);
1605     }
1606
1607     if (ArgReg == 0) return false;
1608
1609     // FIXME: Only handle *easy* calls for now.
1610     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1611         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1612         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1613         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1614       return false;
1615
1616     const Type *ArgTy = ArgVal->getType();
1617     MVT ArgVT;
1618     if (!isTypeLegal(ArgTy, ArgVT))
1619       return false;
1620     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1621     Flags.setOrigAlign(OriginalAlignment);
1622
1623     Args.push_back(ArgReg);
1624     ArgVals.push_back(ArgVal);
1625     ArgVTs.push_back(ArgVT);
1626     ArgFlags.push_back(Flags);
1627   }
1628
1629   // Analyze operands of the call, assigning locations to each operand.
1630   SmallVector<CCValAssign, 16> ArgLocs;
1631   CCState CCInfo(CC, isVarArg, TM, ArgLocs, I->getParent()->getContext());
1632
1633   // Allocate shadow area for Win64
1634   if (Subtarget->isTargetWin64())
1635     CCInfo.AllocateStack(32, 8);
1636
1637   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1638
1639   // Get a count of how many bytes are to be pushed on the stack.
1640   unsigned NumBytes = CCInfo.getNextStackOffset();
1641
1642   // Issue CALLSEQ_START
1643   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1644   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1645     .addImm(NumBytes);
1646
1647   // Process argument: walk the register/memloc assignments, inserting
1648   // copies / loads.
1649   SmallVector<unsigned, 4> RegArgs;
1650   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1651     CCValAssign &VA = ArgLocs[i];
1652     unsigned Arg = Args[VA.getValNo()];
1653     EVT ArgVT = ArgVTs[VA.getValNo()];
1654
1655     // Promote the value if needed.
1656     switch (VA.getLocInfo()) {
1657     default: llvm_unreachable("Unknown loc info!");
1658     case CCValAssign::Full: break;
1659     case CCValAssign::SExt: {
1660       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1661                                        Arg, ArgVT, Arg);
1662       assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1663       ArgVT = VA.getLocVT();
1664       break;
1665     }
1666     case CCValAssign::ZExt: {
1667       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1668                                        Arg, ArgVT, Arg);
1669       assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1670       ArgVT = VA.getLocVT();
1671       break;
1672     }
1673     case CCValAssign::AExt: {
1674       // We don't handle MMX parameters yet.
1675       if (VA.getLocVT().isVector() && VA.getLocVT().getSizeInBits() == 128)
1676         return false;
1677       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1678                                        Arg, ArgVT, Arg);
1679       if (!Emitted)
1680         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1681                                     Arg, ArgVT, Arg);
1682       if (!Emitted)
1683         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1684                                     Arg, ArgVT, Arg);
1685
1686       assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1687       ArgVT = VA.getLocVT();
1688       break;
1689     }
1690     case CCValAssign::BCvt: {
1691       unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1692                                ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1693       assert(BC != 0 && "Failed to emit a bitcast!");
1694       Arg = BC;
1695       ArgVT = VA.getLocVT();
1696       break;
1697     }
1698     }
1699
1700     if (VA.isRegLoc()) {
1701       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1702               VA.getLocReg()).addReg(Arg);
1703       RegArgs.push_back(VA.getLocReg());
1704     } else {
1705       unsigned LocMemOffset = VA.getLocMemOffset();
1706       X86AddressMode AM;
1707       AM.Base.Reg = StackPtr;
1708       AM.Disp = LocMemOffset;
1709       const Value *ArgVal = ArgVals[VA.getValNo()];
1710
1711       // If this is a really simple value, emit this with the Value* version of
1712       // X86FastEmitStore.  If it isn't simple, we don't want to do this, as it
1713       // can cause us to reevaluate the argument.
1714       if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1715         X86FastEmitStore(ArgVT, ArgVal, AM);
1716       else
1717         X86FastEmitStore(ArgVT, Arg, AM);
1718     }
1719   }
1720
1721   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1722   // GOT pointer.
1723   if (Subtarget->isPICStyleGOT()) {
1724     unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1725     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1726             X86::EBX).addReg(Base);
1727   }
1728
1729   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1730     // Count the number of XMM registers allocated.
1731     static const unsigned XMMArgRegs[] = {
1732       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1733       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1734     };
1735     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1736     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1737             X86::AL).addImm(NumXMMRegs);
1738   }
1739
1740   // Issue the call.
1741   MachineInstrBuilder MIB;
1742   if (CalleeOp) {
1743     // Register-indirect call.
1744     unsigned CallOpc;
1745     if (Subtarget->isTargetWin64())
1746       CallOpc = X86::WINCALL64r;
1747     else if (Subtarget->is64Bit())
1748       CallOpc = X86::CALL64r;
1749     else
1750       CallOpc = X86::CALL32r;
1751     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1752       .addReg(CalleeOp);
1753
1754   } else {
1755     // Direct call.
1756     assert(GV && "Not a direct call");
1757     unsigned CallOpc;
1758     if (Subtarget->isTargetWin64())
1759       CallOpc = X86::WINCALL64pcrel32;
1760     else if (Subtarget->is64Bit())
1761       CallOpc = X86::CALL64pcrel32;
1762     else
1763       CallOpc = X86::CALLpcrel32;
1764
1765     // See if we need any target-specific flags on the GV operand.
1766     unsigned char OpFlags = 0;
1767
1768     // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1769     // external symbols most go through the PLT in PIC mode.  If the symbol
1770     // has hidden or protected visibility, or if it is static or local, then
1771     // we don't need to use the PLT - we can directly call it.
1772     if (Subtarget->isTargetELF() &&
1773         TM.getRelocationModel() == Reloc::PIC_ &&
1774         GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1775       OpFlags = X86II::MO_PLT;
1776     } else if (Subtarget->isPICStyleStubAny() &&
1777                (GV->isDeclaration() || GV->isWeakForLinker()) &&
1778                (!Subtarget->getTargetTriple().isMacOSX() ||
1779                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1780       // PC-relative references to external symbols should go through $stub,
1781       // unless we're building with the leopard linker or later, which
1782       // automatically synthesizes these stubs.
1783       OpFlags = X86II::MO_DARWIN_STUB;
1784     }
1785
1786
1787     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1788       .addGlobalAddress(GV, 0, OpFlags);
1789   }
1790
1791   // Add an implicit use GOT pointer in EBX.
1792   if (Subtarget->isPICStyleGOT())
1793     MIB.addReg(X86::EBX);
1794
1795   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1796     MIB.addReg(X86::AL);
1797
1798   // Add implicit physical register uses to the call.
1799   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1800     MIB.addReg(RegArgs[i]);
1801
1802   // Issue CALLSEQ_END
1803   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1804   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1805     .addImm(NumBytes).addImm(0);
1806
1807   // Now handle call return value (if any).
1808   SmallVector<unsigned, 4> UsedRegs;
1809   if (RetVT != MVT::isVoid) {
1810     SmallVector<CCValAssign, 16> RVLocs;
1811     CCState CCInfo(CC, false, TM, RVLocs, I->getParent()->getContext());
1812     CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1813
1814     // Copy all of the result registers out of their specified physreg.
1815     assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1816     EVT CopyVT = RVLocs[0].getValVT();
1817     TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1818
1819     // If this is a call to a function that returns an fp value on the x87 fp
1820     // stack, but where we prefer to use the value in xmm registers, copy it
1821     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1822     if ((RVLocs[0].getLocReg() == X86::ST0 ||
1823          RVLocs[0].getLocReg() == X86::ST1) &&
1824         isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1825       CopyVT = MVT::f80;
1826       DstRC = X86::RFP80RegisterClass;
1827     }
1828
1829     unsigned ResultReg = createResultReg(DstRC);
1830     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1831             ResultReg).addReg(RVLocs[0].getLocReg());
1832     UsedRegs.push_back(RVLocs[0].getLocReg());
1833
1834     if (CopyVT != RVLocs[0].getValVT()) {
1835       // Round the F80 the right size, which also moves to the appropriate xmm
1836       // register. This is accomplished by storing the F80 value in memory and
1837       // then loading it back. Ewww...
1838       EVT ResVT = RVLocs[0].getValVT();
1839       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1840       unsigned MemSize = ResVT.getSizeInBits()/8;
1841       int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1842       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1843                                 TII.get(Opc)), FI)
1844         .addReg(ResultReg);
1845       DstRC = ResVT == MVT::f32
1846         ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1847       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1848       ResultReg = createResultReg(DstRC);
1849       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1850                                 TII.get(Opc), ResultReg), FI);
1851     }
1852
1853     if (AndToI1) {
1854       // Mask out all but lowest bit for some call which produces an i1.
1855       unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1856       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1857               TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1858       ResultReg = AndResult;
1859     }
1860
1861     UpdateValueMap(I, ResultReg);
1862   }
1863
1864   // Set all unused physreg defs as dead.
1865   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1866
1867   return true;
1868 }
1869
1870
1871 bool
1872 X86FastISel::TargetSelectInstruction(const Instruction *I)  {
1873   switch (I->getOpcode()) {
1874   default: break;
1875   case Instruction::Load:
1876     return X86SelectLoad(I);
1877   case Instruction::Store:
1878     return X86SelectStore(I);
1879   case Instruction::Ret:
1880     return X86SelectRet(I);
1881   case Instruction::ICmp:
1882   case Instruction::FCmp:
1883     return X86SelectCmp(I);
1884   case Instruction::ZExt:
1885     return X86SelectZExt(I);
1886   case Instruction::Br:
1887     return X86SelectBranch(I);
1888   case Instruction::Call:
1889     return X86SelectCall(I);
1890   case Instruction::LShr:
1891   case Instruction::AShr:
1892   case Instruction::Shl:
1893     return X86SelectShift(I);
1894   case Instruction::Select:
1895     return X86SelectSelect(I);
1896   case Instruction::Trunc:
1897     return X86SelectTrunc(I);
1898   case Instruction::FPExt:
1899     return X86SelectFPExt(I);
1900   case Instruction::FPTrunc:
1901     return X86SelectFPTrunc(I);
1902   case Instruction::ExtractValue:
1903     return X86SelectExtractValue(I);
1904   case Instruction::IntToPtr: // Deliberate fall-through.
1905   case Instruction::PtrToInt: {
1906     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1907     EVT DstVT = TLI.getValueType(I->getType());
1908     if (DstVT.bitsGT(SrcVT))
1909       return X86SelectZExt(I);
1910     if (DstVT.bitsLT(SrcVT))
1911       return X86SelectTrunc(I);
1912     unsigned Reg = getRegForValue(I->getOperand(0));
1913     if (Reg == 0) return false;
1914     UpdateValueMap(I, Reg);
1915     return true;
1916   }
1917   }
1918
1919   return false;
1920 }
1921
1922 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
1923   MVT VT;
1924   if (!isTypeLegal(C->getType(), VT))
1925     return false;
1926
1927   // Get opcode and regclass of the output for the given load instruction.
1928   unsigned Opc = 0;
1929   const TargetRegisterClass *RC = NULL;
1930   switch (VT.SimpleTy) {
1931   default: return false;
1932   case MVT::i8:
1933     Opc = X86::MOV8rm;
1934     RC  = X86::GR8RegisterClass;
1935     break;
1936   case MVT::i16:
1937     Opc = X86::MOV16rm;
1938     RC  = X86::GR16RegisterClass;
1939     break;
1940   case MVT::i32:
1941     Opc = X86::MOV32rm;
1942     RC  = X86::GR32RegisterClass;
1943     break;
1944   case MVT::i64:
1945     // Must be in x86-64 mode.
1946     Opc = X86::MOV64rm;
1947     RC  = X86::GR64RegisterClass;
1948     break;
1949   case MVT::f32:
1950     if (Subtarget->hasSSE1()) {
1951       Opc = X86::MOVSSrm;
1952       RC  = X86::FR32RegisterClass;
1953     } else {
1954       Opc = X86::LD_Fp32m;
1955       RC  = X86::RFP32RegisterClass;
1956     }
1957     break;
1958   case MVT::f64:
1959     if (Subtarget->hasSSE2()) {
1960       Opc = X86::MOVSDrm;
1961       RC  = X86::FR64RegisterClass;
1962     } else {
1963       Opc = X86::LD_Fp64m;
1964       RC  = X86::RFP64RegisterClass;
1965     }
1966     break;
1967   case MVT::f80:
1968     // No f80 support yet.
1969     return false;
1970   }
1971
1972   // Materialize addresses with LEA instructions.
1973   if (isa<GlobalValue>(C)) {
1974     X86AddressMode AM;
1975     if (X86SelectAddress(C, AM)) {
1976       // If the expression is just a basereg, then we're done, otherwise we need
1977       // to emit an LEA.
1978       if (AM.BaseType == X86AddressMode::RegBase &&
1979           AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
1980         return AM.Base.Reg;
1981       
1982       Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
1983       unsigned ResultReg = createResultReg(RC);
1984       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1985                              TII.get(Opc), ResultReg), AM);
1986       return ResultReg;
1987     }
1988     return 0;
1989   }
1990
1991   // MachineConstantPool wants an explicit alignment.
1992   unsigned Align = TD.getPrefTypeAlignment(C->getType());
1993   if (Align == 0) {
1994     // Alignment of vector types.  FIXME!
1995     Align = TD.getTypeAllocSize(C->getType());
1996   }
1997
1998   // x86-32 PIC requires a PIC base register for constant pools.
1999   unsigned PICBase = 0;
2000   unsigned char OpFlag = 0;
2001   if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2002     OpFlag = X86II::MO_PIC_BASE_OFFSET;
2003     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2004   } else if (Subtarget->isPICStyleGOT()) {
2005     OpFlag = X86II::MO_GOTOFF;
2006     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2007   } else if (Subtarget->isPICStyleRIPRel() &&
2008              TM.getCodeModel() == CodeModel::Small) {
2009     PICBase = X86::RIP;
2010   }
2011
2012   // Create the load from the constant pool.
2013   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2014   unsigned ResultReg = createResultReg(RC);
2015   addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2016                                    TII.get(Opc), ResultReg),
2017                            MCPOffset, PICBase, OpFlag);
2018
2019   return ResultReg;
2020 }
2021
2022 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2023   // Fail on dynamic allocas. At this point, getRegForValue has already
2024   // checked its CSE maps, so if we're here trying to handle a dynamic
2025   // alloca, we're not going to succeed. X86SelectAddress has a
2026   // check for dynamic allocas, because it's called directly from
2027   // various places, but TargetMaterializeAlloca also needs a check
2028   // in order to avoid recursion between getRegForValue,
2029   // X86SelectAddrss, and TargetMaterializeAlloca.
2030   if (!FuncInfo.StaticAllocaMap.count(C))
2031     return 0;
2032
2033   X86AddressMode AM;
2034   if (!X86SelectAddress(C, AM))
2035     return 0;
2036   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2037   TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2038   unsigned ResultReg = createResultReg(RC);
2039   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2040                          TII.get(Opc), ResultReg), AM);
2041   return ResultReg;
2042 }
2043
2044 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2045 /// vreg is being provided by the specified load instruction.  If possible,
2046 /// try to fold the load as an operand to the instruction, returning true if
2047 /// possible.
2048 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2049                                 const LoadInst *LI) {
2050   X86AddressMode AM;
2051   if (!X86SelectAddress(LI->getOperand(0), AM))
2052     return false;
2053
2054   X86InstrInfo &XII = (X86InstrInfo&)TII;
2055
2056   unsigned Size = TD.getTypeAllocSize(LI->getType());
2057   unsigned Alignment = LI->getAlignment();
2058
2059   SmallVector<MachineOperand, 8> AddrOps;
2060   AM.getFullAddress(AddrOps);
2061
2062   MachineInstr *Result =
2063     XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2064   if (Result == 0) return false;
2065
2066   FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2067   MI->eraseFromParent();
2068   return true;
2069 }
2070
2071
2072 namespace llvm {
2073   llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
2074     return new X86FastISel(funcInfo);
2075   }
2076 }