Initial fastisel call support for C, Fast, and X86_FastCall calling conventions....
[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/Instructions.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Support/CallSite.h"
30
31 using namespace llvm;
32
33 class X86FastISel : public FastISel {
34   /// MFI - Keep track of objects allocated on the stack.
35   ///
36   MachineFrameInfo *MFI;
37
38   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
39   /// make the right decision when generating code for different targets.
40   const X86Subtarget *Subtarget;
41
42   /// StackPtr - Register used as the stack pointer.
43   ///
44   unsigned StackPtr;
45
46   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 
47   /// floating point ops.
48   /// When SSE is available, use it for f32 operations.
49   /// When SSE2 is available, use it for f64 operations.
50   bool X86ScalarSSEf64;
51   bool X86ScalarSSEf32;
52
53 public:
54   explicit X86FastISel(MachineFunction &mf,
55                        DenseMap<const Value *, unsigned> &vm,
56                        DenseMap<const BasicBlock *, MachineBasicBlock *> &bm)
57     : FastISel(mf, vm, bm), MFI(MF.getFrameInfo()) {
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(Instruction *I);
65
66 #include "X86GenFastISel.inc"
67
68 private:
69   bool X86FastEmitLoad(MVT VT, unsigned Op0, Value *V, unsigned &RR);
70
71   bool X86FastEmitStore(MVT VT, unsigned Val,
72                         unsigned Ptr, unsigned Offset, Value *V);
73   
74   bool X86SelectConstAddr(Value *V, unsigned &Op0, bool isCall = false);
75
76   bool X86SelectLoad(Instruction *I);
77   
78   bool X86SelectStore(Instruction *I);
79
80   bool X86SelectCmp(Instruction *I);
81
82   bool X86SelectZExt(Instruction *I);
83
84   bool X86SelectBranch(Instruction *I);
85
86   bool X86SelectShift(Instruction *I);
87
88   bool X86SelectSelect(Instruction *I);
89
90   bool X86SelectTrunc(Instruction *I);
91
92   bool X86SelectCall(Instruction *I);
93
94   CCAssignFn *CCAssignFnForCall(unsigned CC, bool isTailCall = false);
95
96   unsigned TargetMaterializeConstant(Constant *C, MachineConstantPool* MCP);
97
98   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
99   /// computed in an SSE register, not on the X87 floating point stack.
100   bool isScalarFPTypeInSSEReg(MVT VT) const {
101     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
102       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
103   }
104
105 };
106
107 static bool isTypeLegal(const Type *Ty, const TargetLowering &TLI, MVT &VT) {
108   VT = MVT::getMVT(Ty, /*HandleUnknown=*/true);
109   if (VT == MVT::Other || !VT.isSimple())
110     // Unhandled type. Halt "fast" selection and bail.
111     return false;
112   if (VT == MVT::iPTR)
113     // Use pointer type.
114     VT = TLI.getPointerTy();
115   // We only handle legal types. For example, on x86-32 the instruction
116   // selector contains all of the 64-bit instructions from x86-64,
117   // under the assumption that i64 won't be used if the target doesn't
118   // support it.
119   return TLI.isTypeLegal(VT);
120 }
121
122 #include "X86GenCallingConv.inc"
123
124 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
125 /// convention.
126 CCAssignFn *X86FastISel::CCAssignFnForCall(unsigned CC, bool isTaillCall) {
127   if (Subtarget->is64Bit()) {
128     if (Subtarget->isTargetWin64())
129       return CC_X86_Win64_C;
130     else if (CC == CallingConv::Fast && isTaillCall)
131       return CC_X86_64_TailCall;
132     else
133       return CC_X86_64_C;
134   }
135
136   if (CC == CallingConv::X86_FastCall)
137     return CC_X86_32_FastCall;
138   else if (CC == CallingConv::Fast && isTaillCall)
139     return CC_X86_32_TailCall;
140   else if (CC == CallingConv::Fast)
141     return CC_X86_32_FastCC;
142   else
143     return CC_X86_32_C;
144 }
145
146 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
147 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
148 /// Return true and the result register by reference if it is possible.
149 bool X86FastISel::X86FastEmitLoad(MVT VT, unsigned Ptr, Value *GV,
150                                   unsigned &ResultReg) {
151   // Get opcode and regclass of the output for the given load instruction.
152   unsigned Opc = 0;
153   const TargetRegisterClass *RC = NULL;
154   switch (VT.getSimpleVT()) {
155   default: return false;
156   case MVT::i8:
157     Opc = X86::MOV8rm;
158     RC  = X86::GR8RegisterClass;
159     break;
160   case MVT::i16:
161     Opc = X86::MOV16rm;
162     RC  = X86::GR16RegisterClass;
163     break;
164   case MVT::i32:
165     Opc = X86::MOV32rm;
166     RC  = X86::GR32RegisterClass;
167     break;
168   case MVT::i64:
169     // Must be in x86-64 mode.
170     Opc = X86::MOV64rm;
171     RC  = X86::GR64RegisterClass;
172     break;
173   case MVT::f32:
174     if (Subtarget->hasSSE1()) {
175       Opc = X86::MOVSSrm;
176       RC  = X86::FR32RegisterClass;
177     } else {
178       Opc = X86::LD_Fp32m;
179       RC  = X86::RFP32RegisterClass;
180     }
181     break;
182   case MVT::f64:
183     if (Subtarget->hasSSE2()) {
184       Opc = X86::MOVSDrm;
185       RC  = X86::FR64RegisterClass;
186     } else {
187       Opc = X86::LD_Fp64m;
188       RC  = X86::RFP64RegisterClass;
189     }
190     break;
191   case MVT::f80:
192     Opc = X86::LD_Fp80m;
193     RC  = X86::RFP80RegisterClass;
194     break;
195   }
196
197   ResultReg = createResultReg(RC);
198   X86AddressMode AM;
199   if (Ptr)
200     // Address is in register.
201     AM.Base.Reg = Ptr;
202   else
203     AM.GV = cast<GlobalValue>(GV);
204   addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
205   return true;
206 }
207
208 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
209 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
210 /// and a displacement offset, or a GlobalAddress,
211 /// i.e. V. Return true if it is possible.
212 bool
213 X86FastISel::X86FastEmitStore(MVT VT, unsigned Val,
214                               unsigned Ptr, unsigned Offset, Value *V) {
215   // Get opcode and regclass of the output for the given load instruction.
216   unsigned Opc = 0;
217   const TargetRegisterClass *RC = NULL;
218   switch (VT.getSimpleVT()) {
219   default: return false;
220   case MVT::i8:
221     Opc = X86::MOV8mr;
222     RC  = X86::GR8RegisterClass;
223     break;
224   case MVT::i16:
225     Opc = X86::MOV16mr;
226     RC  = X86::GR16RegisterClass;
227     break;
228   case MVT::i32:
229     Opc = X86::MOV32mr;
230     RC  = X86::GR32RegisterClass;
231     break;
232   case MVT::i64:
233     // Must be in x86-64 mode.
234     Opc = X86::MOV64mr;
235     RC  = X86::GR64RegisterClass;
236     break;
237   case MVT::f32:
238     if (Subtarget->hasSSE1()) {
239       Opc = X86::MOVSSmr;
240       RC  = X86::FR32RegisterClass;
241     } else {
242       Opc = X86::ST_Fp32m;
243       RC  = X86::RFP32RegisterClass;
244     }
245     break;
246   case MVT::f64:
247     if (Subtarget->hasSSE2()) {
248       Opc = X86::MOVSDmr;
249       RC  = X86::FR64RegisterClass;
250     } else {
251       Opc = X86::ST_Fp64m;
252       RC  = X86::RFP64RegisterClass;
253     }
254     break;
255   case MVT::f80:
256     Opc = X86::ST_FP80m;
257     RC  = X86::RFP80RegisterClass;
258     break;
259   }
260
261   X86AddressMode AM;
262   if (Ptr) {
263     // Address is in register.
264     AM.Base.Reg = Ptr;
265     AM.Disp = Offset;
266   } else
267     AM.GV = cast<GlobalValue>(V);
268   addFullAddress(BuildMI(MBB, TII.get(Opc)), AM).addReg(Val);
269   return true;
270 }
271
272 /// X86SelectConstAddr - Select and emit code to materialize constant address.
273 /// 
274 bool X86FastISel::X86SelectConstAddr(Value *V, unsigned &Op0, bool isCall) {
275   // FIXME: Only GlobalAddress for now.
276   GlobalValue *GV = dyn_cast<GlobalValue>(V);
277   if (!GV)
278     return false;
279
280   if (Subtarget->GVRequiresExtraLoad(GV, TM, isCall)) {
281     // Issue load from stub if necessary.
282     unsigned Opc = 0;
283     const TargetRegisterClass *RC = NULL;
284     if (TLI.getPointerTy() == MVT::i32) {
285       Opc = X86::MOV32rm;
286       RC  = X86::GR32RegisterClass;
287     } else {
288       Opc = X86::MOV64rm;
289       RC  = X86::GR64RegisterClass;
290     }
291     Op0 = createResultReg(RC);
292     X86AddressMode AM;
293     AM.GV = GV;
294     addFullAddress(BuildMI(MBB, TII.get(Opc), Op0), AM);
295     // Prevent loading GV stub multiple times in same MBB.
296     LocalValueMap[V] = Op0;
297   }
298   return true;
299 }
300
301 /// X86SelectStore - Select and emit code to implement store instructions.
302 bool X86FastISel::X86SelectStore(Instruction* I) {
303   MVT VT = MVT::getMVT(I->getOperand(0)->getType());
304   if (VT == MVT::Other || !VT.isSimple())
305     // Unhandled type.  Halt "fast" selection and bail.
306     return false;
307   if (VT == MVT::iPTR)
308     // Use pointer type.
309     VT = TLI.getPointerTy();
310   // We only handle legal types. For example, on x86-32 the instruction
311   // selector contains all of the 64-bit instructions from x86-64,
312   // under the assumption that i64 won't be used if the target doesn't
313   // support it.
314   if (!TLI.isTypeLegal(VT))
315     return false;
316   unsigned Val = getRegForValue(I->getOperand(0));
317   if (Val == 0)
318     // Unhandled operand. Halt "fast" selection and bail.
319     return false;    
320
321   Value *V = I->getOperand(1);
322   unsigned Ptr = getRegForValue(V);
323   if (Ptr == 0) {
324     // Handle constant load address.
325     if (!isa<Constant>(V) || !X86SelectConstAddr(V, Ptr))
326       // Unhandled operand. Halt "fast" selection and bail.
327       return false;    
328   }
329
330   return X86FastEmitStore(VT, Val, Ptr, 0, V);
331 }
332
333 /// X86SelectLoad - Select and emit code to implement load instructions.
334 ///
335 bool X86FastISel::X86SelectLoad(Instruction *I)  {
336   MVT VT;
337   if (!isTypeLegal(I->getType(), TLI, VT))
338     return false;
339
340   Value *V = I->getOperand(0);
341   unsigned Ptr = getRegForValue(V);
342   if (Ptr == 0) {
343     // Handle constant load address.
344     // FIXME: If load type is something we can't handle, this can result in
345     // a dead stub load instruction.
346     if (!isa<Constant>(V) || !X86SelectConstAddr(V, Ptr))
347       // Unhandled operand. Halt "fast" selection and bail.
348       return false;    
349   }
350
351   unsigned ResultReg = 0;
352   if (X86FastEmitLoad(VT, Ptr, V, ResultReg)) {
353     UpdateValueMap(I, ResultReg);
354     return true;
355   }
356   return false;
357 }
358
359 bool X86FastISel::X86SelectCmp(Instruction *I) {
360   CmpInst *CI = cast<CmpInst>(I);
361
362   MVT VT = TLI.getValueType(I->getOperand(0)->getType());
363   if (!TLI.isTypeLegal(VT))
364     return false;
365
366   unsigned Op0Reg = getRegForValue(CI->getOperand(0));
367   if (Op0Reg == 0) return false;
368   unsigned Op1Reg = getRegForValue(CI->getOperand(1));
369   if (Op1Reg == 0) return false;
370
371   unsigned Opc;
372   switch (VT.getSimpleVT()) {
373   case MVT::i8: Opc = X86::CMP8rr; break;
374   case MVT::i16: Opc = X86::CMP16rr; break;
375   case MVT::i32: Opc = X86::CMP32rr; break;
376   case MVT::i64: Opc = X86::CMP64rr; break;
377   case MVT::f32: Opc = X86::UCOMISSrr; break;
378   case MVT::f64: Opc = X86::UCOMISDrr; break;
379   default: return false;
380   }
381
382   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
383   switch (CI->getPredicate()) {
384   case CmpInst::FCMP_OEQ: {
385     unsigned EReg = createResultReg(&X86::GR8RegClass);
386     unsigned NPReg = createResultReg(&X86::GR8RegClass);
387     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
388     BuildMI(MBB, TII.get(X86::SETEr), EReg);
389     BuildMI(MBB, TII.get(X86::SETNPr), NPReg);
390     BuildMI(MBB, TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
391     break;
392   }
393   case CmpInst::FCMP_UNE: {
394     unsigned NEReg = createResultReg(&X86::GR8RegClass);
395     unsigned PReg = createResultReg(&X86::GR8RegClass);
396     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
397     BuildMI(MBB, TII.get(X86::SETNEr), NEReg);
398     BuildMI(MBB, TII.get(X86::SETPr), PReg);
399     BuildMI(MBB, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
400     break;
401   }
402   case CmpInst::FCMP_OGT:
403     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
404     BuildMI(MBB, TII.get(X86::SETAr), ResultReg);
405     break;
406   case CmpInst::FCMP_OGE:
407     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
408     BuildMI(MBB, TII.get(X86::SETAEr), ResultReg);
409     break;
410   case CmpInst::FCMP_OLT:
411     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
412     BuildMI(MBB, TII.get(X86::SETAr), ResultReg);
413     break;
414   case CmpInst::FCMP_OLE:
415     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
416     BuildMI(MBB, TII.get(X86::SETAEr), ResultReg);
417     break;
418   case CmpInst::FCMP_ONE:
419     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
420     BuildMI(MBB, TII.get(X86::SETNEr), ResultReg);
421     break;
422   case CmpInst::FCMP_ORD:
423     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
424     BuildMI(MBB, TII.get(X86::SETNPr), ResultReg);
425     break;
426   case CmpInst::FCMP_UNO:
427     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
428     BuildMI(MBB, TII.get(X86::SETPr), ResultReg);
429     break;
430   case CmpInst::FCMP_UEQ:
431     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
432     BuildMI(MBB, TII.get(X86::SETEr), ResultReg);
433     break;
434   case CmpInst::FCMP_UGT:
435     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
436     BuildMI(MBB, TII.get(X86::SETBr), ResultReg);
437     break;
438   case CmpInst::FCMP_UGE:
439     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
440     BuildMI(MBB, TII.get(X86::SETBEr), ResultReg);
441     break;
442   case CmpInst::FCMP_ULT:
443     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
444     BuildMI(MBB, TII.get(X86::SETBr), ResultReg);
445     break;
446   case CmpInst::FCMP_ULE:
447     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
448     BuildMI(MBB, TII.get(X86::SETBEr), ResultReg);
449     break;
450   case CmpInst::ICMP_EQ:
451     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
452     BuildMI(MBB, TII.get(X86::SETEr), ResultReg);
453     break;
454   case CmpInst::ICMP_NE:
455     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
456     BuildMI(MBB, TII.get(X86::SETNEr), ResultReg);
457     break;
458   case CmpInst::ICMP_UGT:
459     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
460     BuildMI(MBB, TII.get(X86::SETAr), ResultReg);
461     break;
462   case CmpInst::ICMP_UGE:
463     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
464     BuildMI(MBB, TII.get(X86::SETAEr), ResultReg);
465     break;
466   case CmpInst::ICMP_ULT:
467     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
468     BuildMI(MBB, TII.get(X86::SETBr), ResultReg);
469     break;
470   case CmpInst::ICMP_ULE:
471     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
472     BuildMI(MBB, TII.get(X86::SETBEr), ResultReg);
473     break;
474   case CmpInst::ICMP_SGT:
475     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
476     BuildMI(MBB, TII.get(X86::SETGr), ResultReg);
477     break;
478   case CmpInst::ICMP_SGE:
479     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
480     BuildMI(MBB, TII.get(X86::SETGEr), ResultReg);
481     break;
482   case CmpInst::ICMP_SLT:
483     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
484     BuildMI(MBB, TII.get(X86::SETLr), ResultReg);
485     break;
486   case CmpInst::ICMP_SLE:
487     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
488     BuildMI(MBB, TII.get(X86::SETLEr), ResultReg);
489     break;
490   default:
491     return false;
492   }
493
494   UpdateValueMap(I, ResultReg);
495   return true;
496 }
497
498 bool X86FastISel::X86SelectZExt(Instruction *I) {
499   // Special-case hack: The only i1 values we know how to produce currently
500   // set the upper bits of an i8 value to zero.
501   if (I->getType() == Type::Int8Ty &&
502       I->getOperand(0)->getType() == Type::Int1Ty) {
503     unsigned ResultReg = getRegForValue(I->getOperand(0));
504     if (ResultReg == 0) return false;
505     UpdateValueMap(I, ResultReg);
506     return true;
507   }
508
509   return false;
510 }
511
512 bool X86FastISel::X86SelectBranch(Instruction *I) {
513   BranchInst *BI = cast<BranchInst>(I);
514   // Unconditional branches are selected by tablegen-generated code.
515   unsigned OpReg = getRegForValue(BI->getCondition());
516   if (OpReg == 0) return false;
517   MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
518   MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
519
520   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
521   BuildMI(MBB, TII.get(X86::JNE)).addMBB(TrueMBB);
522   BuildMI(MBB, TII.get(X86::JMP)).addMBB(FalseMBB);
523
524   MBB->addSuccessor(TrueMBB);
525   MBB->addSuccessor(FalseMBB);
526
527   return true;
528 }
529
530 bool X86FastISel::X86SelectShift(Instruction *I) {
531   unsigned CReg = 0;
532   unsigned Opc = 0;
533   const TargetRegisterClass *RC = NULL;
534   if (I->getType() == Type::Int8Ty) {
535     CReg = X86::CL;
536     RC = &X86::GR8RegClass;
537     switch (I->getOpcode()) {
538     case Instruction::LShr: Opc = X86::SHR8rCL; break;
539     case Instruction::AShr: Opc = X86::SAR8rCL; break;
540     case Instruction::Shl:  Opc = X86::SHL8rCL; break;
541     default: return false;
542     }
543   } else if (I->getType() == Type::Int16Ty) {
544     CReg = X86::CX;
545     RC = &X86::GR16RegClass;
546     switch (I->getOpcode()) {
547     case Instruction::LShr: Opc = X86::SHR16rCL; break;
548     case Instruction::AShr: Opc = X86::SAR16rCL; break;
549     case Instruction::Shl:  Opc = X86::SHL16rCL; break;
550     default: return false;
551     }
552   } else if (I->getType() == Type::Int32Ty) {
553     CReg = X86::ECX;
554     RC = &X86::GR32RegClass;
555     switch (I->getOpcode()) {
556     case Instruction::LShr: Opc = X86::SHR32rCL; break;
557     case Instruction::AShr: Opc = X86::SAR32rCL; break;
558     case Instruction::Shl:  Opc = X86::SHL32rCL; break;
559     default: return false;
560     }
561   } else if (I->getType() == Type::Int64Ty) {
562     CReg = X86::RCX;
563     RC = &X86::GR64RegClass;
564     switch (I->getOpcode()) {
565     case Instruction::LShr: Opc = X86::SHR64rCL; break;
566     case Instruction::AShr: Opc = X86::SAR64rCL; break;
567     case Instruction::Shl:  Opc = X86::SHL64rCL; break;
568     default: return false;
569     }
570   } else {
571     return false;
572   }
573
574   MVT VT = MVT::getMVT(I->getType(), /*HandleUnknown=*/true);
575   if (VT == MVT::Other || !TLI.isTypeLegal(VT))
576     return false;
577
578   unsigned Op0Reg = getRegForValue(I->getOperand(0));
579   if (Op0Reg == 0) return false;
580   unsigned Op1Reg = getRegForValue(I->getOperand(1));
581   if (Op1Reg == 0) return false;
582   TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
583   unsigned ResultReg = createResultReg(RC);
584   BuildMI(MBB, TII.get(Opc), ResultReg).addReg(Op0Reg);
585   UpdateValueMap(I, ResultReg);
586   return true;
587 }
588
589 bool X86FastISel::X86SelectSelect(Instruction *I) {
590   const Type *Ty = I->getType();
591   if (isa<PointerType>(Ty))
592     Ty = TLI.getTargetData()->getIntPtrType();
593
594   unsigned Opc = 0;
595   const TargetRegisterClass *RC = NULL;
596   if (Ty == Type::Int16Ty) {
597     Opc = X86::CMOVE16rr;
598     RC = &X86::GR16RegClass;
599   } else if (Ty == Type::Int32Ty) {
600     Opc = X86::CMOVE32rr;
601     RC = &X86::GR32RegClass;
602   } else if (Ty == Type::Int64Ty) {
603     Opc = X86::CMOVE64rr;
604     RC = &X86::GR64RegClass;
605   } else {
606     return false; 
607   }
608
609   MVT VT = MVT::getMVT(Ty, /*HandleUnknown=*/true);
610   if (VT == MVT::Other || !TLI.isTypeLegal(VT))
611     return false;
612
613   unsigned Op0Reg = getRegForValue(I->getOperand(0));
614   if (Op0Reg == 0) return false;
615   unsigned Op1Reg = getRegForValue(I->getOperand(1));
616   if (Op1Reg == 0) return false;
617   unsigned Op2Reg = getRegForValue(I->getOperand(2));
618   if (Op2Reg == 0) return false;
619
620   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
621   unsigned ResultReg = createResultReg(RC);
622   BuildMI(MBB, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
623   UpdateValueMap(I, ResultReg);
624   return true;
625 }
626
627 bool X86FastISel::X86SelectTrunc(Instruction *I) {
628   if (Subtarget->is64Bit())
629     // All other cases should be handled by the tblgen generated code.
630     return false;
631   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
632   MVT DstVT = TLI.getValueType(I->getType());
633   if (DstVT != MVT::i8)
634     // All other cases should be handled by the tblgen generated code.
635     return false;
636   if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
637     // All other cases should be handled by the tblgen generated code.
638     return false;
639
640   unsigned InputReg = getRegForValue(I->getOperand(0));
641   if (!InputReg)
642     // Unhandled operand.  Halt "fast" selection and bail.
643     return false;
644
645   // First issue a copy to GR16_ or GR32_.
646   unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16to16_ : X86::MOV32to32_;
647   const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
648     ? X86::GR16_RegisterClass : X86::GR32_RegisterClass;
649   unsigned CopyReg = createResultReg(CopyRC);
650   BuildMI(MBB, TII.get(CopyOpc), CopyReg).addReg(InputReg);
651
652   // Then issue an extract_subreg.
653   unsigned ResultReg = FastEmitInst_extractsubreg(CopyReg,1); // x86_subreg_8bit
654   if (!ResultReg)
655     return false;
656
657   UpdateValueMap(I, ResultReg);
658   return true;
659 }
660
661 bool X86FastISel::X86SelectCall(Instruction *I) {
662   CallInst *CI = cast<CallInst>(I);
663   Value *Callee = I->getOperand(0);
664
665   // Can't handle inline asm yet.
666   if (isa<InlineAsm>(Callee))
667     return false;
668
669   // FIXME: Handle some intrinsics.
670   if (Function *F = CI->getCalledFunction()) {
671     if (F->isDeclaration() &&F->getIntrinsicID())
672       return false;
673   }
674
675   // Materialize callee address in a register. FIXME: GV address can be
676   // handled with a CALLpcrel32 instead.
677   unsigned CalleeOp = getRegForValue(Callee);
678   if (CalleeOp == 0) {
679     if (!isa<Constant>(Callee) || !X86SelectConstAddr(Callee, CalleeOp, true))
680       // Unhandled operand. Halt "fast" selection and bail.
681       return false;    
682   }
683
684   // Handle only C and fastcc calling conventions for now.
685   CallSite CS(CI);
686   unsigned CC = CS.getCallingConv();
687   if (CC != CallingConv::C &&
688       CC != CallingConv::Fast &&
689       CC != CallingConv::X86_FastCall)
690     return false;
691
692   // Let SDISel handle vararg functions.
693   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
694   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
695   if (FTy->isVarArg())
696     return false;
697
698   // Handle *simple* calls for now.
699   const Type *RetTy = CS.getType();
700   MVT RetVT;
701   if (!isTypeLegal(RetTy, TLI, RetVT))
702     return false;
703
704   // Deal with call operands first.
705   SmallVector<unsigned, 4> Args;
706   SmallVector<MVT, 4> ArgVTs;
707   SmallVector<ISD::ArgFlagsTy, 4> ArgFlags;
708   Args.reserve(CS.arg_size());
709   ArgVTs.reserve(CS.arg_size());
710   ArgFlags.reserve(CS.arg_size());
711   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
712        i != e; ++i) {
713     unsigned Arg = getRegForValue(*i);
714     if (Arg == 0)
715       return false;
716     ISD::ArgFlagsTy Flags;
717     unsigned AttrInd = i - CS.arg_begin() + 1;
718     if (CS.paramHasAttr(AttrInd, ParamAttr::SExt))
719       Flags.setSExt();
720     if (CS.paramHasAttr(AttrInd, ParamAttr::ZExt))
721       Flags.setZExt();
722
723     // FIXME: Only handle *easy* calls for now.
724     if (CS.paramHasAttr(AttrInd, ParamAttr::InReg) ||
725         CS.paramHasAttr(AttrInd, ParamAttr::StructRet) ||
726         CS.paramHasAttr(AttrInd, ParamAttr::Nest) ||
727         CS.paramHasAttr(AttrInd, ParamAttr::ByVal))
728       return false;
729
730     const Type *ArgTy = (*i)->getType();
731     MVT ArgVT;
732     if (!isTypeLegal(ArgTy, TLI, ArgVT))
733       return false;
734     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
735     Flags.setOrigAlign(OriginalAlignment);
736
737     Args.push_back(Arg);
738     ArgVTs.push_back(ArgVT);
739     ArgFlags.push_back(Flags);
740   }
741
742   // Analyze operands of the call, assigning locations to each operand.
743   SmallVector<CCValAssign, 16> ArgLocs;
744   CCState CCInfo(CC, false, TM, ArgLocs);
745   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
746
747   // Get a count of how many bytes are to be pushed on the stack.
748   unsigned NumBytes = CCInfo.getNextStackOffset();
749
750   // Issue CALLSEQ_START
751   BuildMI(MBB, TII.get(X86::ADJCALLSTACKDOWN)).addImm(NumBytes);
752
753   // Process argumenet: walk the register/memloc assignments, inserting
754   // copies / loads.
755   SmallVector<unsigned, 4> RegArgs;
756   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
757     CCValAssign &VA = ArgLocs[i];
758     unsigned Arg = Args[VA.getValNo()];
759     MVT ArgVT = ArgVTs[VA.getValNo()];
760   
761     // Promote the value if needed.
762     switch (VA.getLocInfo()) {
763     default: assert(0 && "Unknown loc info!");
764     case CCValAssign::Full: break;
765     case CCValAssign::SExt:
766       abort(); // FIXME
767       break;
768     case CCValAssign::ZExt:
769       abort();
770       break;
771     case CCValAssign::AExt:
772       abort();
773       break;
774     }
775     
776     if (VA.isRegLoc()) {
777       TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
778       bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
779                                       Arg, RC, RC);
780       assert(Emitted && "Failed to emit a copy instruction!");
781       RegArgs.push_back(VA.getLocReg());
782     } else {
783       unsigned LocMemOffset = VA.getLocMemOffset();
784       X86FastEmitStore(ArgVT, Arg, StackPtr, LocMemOffset, NULL);
785     }
786   }
787
788   // Issue the call.
789   unsigned CallOpc = CalleeOp
790     ? (Subtarget->is64Bit() ? X86::CALL64r       : X86::CALL32r)
791     : (Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32);
792   MachineInstrBuilder MIB = CalleeOp
793     ? BuildMI(MBB, TII.get(CallOpc)).addReg(CalleeOp)
794     :BuildMI(MBB, TII.get(CallOpc)).addGlobalAddress(cast<GlobalValue>(Callee));
795   // Add implicit physical register uses to the call.
796   while (!RegArgs.empty()) {
797     MIB.addReg(RegArgs.back());
798     RegArgs.pop_back();
799   }
800
801   // Issue CALLSEQ_END
802   BuildMI(MBB, TII.get(X86::ADJCALLSTACKUP)).addImm(NumBytes).addImm(0);
803
804   // Now handle call return value (if any).
805 #if 0 // FIXME
806   bool isSExt = CS.paramHasAttr(0, ParamAttr::SExt);
807   bool isZExt = CS.paramHasAttr(0, ParamAttr::ZExt);
808 #endif
809   if (RetVT.getSimpleVT() != MVT::isVoid) {
810     SmallVector<CCValAssign, 16> RVLocs;
811     CCState CCInfo(CC, false, TM, RVLocs);
812     CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
813
814     // Copy all of the result registers out of their specified physreg.
815     assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
816     MVT CopyVT = RVLocs[0].getValVT();
817     TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
818     TargetRegisterClass *SrcRC = DstRC;
819     
820     // If this is a call to a function that returns an fp value on the x87 fp
821     // stack, but where we prefer to use the value in xmm registers, copy it
822     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
823     if ((RVLocs[0].getLocReg() == X86::ST0 ||
824          RVLocs[0].getLocReg() == X86::ST1) &&
825         isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
826       CopyVT = MVT::f80;
827       SrcRC = X86::RSTRegisterClass;
828       DstRC = X86::RFP80RegisterClass;
829     }
830
831     unsigned ResultReg = createResultReg(DstRC);
832     bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
833                                     RVLocs[0].getLocReg(), DstRC, SrcRC);
834     assert(Emitted && "Failed to emit a copy instruction!");
835     if (CopyVT != RVLocs[0].getValVT()) {
836       // Round the F80 the right size, which also moves to the appropriate xmm
837       // register. This is accomplished by storing the F80 value in memory and
838       // then loading it back. Ewww...
839       MVT ResVT = RVLocs[0].getValVT();
840       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
841       unsigned MemSize = ResVT.getSizeInBits()/8;
842       int FI = MFI->CreateStackObject(MemSize, MemSize);
843       addFrameReference(BuildMI(MBB, TII.get(Opc)), FI).addReg(ResultReg);
844       DstRC = ResVT == MVT::f32
845         ? X86::FR32RegisterClass : X86::FR64RegisterClass;
846       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
847       ResultReg = createResultReg(DstRC);
848       addFrameReference(BuildMI(MBB, TII.get(Opc), ResultReg), FI);
849     }
850
851     UpdateValueMap(I, ResultReg);
852   }
853
854   return true;
855 }
856
857
858 bool
859 X86FastISel::TargetSelectInstruction(Instruction *I)  {
860   switch (I->getOpcode()) {
861   default: break;
862   case Instruction::Load:
863     return X86SelectLoad(I);
864   case Instruction::Store:
865     return X86SelectStore(I);
866   case Instruction::ICmp:
867   case Instruction::FCmp:
868     return X86SelectCmp(I);
869   case Instruction::ZExt:
870     return X86SelectZExt(I);
871   case Instruction::Br:
872     return X86SelectBranch(I);
873 #if 0
874   case Instruction::Call:
875     return X86SelectCall(I);
876 #endif
877   case Instruction::LShr:
878   case Instruction::AShr:
879   case Instruction::Shl:
880     return X86SelectShift(I);
881   case Instruction::Select:
882     return X86SelectSelect(I);
883   case Instruction::Trunc:
884     return X86SelectTrunc(I);
885   }
886
887   return false;
888 }
889
890 unsigned X86FastISel::TargetMaterializeConstant(Constant *C,
891                                                 MachineConstantPool* MCP) {
892   // Can't handle PIC-mode yet.
893   if (TM.getRelocationModel() == Reloc::PIC_)
894     return 0;
895   
896   MVT VT = MVT::getMVT(C->getType(), /*HandleUnknown=*/true);
897   if (VT == MVT::Other || !VT.isSimple())
898     // Unhandled type. Halt "fast" selection and bail.
899     return false;
900   if (VT == MVT::iPTR)
901     // Use pointer type.
902     VT = TLI.getPointerTy();
903   // We only handle legal types. For example, on x86-32 the instruction
904   // selector contains all of the 64-bit instructions from x86-64,
905   // under the assumption that i64 won't be used if the target doesn't
906   // support it.
907   if (!TLI.isTypeLegal(VT))
908     return false;
909   
910   // Get opcode and regclass of the output for the given load instruction.
911   unsigned Opc = 0;
912   const TargetRegisterClass *RC = NULL;
913   switch (VT.getSimpleVT()) {
914   default: return false;
915   case MVT::i8:
916     Opc = X86::MOV8rm;
917     RC  = X86::GR8RegisterClass;
918     break;
919   case MVT::i16:
920     Opc = X86::MOV16rm;
921     RC  = X86::GR16RegisterClass;
922     break;
923   case MVT::i32:
924     Opc = X86::MOV32rm;
925     RC  = X86::GR32RegisterClass;
926     break;
927   case MVT::i64:
928     // Must be in x86-64 mode.
929     Opc = X86::MOV64rm;
930     RC  = X86::GR64RegisterClass;
931     break;
932   case MVT::f32:
933     if (Subtarget->hasSSE1()) {
934       Opc = X86::MOVSSrm;
935       RC  = X86::FR32RegisterClass;
936     } else {
937       Opc = X86::LD_Fp32m;
938       RC  = X86::RFP32RegisterClass;
939     }
940     break;
941   case MVT::f64:
942     if (Subtarget->hasSSE2()) {
943       Opc = X86::MOVSDrm;
944       RC  = X86::FR64RegisterClass;
945     } else {
946       Opc = X86::LD_Fp64m;
947       RC  = X86::RFP64RegisterClass;
948     }
949     break;
950   case MVT::f80:
951     Opc = X86::LD_Fp80m;
952     RC  = X86::RFP80RegisterClass;
953     break;
954   }
955   
956   unsigned ResultReg = createResultReg(RC);
957   if (isa<GlobalValue>(C)) {
958     // FIXME: If store value type is something we can't handle, this can result
959     // in a dead stub load instruction.
960     if (X86SelectConstAddr(C, ResultReg))
961       return ResultReg;
962     return 0;
963   }
964   
965   // MachineConstantPool wants an explicit alignment.
966   unsigned Align =
967                TM.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
968   if (Align == 0) {
969     // Alignment of vector types.  FIXME!
970     Align = TM.getTargetData()->getABITypeSize(C->getType());
971     Align = Log2_64(Align);
972   }
973   
974   unsigned MCPOffset = MCP->getConstantPoolIndex(C, Align);
975   addConstantPoolReference(BuildMI(MBB, TII.get(Opc), ResultReg), MCPOffset);
976   return ResultReg;
977 }
978
979 namespace llvm {
980   llvm::FastISel *X86::createFastISel(MachineFunction &mf,
981                         DenseMap<const Value *, unsigned> &vm,
982                         DenseMap<const BasicBlock *, MachineBasicBlock *> &bm) {
983     return new X86FastISel(mf, vm, bm);
984   }
985 }