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