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