8a72f2618fb5ea20eaa05d7da89a85facf64d13d
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.h - X86 DAG Lowering Interface ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetOptions.h"
27 using namespace llvm;
28
29 // FIXME: temporary.
30 #include "llvm/Support/CommandLine.h"
31 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
32                                   cl::desc("Enable fastcc on X86"));
33
34 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
35   : TargetLowering(TM) {
36   Subtarget = &TM.getSubtarget<X86Subtarget>();
37   X86ScalarSSE = Subtarget->hasSSE2();
38
39   // Set up the TargetLowering object.
40
41   // X86 is weird, it always uses i8 for shift amounts and setcc results.
42   setShiftAmountType(MVT::i8);
43   setSetCCResultType(MVT::i8);
44   setSetCCResultContents(ZeroOrOneSetCCResult);
45   setSchedulingPreference(SchedulingForRegPressure);
46   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
47   setStackPointerRegisterToSaveRestore(X86::ESP);
48
49   // Set up the register classes.
50   addRegisterClass(MVT::i8, X86::R8RegisterClass);
51   addRegisterClass(MVT::i16, X86::R16RegisterClass);
52   addRegisterClass(MVT::i32, X86::R32RegisterClass);
53
54   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
55   // operation.
56   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
57   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
58   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
59
60   if (X86ScalarSSE)
61     // No SSE i64 SINT_TO_FP, so expand i32 UINT_TO_FP instead.
62     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Expand);
63   else
64     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
65
66   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
67   // this operation.
68   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
69   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
70
71   if (!X86ScalarSSE) {
72     // We can handle SINT_TO_FP and FP_TO_SINT from/TO i64 even though i64
73     // isn't legal.
74     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
75     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
76     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
77     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
78   }
79
80   // Handle FP_TO_UINT by promoting the destination to a larger signed
81   // conversion.
82   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
83   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
84   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
85
86   if (!X86ScalarSSE)
87     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
88
89   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
90   // this operation.
91   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
92   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
93   setOperationAction(ISD::FP_TO_SINT       , MVT::i16  , Promote);
94
95   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
96   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
97
98   if (X86DAGIsel) {
99     setOperationAction(ISD::BRCOND         , MVT::Other, Custom);
100   }
101   setOperationAction(ISD::BRCONDTWOWAY     , MVT::Other, Expand);
102   setOperationAction(ISD::BRTWOWAY_CC      , MVT::Other, Expand);
103   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
104   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
105   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
106   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
107   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
108   setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
109   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
110   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
111   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
112   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
113   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
114   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
115   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
116   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
117   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
118   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
119   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
120
121   if (!X86DAGIsel) {
122     setOperationAction(ISD::BSWAP          , MVT::i32  , Expand);
123     setOperationAction(ISD::ROTL           , MVT::i8   , Expand);
124     setOperationAction(ISD::ROTR           , MVT::i8   , Expand);
125     setOperationAction(ISD::ROTL           , MVT::i16  , Expand);
126     setOperationAction(ISD::ROTR           , MVT::i16  , Expand);
127     setOperationAction(ISD::ROTL           , MVT::i32  , Expand);
128     setOperationAction(ISD::ROTR           , MVT::i32  , Expand);
129   }
130   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
131
132   setOperationAction(ISD::READIO           , MVT::i1   , Expand);
133   setOperationAction(ISD::READIO           , MVT::i8   , Expand);
134   setOperationAction(ISD::READIO           , MVT::i16  , Expand);
135   setOperationAction(ISD::READIO           , MVT::i32  , Expand);
136   setOperationAction(ISD::WRITEIO          , MVT::i1   , Expand);
137   setOperationAction(ISD::WRITEIO          , MVT::i8   , Expand);
138   setOperationAction(ISD::WRITEIO          , MVT::i16  , Expand);
139   setOperationAction(ISD::WRITEIO          , MVT::i32  , Expand);
140
141   // These should be promoted to a larger select which is supported.
142   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
143   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
144   if (X86DAGIsel) {
145     // X86 wants to expand cmov itself.
146     setOperationAction(ISD::SELECT         , MVT::i16  , Custom);
147     setOperationAction(ISD::SELECT         , MVT::i32  , Custom);
148     setOperationAction(ISD::SELECT         , MVT::f32  , Custom);
149     setOperationAction(ISD::SELECT         , MVT::f64  , Custom);
150     setOperationAction(ISD::SETCC          , MVT::i8   , Custom);
151     setOperationAction(ISD::SETCC          , MVT::i16  , Custom);
152     setOperationAction(ISD::SETCC          , MVT::i32  , Custom);
153     setOperationAction(ISD::SETCC          , MVT::f32  , Custom);
154     setOperationAction(ISD::SETCC          , MVT::f64  , Custom);
155     // X86 ret instruction may pop stack.
156     setOperationAction(ISD::RET            , MVT::Other, Custom);
157     // Darwin ABI issue.
158     setOperationAction(ISD::GlobalAddress  , MVT::i32  , Custom);
159     // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
160     setOperationAction(ISD::ADD_PARTS      , MVT::i32  , Custom);
161     setOperationAction(ISD::SUB_PARTS      , MVT::i32  , Custom);
162     setOperationAction(ISD::SHL_PARTS      , MVT::i32  , Custom);
163     setOperationAction(ISD::SRA_PARTS      , MVT::i32  , Custom);
164     setOperationAction(ISD::SRL_PARTS      , MVT::i32  , Custom);
165     // X86 wants to expand memset / memcpy itself.
166     setOperationAction(ISD::MEMSET         , MVT::Other, Custom);
167     setOperationAction(ISD::MEMCPY         , MVT::Other, Custom);
168   }
169
170   // We don't have line number support yet.
171   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
172   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
173   setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
174
175   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
176   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
177   
178   // Use the default implementation.
179   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
180   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
181   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
182   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
183   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
184   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
185
186   if (X86ScalarSSE) {
187     // Set up the FP register classes.
188     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
189     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
190
191     // SSE has no load+extend ops
192     setOperationAction(ISD::EXTLOAD,  MVT::f32, Expand);
193     setOperationAction(ISD::ZEXTLOAD, MVT::f32, Expand);
194
195     // SSE has no i16 to fp conversion, only i32
196     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
197     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
198
199     // Expand FP_TO_UINT into a select.
200     // FIXME: We would like to use a Custom expander here eventually to do
201     // the optimal thing for SSE vs. the default expansion in the legalizer.
202     setOperationAction(ISD::FP_TO_UINT       , MVT::i32  , Expand);
203         
204     // We don't support sin/cos/sqrt/fmod
205     setOperationAction(ISD::FSIN , MVT::f64, Expand);
206     setOperationAction(ISD::FCOS , MVT::f64, Expand);
207     setOperationAction(ISD::FABS , MVT::f64, Expand);
208     setOperationAction(ISD::FNEG , MVT::f64, Expand);
209     setOperationAction(ISD::FREM , MVT::f64, Expand);
210     setOperationAction(ISD::FSIN , MVT::f32, Expand);
211     setOperationAction(ISD::FCOS , MVT::f32, Expand);
212     setOperationAction(ISD::FABS , MVT::f32, Expand);
213     setOperationAction(ISD::FNEG , MVT::f32, Expand);
214     setOperationAction(ISD::FREM , MVT::f32, Expand);
215
216     addLegalFPImmediate(+0.0); // xorps / xorpd
217   } else {
218     // Set up the FP register classes.
219     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
220
221     if (X86DAGIsel) {
222       setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
223       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
224     }
225
226     if (!UnsafeFPMath) {
227       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
228       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
229     }
230
231     addLegalFPImmediate(+0.0); // FLD0
232     addLegalFPImmediate(+1.0); // FLD1
233     addLegalFPImmediate(-0.0); // FLD0/FCHS
234     addLegalFPImmediate(-1.0); // FLD1/FCHS
235   }
236   computeRegisterProperties();
237
238   maxStoresPerMemSet = 8; // For %llvm.memset -> sequence of stores
239   maxStoresPerMemCpy = 8; // For %llvm.memcpy -> sequence of stores
240   maxStoresPerMemMove = 8; // For %llvm.memmove -> sequence of stores
241   allowUnalignedMemoryAccesses = true; // x86 supports it!
242 }
243
244 std::vector<SDOperand>
245 X86TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
246   if (F.getCallingConv() == CallingConv::Fast && EnableFastCC)
247     return LowerFastCCArguments(F, DAG);
248   return LowerCCCArguments(F, DAG);
249 }
250
251 std::pair<SDOperand, SDOperand>
252 X86TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
253                                bool isVarArg, unsigned CallingConv,
254                                bool isTailCall,
255                                SDOperand Callee, ArgListTy &Args,
256                                SelectionDAG &DAG) {
257   assert((!isVarArg || CallingConv == CallingConv::C) &&
258          "Only C takes varargs!");
259
260   // If the callee is a GlobalAddress node (quite common, every direct call is)
261   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
262   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
263     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
264   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
265     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
266
267   if (CallingConv == CallingConv::Fast && EnableFastCC)
268     return LowerFastCCCallTo(Chain, RetTy, isTailCall, Callee, Args, DAG);
269   return  LowerCCCCallTo(Chain, RetTy, isVarArg, isTailCall, Callee, Args, DAG);
270 }
271
272 //===----------------------------------------------------------------------===//
273 //                    C Calling Convention implementation
274 //===----------------------------------------------------------------------===//
275
276 std::vector<SDOperand>
277 X86TargetLowering::LowerCCCArguments(Function &F, SelectionDAG &DAG) {
278   std::vector<SDOperand> ArgValues;
279
280   MachineFunction &MF = DAG.getMachineFunction();
281   MachineFrameInfo *MFI = MF.getFrameInfo();
282
283   // Add DAG nodes to load the arguments...  On entry to a function on the X86,
284   // the stack frame looks like this:
285   //
286   // [ESP] -- return address
287   // [ESP + 4] -- first argument (leftmost lexically)
288   // [ESP + 8] -- second argument, if first argument is four bytes in size
289   //    ...
290   //
291   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
292   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
293     MVT::ValueType ObjectVT = getValueType(I->getType());
294     unsigned ArgIncrement = 4;
295     unsigned ObjSize;
296     switch (ObjectVT) {
297     default: assert(0 && "Unhandled argument type!");
298     case MVT::i1:
299     case MVT::i8:  ObjSize = 1;                break;
300     case MVT::i16: ObjSize = 2;                break;
301     case MVT::i32: ObjSize = 4;                break;
302     case MVT::i64: ObjSize = ArgIncrement = 8; break;
303     case MVT::f32: ObjSize = 4;                break;
304     case MVT::f64: ObjSize = ArgIncrement = 8; break;
305     }
306     // Create the frame index object for this incoming parameter...
307     int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
308
309     // Create the SelectionDAG nodes corresponding to a load from this parameter
310     SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
311
312     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
313     // dead loads.
314     SDOperand ArgValue;
315     if (!I->use_empty())
316       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
317                              DAG.getSrcValue(NULL));
318     else {
319       if (MVT::isInteger(ObjectVT))
320         ArgValue = DAG.getConstant(0, ObjectVT);
321       else
322         ArgValue = DAG.getConstantFP(0, ObjectVT);
323     }
324     ArgValues.push_back(ArgValue);
325
326     ArgOffset += ArgIncrement;   // Move on to the next argument...
327   }
328
329   // If the function takes variable number of arguments, make a frame index for
330   // the start of the first vararg value... for expansion of llvm.va_start.
331   if (F.isVarArg())
332     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
333   ReturnAddrIndex = 0;     // No return address slot generated yet.
334   BytesToPopOnReturn = 0;  // Callee pops nothing.
335   BytesCallerReserves = ArgOffset;
336
337   // Finally, inform the code generator which regs we return values in.
338   switch (getValueType(F.getReturnType())) {
339   default: assert(0 && "Unknown type!");
340   case MVT::isVoid: break;
341   case MVT::i1:
342   case MVT::i8:
343   case MVT::i16:
344   case MVT::i32:
345     MF.addLiveOut(X86::EAX);
346     break;
347   case MVT::i64:
348     MF.addLiveOut(X86::EAX);
349     MF.addLiveOut(X86::EDX);
350     break;
351   case MVT::f32:
352   case MVT::f64:
353     MF.addLiveOut(X86::ST0);
354     break;
355   }
356   return ArgValues;
357 }
358
359 std::pair<SDOperand, SDOperand>
360 X86TargetLowering::LowerCCCCallTo(SDOperand Chain, const Type *RetTy,
361                                   bool isVarArg, bool isTailCall,
362                                   SDOperand Callee, ArgListTy &Args,
363                                   SelectionDAG &DAG) {
364   // Count how many bytes are to be pushed on the stack.
365   unsigned NumBytes = 0;
366
367   if (Args.empty()) {
368     // Save zero bytes.
369     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
370                         DAG.getConstant(0, getPointerTy()));
371   } else {
372     for (unsigned i = 0, e = Args.size(); i != e; ++i)
373       switch (getValueType(Args[i].second)) {
374       default: assert(0 && "Unknown value type!");
375       case MVT::i1:
376       case MVT::i8:
377       case MVT::i16:
378       case MVT::i32:
379       case MVT::f32:
380         NumBytes += 4;
381         break;
382       case MVT::i64:
383       case MVT::f64:
384         NumBytes += 8;
385         break;
386       }
387
388     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
389                         DAG.getConstant(NumBytes, getPointerTy()));
390
391     // Arguments go on the stack in reverse order, as specified by the ABI.
392     unsigned ArgOffset = 0;
393     SDOperand StackPtr = DAG.getRegister(X86::ESP, MVT::i32);
394     std::vector<SDOperand> Stores;
395
396     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
397       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
398       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
399
400       switch (getValueType(Args[i].second)) {
401       default: assert(0 && "Unexpected ValueType for argument!");
402       case MVT::i1:
403       case MVT::i8:
404       case MVT::i16:
405         // Promote the integer to 32 bits.  If the input type is signed use a
406         // sign extend, otherwise use a zero extend.
407         if (Args[i].second->isSigned())
408           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
409         else
410           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
411
412         // FALL THROUGH
413       case MVT::i32:
414       case MVT::f32:
415         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
416                                      Args[i].first, PtrOff,
417                                      DAG.getSrcValue(NULL)));
418         ArgOffset += 4;
419         break;
420       case MVT::i64:
421       case MVT::f64:
422         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
423                                      Args[i].first, PtrOff,
424                                      DAG.getSrcValue(NULL)));
425         ArgOffset += 8;
426         break;
427       }
428     }
429     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
430   }
431
432   std::vector<MVT::ValueType> RetVals;
433   MVT::ValueType RetTyVT = getValueType(RetTy);
434   RetVals.push_back(MVT::Other);
435
436   // The result values produced have to be legal.  Promote the result.
437   switch (RetTyVT) {
438   case MVT::isVoid: break;
439   default:
440     RetVals.push_back(RetTyVT);
441     break;
442   case MVT::i1:
443   case MVT::i8:
444   case MVT::i16:
445     RetVals.push_back(MVT::i32);
446     break;
447   case MVT::f32:
448     if (X86ScalarSSE)
449       RetVals.push_back(MVT::f32);
450     else
451       RetVals.push_back(MVT::f64);
452     break;
453   case MVT::i64:
454     RetVals.push_back(MVT::i32);
455     RetVals.push_back(MVT::i32);
456     break;
457   }
458
459   if (X86DAGIsel) {
460     std::vector<MVT::ValueType> NodeTys;
461     NodeTys.push_back(MVT::Other);   // Returns a chain
462     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
463     std::vector<SDOperand> Ops;
464     Ops.push_back(Chain);
465     Ops.push_back(Callee);
466
467     // FIXME: Do not generate X86ISD::TAILCALL for now.
468     Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops);
469     SDOperand InFlag = Chain.getValue(1);
470
471     NodeTys.clear();
472     NodeTys.push_back(MVT::Other);   // Returns a chain
473     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
474     Ops.clear();
475     Ops.push_back(Chain);
476     Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
477     Ops.push_back(DAG.getConstant(0, getPointerTy()));
478     Ops.push_back(InFlag);
479     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
480     InFlag = Chain.getValue(1);
481     
482     SDOperand RetVal;
483     if (RetTyVT != MVT::isVoid) {
484       switch (RetTyVT) {
485       default: assert(0 && "Unknown value type to return!");
486       case MVT::i1:
487       case MVT::i8:
488         RetVal = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag);
489         Chain = RetVal.getValue(1);
490         if (RetTyVT == MVT::i1) 
491           RetVal = DAG.getNode(ISD::TRUNCATE, MVT::i1, RetVal);
492         break;
493       case MVT::i16:
494         RetVal = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
495         Chain = RetVal.getValue(1);
496         break;
497       case MVT::i32:
498         RetVal = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
499         Chain = RetVal.getValue(1);
500         break;
501       case MVT::i64: {
502         SDOperand Lo = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
503         SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), X86::EDX, MVT::i32, 
504                                           Lo.getValue(2));
505         RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
506         Chain = Hi.getValue(1);
507         break;
508       }
509       case MVT::f32:
510       case MVT::f64: {
511         std::vector<MVT::ValueType> Tys;
512         Tys.push_back(MVT::f64);
513         Tys.push_back(MVT::Other);
514         Tys.push_back(MVT::Flag);
515         std::vector<SDOperand> Ops;
516         Ops.push_back(Chain);
517         Ops.push_back(InFlag);
518         RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
519         Chain  = RetVal.getValue(1);
520         InFlag = RetVal.getValue(2);
521         if (X86ScalarSSE) {
522           // FIXME:Currently the FST is flagged to the FP_GET_RESULT. This
523           // shouldn't be necessary except for RFP cannot be live across
524           // multiple blocks. When stackifier is fixed, they can be uncoupled.
525           unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
526           MachineFunction &MF = DAG.getMachineFunction();
527           int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
528           SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
529           Tys.clear();
530           Tys.push_back(MVT::Other);
531           Ops.clear();
532           Ops.push_back(Chain);
533           Ops.push_back(RetVal);
534           Ops.push_back(StackSlot);
535           Ops.push_back(DAG.getValueType(RetTyVT));
536           Ops.push_back(InFlag);
537           Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
538           RetVal = DAG.getLoad(RetTyVT, Chain, StackSlot,
539                                DAG.getSrcValue(NULL));
540           Chain = RetVal.getValue(1);
541         }
542
543         if (RetTyVT == MVT::f32 && !X86ScalarSSE)
544           // FIXME: we would really like to remember that this FP_ROUND
545           // operation is okay to eliminate if we allow excess FP precision.
546           RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
547         break;
548       }
549       }
550     }
551
552     return std::make_pair(RetVal, Chain);
553   } else {
554     std::vector<SDOperand> Ops;
555     Ops.push_back(Chain);
556     Ops.push_back(Callee);
557     Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
558     Ops.push_back(DAG.getConstant(0, getPointerTy()));
559
560     SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
561                                     RetVals, Ops);
562
563     SDOperand ResultVal;
564     switch (RetTyVT) {
565     case MVT::isVoid: break;
566     default:
567       ResultVal = TheCall.getValue(1);
568       break;
569     case MVT::i1:
570     case MVT::i8:
571     case MVT::i16:
572       ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
573       break;
574     case MVT::f32:
575       // FIXME: we would really like to remember that this FP_ROUND operation is
576       // okay to eliminate if we allow excess FP precision.
577       ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
578       break;
579     case MVT::i64:
580       ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
581                               TheCall.getValue(2));
582       break;
583     }
584
585     Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
586     return std::make_pair(ResultVal, Chain);
587   }
588 }
589
590 //===----------------------------------------------------------------------===//
591 //                    Fast Calling Convention implementation
592 //===----------------------------------------------------------------------===//
593 //
594 // The X86 'fast' calling convention passes up to two integer arguments in
595 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
596 // and requires that the callee pop its arguments off the stack (allowing proper
597 // tail calls), and has the same return value conventions as C calling convs.
598 //
599 // This calling convention always arranges for the callee pop value to be 8n+4
600 // bytes, which is needed for tail recursion elimination and stack alignment
601 // reasons.
602 //
603 // Note that this can be enhanced in the future to pass fp vals in registers
604 // (when we have a global fp allocator) and do other tricks.
605 //
606
607 /// AddLiveIn - This helper function adds the specified physical register to the
608 /// MachineFunction as a live in value.  It also creates a corresponding virtual
609 /// register for it.
610 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
611                           TargetRegisterClass *RC) {
612   assert(RC->contains(PReg) && "Not the correct regclass!");
613   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
614   MF.addLiveIn(PReg, VReg);
615   return VReg;
616 }
617
618
619 std::vector<SDOperand>
620 X86TargetLowering::LowerFastCCArguments(Function &F, SelectionDAG &DAG) {
621   std::vector<SDOperand> ArgValues;
622
623   MachineFunction &MF = DAG.getMachineFunction();
624   MachineFrameInfo *MFI = MF.getFrameInfo();
625
626   // Add DAG nodes to load the arguments...  On entry to a function the stack
627   // frame looks like this:
628   //
629   // [ESP] -- return address
630   // [ESP + 4] -- first nonreg argument (leftmost lexically)
631   // [ESP + 8] -- second nonreg argument, if first argument is 4 bytes in size
632   //    ...
633   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
634
635   // Keep track of the number of integer regs passed so far.  This can be either
636   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
637   // used).
638   unsigned NumIntRegs = 0;
639
640   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
641     MVT::ValueType ObjectVT = getValueType(I->getType());
642     unsigned ArgIncrement = 4;
643     unsigned ObjSize = 0;
644     SDOperand ArgValue;
645
646     switch (ObjectVT) {
647     default: assert(0 && "Unhandled argument type!");
648     case MVT::i1:
649     case MVT::i8:
650       if (NumIntRegs < 2) {
651         if (!I->use_empty()) {
652           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
653                                     X86::R8RegisterClass);
654           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i8);
655           DAG.setRoot(ArgValue.getValue(1));
656           if (ObjectVT == MVT::i1)
657             // FIXME: Should insert a assertzext here.
658             ArgValue = DAG.getNode(ISD::TRUNCATE, MVT::i1, ArgValue);
659         }
660         ++NumIntRegs;
661         break;
662       }
663
664       ObjSize = 1;
665       break;
666     case MVT::i16:
667       if (NumIntRegs < 2) {
668         if (!I->use_empty()) {
669           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
670                                     X86::R16RegisterClass);
671           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i16);
672           DAG.setRoot(ArgValue.getValue(1));
673         }
674         ++NumIntRegs;
675         break;
676       }
677       ObjSize = 2;
678       break;
679     case MVT::i32:
680       if (NumIntRegs < 2) {
681         if (!I->use_empty()) {
682           unsigned VReg = AddLiveIn(MF,NumIntRegs ? X86::EDX : X86::EAX,
683                                     X86::R32RegisterClass);
684           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
685           DAG.setRoot(ArgValue.getValue(1));
686         }
687         ++NumIntRegs;
688         break;
689       }
690       ObjSize = 4;
691       break;
692     case MVT::i64:
693       if (NumIntRegs == 0) {
694         if (!I->use_empty()) {
695           unsigned BotReg = AddLiveIn(MF, X86::EAX, X86::R32RegisterClass);
696           unsigned TopReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
697
698           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
699           SDOperand Hi  = DAG.getCopyFromReg(Low.getValue(1), TopReg, MVT::i32);
700           DAG.setRoot(Hi.getValue(1));
701
702           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
703         }
704         NumIntRegs = 2;
705         break;
706       } else if (NumIntRegs == 1) {
707         if (!I->use_empty()) {
708           unsigned BotReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
709           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
710           DAG.setRoot(Low.getValue(1));
711
712           // Load the high part from memory.
713           // Create the frame index object for this incoming parameter...
714           int FI = MFI->CreateFixedObject(4, ArgOffset);
715           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
716           SDOperand Hi = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
717                                      DAG.getSrcValue(NULL));
718           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
719         }
720         ArgOffset += 4;
721         NumIntRegs = 2;
722         break;
723       }
724       ObjSize = ArgIncrement = 8;
725       break;
726     case MVT::f32: ObjSize = 4;                break;
727     case MVT::f64: ObjSize = ArgIncrement = 8; break;
728     }
729
730     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
731     // dead loads.
732     if (ObjSize && !I->use_empty()) {
733       // Create the frame index object for this incoming parameter...
734       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
735
736       // Create the SelectionDAG nodes corresponding to a load from this
737       // parameter.
738       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
739
740       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
741                              DAG.getSrcValue(NULL));
742     } else if (ArgValue.Val == 0) {
743       if (MVT::isInteger(ObjectVT))
744         ArgValue = DAG.getConstant(0, ObjectVT);
745       else
746         ArgValue = DAG.getConstantFP(0, ObjectVT);
747     }
748     ArgValues.push_back(ArgValue);
749
750     if (ObjSize)
751       ArgOffset += ArgIncrement;   // Move on to the next argument.
752   }
753
754   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
755   // arguments and the arguments after the retaddr has been pushed are aligned.
756   if ((ArgOffset & 7) == 0)
757     ArgOffset += 4;
758
759   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
760   ReturnAddrIndex = 0;             // No return address slot generated yet.
761   BytesToPopOnReturn = ArgOffset;  // Callee pops all stack arguments.
762   BytesCallerReserves = 0;
763
764   // Finally, inform the code generator which regs we return values in.
765   switch (getValueType(F.getReturnType())) {
766   default: assert(0 && "Unknown type!");
767   case MVT::isVoid: break;
768   case MVT::i1:
769   case MVT::i8:
770   case MVT::i16:
771   case MVT::i32:
772     MF.addLiveOut(X86::EAX);
773     break;
774   case MVT::i64:
775     MF.addLiveOut(X86::EAX);
776     MF.addLiveOut(X86::EDX);
777     break;
778   case MVT::f32:
779   case MVT::f64:
780     MF.addLiveOut(X86::ST0);
781     break;
782   }
783   return ArgValues;
784 }
785
786 std::pair<SDOperand, SDOperand>
787 X86TargetLowering::LowerFastCCCallTo(SDOperand Chain, const Type *RetTy,
788                                      bool isTailCall, SDOperand Callee,
789                                      ArgListTy &Args, SelectionDAG &DAG) {
790   // Count how many bytes are to be pushed on the stack.
791   unsigned NumBytes = 0;
792
793   // Keep track of the number of integer regs passed so far.  This can be either
794   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
795   // used).
796   unsigned NumIntRegs = 0;
797
798   for (unsigned i = 0, e = Args.size(); i != e; ++i)
799     switch (getValueType(Args[i].second)) {
800     default: assert(0 && "Unknown value type!");
801     case MVT::i1:
802     case MVT::i8:
803     case MVT::i16:
804     case MVT::i32:
805       if (NumIntRegs < 2) {
806         ++NumIntRegs;
807         break;
808       }
809       // fall through
810     case MVT::f32:
811       NumBytes += 4;
812       break;
813     case MVT::i64:
814       if (NumIntRegs == 0) {
815         NumIntRegs = 2;
816         break;
817       } else if (NumIntRegs == 1) {
818         NumIntRegs = 2;
819         NumBytes += 4;
820         break;
821       }
822
823       // fall through
824     case MVT::f64:
825       NumBytes += 8;
826       break;
827     }
828
829   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
830   // arguments and the arguments after the retaddr has been pushed are aligned.
831   if ((NumBytes & 7) == 0)
832     NumBytes += 4;
833
834   Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
835                       DAG.getConstant(NumBytes, getPointerTy()));
836
837   // Arguments go on the stack in reverse order, as specified by the ABI.
838   unsigned ArgOffset = 0;
839   SDOperand StackPtr = DAG.getRegister(X86::ESP, MVT::i32);
840   NumIntRegs = 0;
841   std::vector<SDOperand> Stores;
842   std::vector<SDOperand> RegValuesToPass;
843   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
844     switch (getValueType(Args[i].second)) {
845     default: assert(0 && "Unexpected ValueType for argument!");
846     case MVT::i1:
847       Args[i].first = DAG.getNode(ISD::ANY_EXTEND, MVT::i8, Args[i].first);
848       // Fall through.
849     case MVT::i8:
850     case MVT::i16:
851     case MVT::i32:
852       if (NumIntRegs < 2) {
853         RegValuesToPass.push_back(Args[i].first);
854         ++NumIntRegs;
855         break;
856       }
857       // Fall through
858     case MVT::f32: {
859       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
860       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
861       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
862                                    Args[i].first, PtrOff,
863                                    DAG.getSrcValue(NULL)));
864       ArgOffset += 4;
865       break;
866     }
867     case MVT::i64:
868       if (NumIntRegs < 2) {    // Can pass part of it in regs?
869         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
870                                    Args[i].first, DAG.getConstant(1, MVT::i32));
871         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
872                                    Args[i].first, DAG.getConstant(0, MVT::i32));
873         RegValuesToPass.push_back(Lo);
874         ++NumIntRegs;
875         if (NumIntRegs < 2) {   // Pass both parts in regs?
876           RegValuesToPass.push_back(Hi);
877           ++NumIntRegs;
878         } else {
879           // Pass the high part in memory.
880           SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
881           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
882           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
883                                        Hi, PtrOff, DAG.getSrcValue(NULL)));
884           ArgOffset += 4;
885         }
886         break;
887       }
888       // Fall through
889     case MVT::f64:
890       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
891       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
892       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
893                                    Args[i].first, PtrOff,
894                                    DAG.getSrcValue(NULL)));
895       ArgOffset += 8;
896       break;
897     }
898   }
899   if (!Stores.empty())
900     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
901
902   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
903   // arguments and the arguments after the retaddr has been pushed are aligned.
904   if ((ArgOffset & 7) == 0)
905     ArgOffset += 4;
906
907   std::vector<MVT::ValueType> RetVals;
908   MVT::ValueType RetTyVT = getValueType(RetTy);
909
910   RetVals.push_back(MVT::Other);
911
912   // The result values produced have to be legal.  Promote the result.
913   switch (RetTyVT) {
914   case MVT::isVoid: break;
915   default:
916     RetVals.push_back(RetTyVT);
917     break;
918   case MVT::i1:
919   case MVT::i8:
920   case MVT::i16:
921     RetVals.push_back(MVT::i32);
922     break;
923   case MVT::f32:
924     if (X86ScalarSSE)
925       RetVals.push_back(MVT::f32);
926     else
927       RetVals.push_back(MVT::f64);
928     break;
929   case MVT::i64:
930     RetVals.push_back(MVT::i32);
931     RetVals.push_back(MVT::i32);
932     break;
933   }
934
935   if (X86DAGIsel) {
936     // Build a sequence of copy-to-reg nodes chained together with token chain
937     // and flag operands which copy the outgoing args into registers.
938     SDOperand InFlag;
939     for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
940       unsigned CCReg;
941       SDOperand RegToPass = RegValuesToPass[i];
942       switch (RegToPass.getValueType()) {
943       default: assert(0 && "Bad thing to pass in regs");
944       case MVT::i8:
945         CCReg = (i == 0) ? X86::AL  : X86::DL;
946         break;
947       case MVT::i16:
948         CCReg = (i == 0) ? X86::AX  : X86::DX;
949         break;
950       case MVT::i32:
951         CCReg = (i == 0) ? X86::EAX : X86::EDX;
952         break;
953       }
954
955       Chain = DAG.getCopyToReg(Chain, CCReg, RegToPass, InFlag);
956       InFlag = Chain.getValue(1);
957     }
958
959     std::vector<MVT::ValueType> NodeTys;
960     NodeTys.push_back(MVT::Other);   // Returns a chain
961     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
962     std::vector<SDOperand> Ops;
963     Ops.push_back(Chain);
964     Ops.push_back(Callee);
965     if (InFlag.Val)
966       Ops.push_back(InFlag);
967
968     // FIXME: Do not generate X86ISD::TAILCALL for now.
969     Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops);
970     InFlag = Chain.getValue(1);
971
972     NodeTys.clear();
973     NodeTys.push_back(MVT::Other);   // Returns a chain
974     NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
975     Ops.clear();
976     Ops.push_back(Chain);
977     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
978     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
979     Ops.push_back(InFlag);
980     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
981     InFlag = Chain.getValue(1);
982     
983     SDOperand RetVal;
984     if (RetTyVT != MVT::isVoid) {
985       switch (RetTyVT) {
986       default: assert(0 && "Unknown value type to return!");
987       case MVT::i1:
988       case MVT::i8:
989         RetVal = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag);
990         Chain = RetVal.getValue(1);
991         if (RetTyVT == MVT::i1) 
992           RetVal = DAG.getNode(ISD::TRUNCATE, MVT::i1, RetVal);
993         break;
994       case MVT::i16:
995         RetVal = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
996         Chain = RetVal.getValue(1);
997         break;
998       case MVT::i32:
999         RetVal = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
1000         Chain = RetVal.getValue(1);
1001         break;
1002       case MVT::i64: {
1003         SDOperand Lo = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
1004         SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), X86::EDX, MVT::i32, 
1005                                           Lo.getValue(2));
1006         RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
1007         Chain = Hi.getValue(1);
1008         break;
1009       }
1010       case MVT::f32:
1011       case MVT::f64: {
1012         std::vector<MVT::ValueType> Tys;
1013         Tys.push_back(MVT::f64);
1014         Tys.push_back(MVT::Other);
1015         Tys.push_back(MVT::Flag);
1016         std::vector<SDOperand> Ops;
1017         Ops.push_back(Chain);
1018         Ops.push_back(InFlag);
1019         RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
1020         Chain  = RetVal.getValue(1);
1021         InFlag = RetVal.getValue(2);
1022         if (X86ScalarSSE) {
1023           // FIXME:Currently the FST is flagged to the FP_GET_RESULT. This
1024           // shouldn't be necessary except for RFP cannot be live across
1025           // multiple blocks. When stackifier is fixed, they can be uncoupled.
1026           unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
1027           MachineFunction &MF = DAG.getMachineFunction();
1028           int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
1029           SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1030           Tys.clear();
1031           Tys.push_back(MVT::Other);
1032           Ops.clear();
1033           Ops.push_back(Chain);
1034           Ops.push_back(RetVal);
1035           Ops.push_back(StackSlot);
1036           Ops.push_back(DAG.getValueType(RetTyVT));
1037           Ops.push_back(InFlag);
1038           Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1039           RetVal = DAG.getLoad(RetTyVT, Chain, StackSlot,
1040                                DAG.getSrcValue(NULL));
1041           Chain = RetVal.getValue(1);
1042         }
1043
1044         if (RetTyVT == MVT::f32 && !X86ScalarSSE)
1045           // FIXME: we would really like to remember that this FP_ROUND
1046           // operation is okay to eliminate if we allow excess FP precision.
1047           RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
1048         break;
1049       }
1050       }
1051     }
1052
1053     return std::make_pair(RetVal, Chain);
1054   } else {
1055     std::vector<SDOperand> Ops;
1056     Ops.push_back(Chain);
1057     Ops.push_back(Callee);
1058     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
1059     // Callee pops all arg values on the stack.
1060     Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
1061
1062     // Pass register arguments as needed.
1063     Ops.insert(Ops.end(), RegValuesToPass.begin(), RegValuesToPass.end());
1064
1065     SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1066                                     RetVals, Ops);
1067     Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
1068
1069     SDOperand ResultVal;
1070     switch (RetTyVT) {
1071     case MVT::isVoid: break;
1072     default:
1073       ResultVal = TheCall.getValue(1);
1074       break;
1075     case MVT::i1:
1076     case MVT::i8:
1077     case MVT::i16:
1078       ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
1079       break;
1080     case MVT::f32:
1081       // FIXME: we would really like to remember that this FP_ROUND operation is
1082       // okay to eliminate if we allow excess FP precision.
1083       ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
1084       break;
1085     case MVT::i64:
1086       ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
1087                               TheCall.getValue(2));
1088       break;
1089     }
1090
1091     return std::make_pair(ResultVal, Chain);
1092   }
1093 }
1094
1095 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1096   if (ReturnAddrIndex == 0) {
1097     // Set up a frame object for the return address.
1098     MachineFunction &MF = DAG.getMachineFunction();
1099     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1100   }
1101
1102   return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
1103 }
1104
1105
1106
1107 std::pair<SDOperand, SDOperand> X86TargetLowering::
1108 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
1109                         SelectionDAG &DAG) {
1110   SDOperand Result;
1111   if (Depth)        // Depths > 0 not supported yet!
1112     Result = DAG.getConstant(0, getPointerTy());
1113   else {
1114     SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
1115     if (!isFrameAddress)
1116       // Just load the return address
1117       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
1118                            DAG.getSrcValue(NULL));
1119     else
1120       Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
1121                            DAG.getConstant(4, MVT::i32));
1122   }
1123   return std::make_pair(Result, Chain);
1124 }
1125
1126 /// getCondBrOpcodeForX86CC - Returns the X86 conditional branch opcode
1127 /// which corresponds to the condition code.
1128 static unsigned getCondBrOpcodeForX86CC(unsigned X86CC) {
1129   switch (X86CC) {
1130   default: assert(0 && "Unknown X86 conditional code!");
1131   case X86ISD::COND_A:  return X86::JA;
1132   case X86ISD::COND_AE: return X86::JAE;
1133   case X86ISD::COND_B:  return X86::JB;
1134   case X86ISD::COND_BE: return X86::JBE;
1135   case X86ISD::COND_E:  return X86::JE;
1136   case X86ISD::COND_G:  return X86::JG;
1137   case X86ISD::COND_GE: return X86::JGE;
1138   case X86ISD::COND_L:  return X86::JL;
1139   case X86ISD::COND_LE: return X86::JLE;
1140   case X86ISD::COND_NE: return X86::JNE;
1141   case X86ISD::COND_NO: return X86::JNO;
1142   case X86ISD::COND_NP: return X86::JNP;
1143   case X86ISD::COND_NS: return X86::JNS;
1144   case X86ISD::COND_O:  return X86::JO;
1145   case X86ISD::COND_P:  return X86::JP;
1146   case X86ISD::COND_S:  return X86::JS;
1147   }
1148 }
1149
1150 /// getX86CC - do a one to one translation of a ISD::CondCode to the X86
1151 /// specific condition code. It returns a X86ISD::COND_INVALID if it cannot
1152 /// do a direct translation.
1153 static unsigned getX86CC(SDOperand CC, bool isFP) {
1154   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
1155   unsigned X86CC = X86ISD::COND_INVALID;
1156   if (!isFP) {
1157     switch (SetCCOpcode) {
1158     default: break;
1159     case ISD::SETEQ:  X86CC = X86ISD::COND_E;  break;
1160     case ISD::SETGT:  X86CC = X86ISD::COND_G;  break;
1161     case ISD::SETGE:  X86CC = X86ISD::COND_GE; break;
1162     case ISD::SETLT:  X86CC = X86ISD::COND_L;  break;
1163     case ISD::SETLE:  X86CC = X86ISD::COND_LE; break;
1164     case ISD::SETNE:  X86CC = X86ISD::COND_NE; break;
1165     case ISD::SETULT: X86CC = X86ISD::COND_B;  break;
1166     case ISD::SETUGT: X86CC = X86ISD::COND_A;  break;
1167     case ISD::SETULE: X86CC = X86ISD::COND_BE; break;
1168     case ISD::SETUGE: X86CC = X86ISD::COND_AE; break;
1169     }
1170   } else {
1171     // On a floating point condition, the flags are set as follows:
1172     // ZF  PF  CF   op
1173     //  0 | 0 | 0 | X > Y
1174     //  0 | 0 | 1 | X < Y
1175     //  1 | 0 | 0 | X == Y
1176     //  1 | 1 | 1 | unordered
1177     switch (SetCCOpcode) {
1178     default: break;
1179     case ISD::SETUEQ:
1180     case ISD::SETEQ: X86CC = X86ISD::COND_E;  break;
1181     case ISD::SETOGT:
1182     case ISD::SETGT: X86CC = X86ISD::COND_A;  break;
1183     case ISD::SETOGE:
1184     case ISD::SETGE: X86CC = X86ISD::COND_AE; break;
1185     case ISD::SETULT:
1186     case ISD::SETLT: X86CC = X86ISD::COND_B;  break;
1187     case ISD::SETULE:
1188     case ISD::SETLE: X86CC = X86ISD::COND_BE; break;
1189     case ISD::SETONE:
1190     case ISD::SETNE: X86CC = X86ISD::COND_NE; break;
1191     case ISD::SETUO: X86CC = X86ISD::COND_P;  break;
1192     case ISD::SETO:  X86CC = X86ISD::COND_NP; break;
1193     }
1194   }
1195   return X86CC;
1196 }
1197
1198 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1199 /// code. Current x86 isa includes the following FP cmov instructions:
1200 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1201 static bool hasFPCMov(unsigned X86CC) {
1202   switch (X86CC) {
1203   default:
1204     return false;
1205   case X86ISD::COND_B:
1206   case X86ISD::COND_BE:
1207   case X86ISD::COND_E:
1208   case X86ISD::COND_P:
1209   case X86ISD::COND_A:
1210   case X86ISD::COND_AE:
1211   case X86ISD::COND_NE:
1212   case X86ISD::COND_NP:
1213     return true;
1214   }
1215 }
1216
1217 MachineBasicBlock *
1218 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1219                                            MachineBasicBlock *BB) {
1220   switch (MI->getOpcode()) {
1221   default: assert(false && "Unexpected instr type to insert");
1222   case X86::CMOV_FR32:
1223   case X86::CMOV_FR64: {
1224     // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1225     // control-flow pattern.  The incoming instruction knows the destination vreg
1226     // to set, the condition code register to branch on, the true/false values to
1227     // select between, and a branch opcode to use.
1228     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1229     ilist<MachineBasicBlock>::iterator It = BB;
1230     ++It;
1231   
1232     //  thisMBB:
1233     //  ...
1234     //   TrueVal = ...
1235     //   cmpTY ccX, r1, r2
1236     //   bCC copy1MBB
1237     //   fallthrough --> copy0MBB
1238     MachineBasicBlock *thisMBB = BB;
1239     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1240     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1241     unsigned Opc = getCondBrOpcodeForX86CC(MI->getOperand(3).getImmedValue());
1242     BuildMI(BB, Opc, 1).addMBB(sinkMBB);
1243     MachineFunction *F = BB->getParent();
1244     F->getBasicBlockList().insert(It, copy0MBB);
1245     F->getBasicBlockList().insert(It, sinkMBB);
1246     // Update machine-CFG edges
1247     BB->addSuccessor(copy0MBB);
1248     BB->addSuccessor(sinkMBB);
1249   
1250     //  copy0MBB:
1251     //   %FalseValue = ...
1252     //   # fallthrough to sinkMBB
1253     BB = copy0MBB;
1254   
1255     // Update machine-CFG edges
1256     BB->addSuccessor(sinkMBB);
1257   
1258     //  sinkMBB:
1259     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1260     //  ...
1261     BB = sinkMBB;
1262     BuildMI(BB, X86::PHI, 4, MI->getOperand(0).getReg())
1263       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1264       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1265
1266     delete MI;   // The pseudo instruction is gone now.
1267     return BB;
1268   }
1269
1270   case X86::FP_TO_INT16_IN_MEM:
1271   case X86::FP_TO_INT32_IN_MEM:
1272   case X86::FP_TO_INT64_IN_MEM: {
1273     // Change the floating point control register to use "round towards zero"
1274     // mode when truncating to an integer value.
1275     MachineFunction *F = BB->getParent();
1276     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1277     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1278
1279     // Load the old value of the high byte of the control word...
1280     unsigned OldCW =
1281       F->getSSARegMap()->createVirtualRegister(X86::R16RegisterClass);
1282     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
1283
1284     // Set the high part to be round to zero...
1285     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
1286
1287     // Reload the modified control word now...
1288     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1289
1290     // Restore the memory image of control word to original value
1291     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
1292
1293     // Get the X86 opcode to use.
1294     unsigned Opc;
1295     switch (MI->getOpcode()) {
1296     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
1297     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
1298     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
1299     }
1300
1301     X86AddressMode AM;
1302     MachineOperand &Op = MI->getOperand(0);
1303     if (Op.isRegister()) {
1304       AM.BaseType = X86AddressMode::RegBase;
1305       AM.Base.Reg = Op.getReg();
1306     } else {
1307       AM.BaseType = X86AddressMode::FrameIndexBase;
1308       AM.Base.FrameIndex = Op.getFrameIndex();
1309     }
1310     Op = MI->getOperand(1);
1311     if (Op.isImmediate())
1312       AM.Scale = Op.getImmedValue();
1313     Op = MI->getOperand(2);
1314     if (Op.isImmediate())
1315       AM.IndexReg = Op.getImmedValue();
1316     Op = MI->getOperand(3);
1317     if (Op.isGlobalAddress()) {
1318       AM.GV = Op.getGlobal();
1319     } else {
1320       AM.Disp = Op.getImmedValue();
1321     }
1322     addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(MI->getOperand(4).getReg());
1323
1324     // Reload the original control word now.
1325     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1326
1327     delete MI;   // The pseudo instruction is gone now.
1328     return BB;
1329   }
1330   }
1331 }
1332
1333
1334 //===----------------------------------------------------------------------===//
1335 //                           X86 Custom Lowering Hooks
1336 //===----------------------------------------------------------------------===//
1337
1338 /// LowerOperation - Provide custom lowering hooks for some operations.
1339 ///
1340 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1341   switch (Op.getOpcode()) {
1342   default: assert(0 && "Should not custom lower this!");
1343   case ISD::ADD_PARTS:
1344   case ISD::SUB_PARTS: {
1345     assert(Op.getNumOperands() == 4 && Op.getValueType() == MVT::i32 &&
1346            "Not an i64 add/sub!");
1347     bool isAdd = Op.getOpcode() == ISD::ADD_PARTS;
1348     std::vector<MVT::ValueType> Tys;
1349     Tys.push_back(MVT::i32);
1350     Tys.push_back(MVT::Flag);
1351     std::vector<SDOperand> Ops;
1352     Ops.push_back(Op.getOperand(0));
1353     Ops.push_back(Op.getOperand(2));
1354     SDOperand Lo = DAG.getNode(isAdd ? X86ISD::ADD_FLAG : X86ISD::SUB_FLAG,
1355                                Tys, Ops);
1356     SDOperand Hi = DAG.getNode(isAdd ? X86ISD::ADC : X86ISD::SBB, MVT::i32,
1357                                Op.getOperand(1), Op.getOperand(3),
1358                                Lo.getValue(1));
1359     Tys.clear();
1360     Tys.push_back(MVT::i32);
1361     Tys.push_back(MVT::i32);
1362     Ops.clear();
1363     Ops.push_back(Lo);
1364     Ops.push_back(Hi);
1365     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1366   }
1367   case ISD::SHL_PARTS:
1368   case ISD::SRA_PARTS:
1369   case ISD::SRL_PARTS: {
1370     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
1371            "Not an i64 shift!");
1372     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
1373     SDOperand ShOpLo = Op.getOperand(0);
1374     SDOperand ShOpHi = Op.getOperand(1);
1375     SDOperand ShAmt  = Op.getOperand(2);
1376     SDOperand Tmp1 = isSRA ? DAG.getNode(ISD::SRA, MVT::i32, ShOpHi,
1377                                          DAG.getConstant(31, MVT::i8))
1378                            : DAG.getConstant(0, MVT::i32);
1379
1380     SDOperand Tmp2, Tmp3;
1381     if (Op.getOpcode() == ISD::SHL_PARTS) {
1382       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
1383       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
1384     } else {
1385       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
1386       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
1387     }
1388
1389     SDOperand InFlag = DAG.getNode(X86ISD::TEST, MVT::Flag,
1390                                    ShAmt, DAG.getConstant(32, MVT::i8));
1391
1392     SDOperand Hi, Lo;
1393     SDOperand CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1394
1395     std::vector<MVT::ValueType> Tys;
1396     Tys.push_back(MVT::i32);
1397     Tys.push_back(MVT::Flag);
1398     std::vector<SDOperand> Ops;
1399     if (Op.getOpcode() == ISD::SHL_PARTS) {
1400       Ops.push_back(Tmp2);
1401       Ops.push_back(Tmp3);
1402       Ops.push_back(CC);
1403       Ops.push_back(InFlag);
1404       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1405       InFlag = Hi.getValue(1);
1406
1407       Ops.clear();
1408       Ops.push_back(Tmp3);
1409       Ops.push_back(Tmp1);
1410       Ops.push_back(CC);
1411       Ops.push_back(InFlag);
1412       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1413     } else {
1414       Ops.push_back(Tmp2);
1415       Ops.push_back(Tmp3);
1416       Ops.push_back(CC);
1417       Ops.push_back(InFlag);
1418       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1419       InFlag = Lo.getValue(1);
1420
1421       Ops.clear();
1422       Ops.push_back(Tmp3);
1423       Ops.push_back(Tmp1);
1424       Ops.push_back(CC);
1425       Ops.push_back(InFlag);
1426       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1427     }
1428
1429     Tys.clear();
1430     Tys.push_back(MVT::i32);
1431     Tys.push_back(MVT::i32);
1432     Ops.clear();
1433     Ops.push_back(Lo);
1434     Ops.push_back(Hi);
1435     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1436   }
1437   case ISD::SINT_TO_FP: {
1438     assert(Op.getValueType() == MVT::f64 &&
1439            Op.getOperand(0).getValueType() <= MVT::i64 &&
1440            Op.getOperand(0).getValueType() >= MVT::i16 &&
1441            "Unknown SINT_TO_FP to lower!");
1442
1443     SDOperand Result;
1444     MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
1445     unsigned Size = MVT::getSizeInBits(SrcVT)/8;
1446     MachineFunction &MF = DAG.getMachineFunction();
1447     int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
1448     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1449     SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other,
1450                                   DAG.getEntryNode(), Op.getOperand(0),
1451                                   StackSlot, DAG.getSrcValue(NULL));
1452
1453     // Build the FILD
1454     std::vector<MVT::ValueType> Tys;
1455     Tys.push_back(MVT::f64);
1456     Tys.push_back(MVT::Flag);
1457     std::vector<SDOperand> Ops;
1458     Ops.push_back(Chain);
1459     Ops.push_back(StackSlot);
1460     Ops.push_back(DAG.getValueType(SrcVT));
1461     Result = DAG.getNode(X86ISD::FILD, Tys, Ops);
1462     return Result;
1463   }
1464   case ISD::FP_TO_SINT: {
1465     assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
1466            Op.getOperand(0).getValueType() == MVT::f64 &&
1467            "Unknown FP_TO_SINT to lower!");
1468     // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
1469     // stack slot.
1470     MachineFunction &MF = DAG.getMachineFunction();
1471     unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
1472     int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1473     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1474
1475     unsigned Opc;
1476     switch (Op.getValueType()) {
1477     default: assert(0 && "Invalid FP_TO_SINT to lower!");
1478     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
1479     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
1480     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
1481     }
1482
1483     // Build the FP_TO_INT*_IN_MEM
1484     std::vector<SDOperand> Ops;
1485     Ops.push_back(DAG.getEntryNode());
1486     Ops.push_back(Op.getOperand(0));
1487     Ops.push_back(StackSlot);
1488     SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
1489
1490     // Load the result.
1491     return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
1492                        DAG.getSrcValue(NULL));
1493   }
1494   case ISD::READCYCLECOUNTER: {
1495     std::vector<MVT::ValueType> Tys;
1496     Tys.push_back(MVT::Other);
1497     Tys.push_back(MVT::Flag);
1498     std::vector<SDOperand> Ops;
1499     Ops.push_back(Op.getOperand(0));
1500     SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, Ops);
1501     Ops.clear();
1502     Ops.push_back(DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1)));
1503     Ops.push_back(DAG.getCopyFromReg(Ops[0].getValue(1), X86::EDX, 
1504                                      MVT::i32, Ops[0].getValue(2)));
1505     Ops.push_back(Ops[1].getValue(1));
1506     Tys[0] = Tys[1] = MVT::i32;
1507     Tys.push_back(MVT::Other);
1508     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1509   }
1510   case ISD::SETCC: {
1511     assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
1512     SDOperand CC   = Op.getOperand(2);
1513     SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1514                                  Op.getOperand(0), Op.getOperand(1));
1515     ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
1516     bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
1517     unsigned X86CC = getX86CC(CC, isFP);
1518     if (X86CC != X86ISD::COND_INVALID) {
1519       return DAG.getNode(X86ISD::SETCC, MVT::i8, 
1520                          DAG.getConstant(X86CC, MVT::i8), Cond);
1521     } else {
1522       assert(isFP && "Illegal integer SetCC!");
1523
1524       std::vector<MVT::ValueType> Tys;
1525       std::vector<SDOperand> Ops;
1526       switch (SetCCOpcode) {
1527       default: assert(false && "Illegal floating point SetCC!");
1528       case ISD::SETOEQ: {  // !PF & ZF
1529         Tys.push_back(MVT::i8);
1530         Tys.push_back(MVT::Flag);
1531         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
1532         Ops.push_back(Cond);
1533         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1534         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1535                                      DAG.getConstant(X86ISD::COND_E, MVT::i8),
1536                                      Tmp1.getValue(1));
1537         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
1538       }
1539       case ISD::SETOLT: {  // !PF & CF
1540         Tys.push_back(MVT::i8);
1541         Tys.push_back(MVT::Flag);
1542         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
1543         Ops.push_back(Cond);
1544         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1545         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1546                                      DAG.getConstant(X86ISD::COND_B, MVT::i8),
1547                                      Tmp1.getValue(1));
1548         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
1549       }
1550       case ISD::SETOLE: {  // !PF & (CF || ZF)
1551         Tys.push_back(MVT::i8);
1552         Tys.push_back(MVT::Flag);
1553         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
1554         Ops.push_back(Cond);
1555         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1556         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1557                                      DAG.getConstant(X86ISD::COND_BE, MVT::i8),
1558                                      Tmp1.getValue(1));
1559         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
1560       }
1561       case ISD::SETUGT: {  // PF | (!ZF & !CF)
1562         Tys.push_back(MVT::i8);
1563         Tys.push_back(MVT::Flag);
1564         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
1565         Ops.push_back(Cond);
1566         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1567         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1568                                      DAG.getConstant(X86ISD::COND_A, MVT::i8),
1569                                      Tmp1.getValue(1));
1570         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
1571       }
1572       case ISD::SETUGE: {  // PF | !CF
1573         Tys.push_back(MVT::i8);
1574         Tys.push_back(MVT::Flag);
1575         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
1576         Ops.push_back(Cond);
1577         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1578         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1579                                      DAG.getConstant(X86ISD::COND_AE, MVT::i8),
1580                                      Tmp1.getValue(1));
1581         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
1582       }
1583       case ISD::SETUNE: {  // PF | !ZF
1584         Tys.push_back(MVT::i8);
1585         Tys.push_back(MVT::Flag);
1586         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
1587         Ops.push_back(Cond);
1588         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1589         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1590                                      DAG.getConstant(X86ISD::COND_NE, MVT::i8),
1591                                      Tmp1.getValue(1));
1592         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
1593       }
1594       }
1595     }
1596   }
1597   case ISD::SELECT: {
1598     MVT::ValueType VT = Op.getValueType();
1599     bool isFP      = MVT::isFloatingPoint(VT);
1600     bool isFPStack = isFP && !X86ScalarSSE;
1601     bool isFPSSE   = isFP && X86ScalarSSE;
1602     bool addTest   = false;
1603     SDOperand Op0 = Op.getOperand(0);
1604     SDOperand Cond, CC;
1605     if (Op0.getOpcode() == X86ISD::SETCC) {
1606       // If condition flag is set by a X86ISD::CMP, then make a copy of it
1607       // (since flag operand cannot be shared). If the X86ISD::SETCC does not
1608       // have another use it will be eliminated.
1609       // If the X86ISD::SETCC has more than one use, then it's probably better
1610       // to use a test instead of duplicating the X86ISD::CMP (for register
1611       // pressure reason).
1612       if (Op0.getOperand(1).getOpcode() == X86ISD::CMP) {
1613         if (!Op0.hasOneUse()) {
1614           std::vector<MVT::ValueType> Tys;
1615           for (unsigned i = 0; i < Op0.Val->getNumValues(); ++i)
1616             Tys.push_back(Op0.Val->getValueType(i));
1617           std::vector<SDOperand> Ops;
1618           for (unsigned i = 0; i < Op0.getNumOperands(); ++i)
1619             Ops.push_back(Op0.getOperand(i));
1620           Op0 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1621         }
1622
1623         CC   = Op0.getOperand(0);
1624         Cond = Op0.getOperand(1);
1625         // Make a copy as flag result cannot be used by more than one.
1626         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1627                            Cond.getOperand(0), Cond.getOperand(1));
1628         addTest =
1629           isFPStack && !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
1630       } else
1631         addTest = true;
1632     } else if (Op0.getOpcode() == ISD::SETCC) {
1633       CC = Op0.getOperand(2);
1634       bool isFP = MVT::isFloatingPoint(Op0.getOperand(1).getValueType());
1635       unsigned X86CC = getX86CC(CC, isFP);
1636       CC = DAG.getConstant(X86CC, MVT::i8);
1637       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1638                          Op0.getOperand(0), Op0.getOperand(1));
1639     } else
1640       addTest = true;
1641
1642     if (addTest) {
1643       CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1644       Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Op0, Op0);
1645     }
1646
1647     std::vector<MVT::ValueType> Tys;
1648     Tys.push_back(Op.getValueType());
1649     Tys.push_back(MVT::Flag);
1650     std::vector<SDOperand> Ops;
1651     // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
1652     // condition is true.
1653     Ops.push_back(Op.getOperand(2));
1654     Ops.push_back(Op.getOperand(1));
1655     Ops.push_back(CC);
1656     Ops.push_back(Cond);
1657     return DAG.getNode(X86ISD::CMOV, Tys, Ops);
1658   }
1659   case ISD::BRCOND: {
1660     bool addTest = false;
1661     SDOperand Cond  = Op.getOperand(1);
1662     SDOperand Dest  = Op.getOperand(2);
1663     SDOperand CC;
1664     if (Cond.getOpcode() == X86ISD::SETCC) {
1665       // If condition flag is set by a X86ISD::CMP, then make a copy of it
1666       // (since flag operand cannot be shared). If the X86ISD::SETCC does not
1667       // have another use it will be eliminated.
1668       // If the X86ISD::SETCC has more than one use, then it's probably better
1669       // to use a test instead of duplicating the X86ISD::CMP (for register
1670       // pressure reason).
1671       if (Cond.getOperand(1).getOpcode() == X86ISD::CMP) {
1672         if (!Cond.hasOneUse()) {
1673           std::vector<MVT::ValueType> Tys;
1674           for (unsigned i = 0; i < Cond.Val->getNumValues(); ++i)
1675             Tys.push_back(Cond.Val->getValueType(i));
1676           std::vector<SDOperand> Ops;
1677           for (unsigned i = 0; i < Cond.getNumOperands(); ++i)
1678             Ops.push_back(Cond.getOperand(i));
1679           Cond = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1680         }
1681
1682         CC   = Cond.getOperand(0);
1683         Cond = Cond.getOperand(1);
1684         // Make a copy as flag result cannot be used by more than one.
1685         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1686                            Cond.getOperand(0), Cond.getOperand(1));
1687       } else
1688         addTest = true;
1689     } else if (Cond.getOpcode() == ISD::SETCC) {
1690       CC = Cond.getOperand(2);
1691       bool isFP = MVT::isFloatingPoint(Cond.getOperand(1).getValueType());
1692       unsigned X86CC = getX86CC(CC, isFP);
1693       CC = DAG.getConstant(X86CC, MVT::i8);
1694       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1695                          Cond.getOperand(0), Cond.getOperand(1));
1696     } else
1697       addTest = true;
1698
1699     if (addTest) {
1700       CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1701       Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Cond, Cond);
1702     }
1703     return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
1704                        Op.getOperand(0), Op.getOperand(2), CC, Cond);
1705   }
1706   case ISD::MEMSET: {
1707     SDOperand InFlag;
1708     SDOperand Chain = Op.getOperand(0);
1709     unsigned Align =
1710       (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
1711     if (Align == 0) Align = 1;
1712
1713     MVT::ValueType AVT;
1714     SDOperand Count;
1715     if (ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
1716       unsigned ValReg;
1717       unsigned Val = ValC->getValue() & 255;
1718
1719       // If the value is a constant, then we can potentially use larger sets.
1720       switch (Align & 3) {
1721       case 2:   // WORD aligned
1722         AVT = MVT::i16;
1723         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1724           Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
1725         else
1726           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1727                               DAG.getConstant(1, MVT::i8));
1728         Val    = (Val << 8) | Val;
1729         ValReg = X86::AX;
1730         break;
1731       case 0:   // DWORD aligned
1732         AVT = MVT::i32;
1733         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1734           Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
1735         else
1736           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1737                               DAG.getConstant(2, MVT::i8));
1738         Val = (Val << 8)  | Val;
1739         Val = (Val << 16) | Val;
1740         ValReg = X86::EAX;
1741         break;
1742       default:  // Byte aligned
1743         AVT = MVT::i8;
1744         Count = Op.getOperand(3);
1745         ValReg = X86::AL;
1746         break;
1747       }
1748
1749       Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
1750                                 InFlag);
1751       InFlag = Chain.getValue(1);
1752     } else {
1753       AVT    = MVT::i8;
1754       Count  = Op.getOperand(3);
1755       Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
1756       InFlag = Chain.getValue(1);
1757     }
1758
1759     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
1760     InFlag = Chain.getValue(1);
1761     Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
1762     InFlag = Chain.getValue(1);
1763
1764     return DAG.getNode(X86ISD::REP_STOS, MVT::Other, Chain,
1765                        DAG.getValueType(AVT), InFlag);
1766   }
1767   case ISD::MEMCPY: {
1768     SDOperand Chain = Op.getOperand(0);
1769     unsigned Align =
1770       (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
1771     if (Align == 0) Align = 1;
1772
1773     MVT::ValueType AVT;
1774     SDOperand Count;
1775     switch (Align & 3) {
1776     case 2:   // WORD aligned
1777       AVT = MVT::i16;
1778       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1779         Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
1780       else
1781         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1782                             DAG.getConstant(1, MVT::i8));
1783       break;
1784     case 0:   // DWORD aligned
1785       AVT = MVT::i32;
1786       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
1787         Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
1788       else
1789         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1790                             DAG.getConstant(2, MVT::i8));
1791       break;
1792     default:  // Byte aligned
1793       AVT = MVT::i8;
1794       Count = Op.getOperand(3);
1795       break;
1796     }
1797
1798     SDOperand InFlag;
1799     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
1800     InFlag = Chain.getValue(1);
1801     Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
1802     InFlag = Chain.getValue(1);
1803     Chain  = DAG.getCopyToReg(Chain, X86::ESI, Op.getOperand(2), InFlag);
1804     InFlag = Chain.getValue(1);
1805
1806     return DAG.getNode(X86ISD::REP_MOVS, MVT::Other, Chain,
1807                        DAG.getValueType(AVT), InFlag);
1808   }
1809   case ISD::GlobalAddress: {
1810     SDOperand Result;
1811     GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1812     // For Darwin, external and weak symbols are indirect, so we want to load
1813     // the value at address GV, not the value of GV itself.  This means that
1814     // the GlobalAddress must be in the base or index register of the address,
1815     // not the GV offset field.
1816     if (getTargetMachine().
1817         getSubtarget<X86Subtarget>().getIndirectExternAndWeakGlobals() &&
1818         (GV->hasWeakLinkage() || GV->isExternal()))
1819       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(),
1820                            DAG.getTargetGlobalAddress(GV, getPointerTy()),
1821                            DAG.getSrcValue(NULL));
1822     return Result;
1823   }
1824   case ISD::VASTART: {
1825     // vastart just stores the address of the VarArgsFrameIndex slot into the
1826     // memory location argument.
1827     // FIXME: Replace MVT::i32 with PointerTy
1828     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
1829     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
1830                        Op.getOperand(1), Op.getOperand(2));
1831   }
1832   case ISD::RET: {
1833     SDOperand Copy;
1834     
1835     switch(Op.getNumOperands()) {
1836     default:
1837       assert(0 && "Do not know how to return this many arguments!");
1838       abort();
1839     case 1: 
1840       return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Op.getOperand(0),
1841                          DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1842     case 2: {
1843       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
1844       if (MVT::isInteger(ArgVT))
1845         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EAX, Op.getOperand(1),
1846                                 SDOperand());
1847       else if (!X86ScalarSSE) {
1848         std::vector<MVT::ValueType> Tys;
1849         Tys.push_back(MVT::Other);
1850         Tys.push_back(MVT::Flag);
1851         std::vector<SDOperand> Ops;
1852         Ops.push_back(Op.getOperand(0));
1853         Ops.push_back(Op.getOperand(1));
1854         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
1855       } else {
1856         // Spill the value to memory and reload it into top of stack.
1857         unsigned Size = MVT::getSizeInBits(ArgVT)/8;
1858         MachineFunction &MF = DAG.getMachineFunction();
1859         int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
1860         SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1861         SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), 
1862                                       Op.getOperand(1), StackSlot, 
1863                                       DAG.getSrcValue(0));
1864         std::vector<MVT::ValueType> Tys;
1865         Tys.push_back(MVT::f64);
1866         Tys.push_back(MVT::Other);
1867         std::vector<SDOperand> Ops;
1868         Ops.push_back(Chain);
1869         Ops.push_back(StackSlot);
1870         Ops.push_back(DAG.getValueType(ArgVT));
1871         Copy = DAG.getNode(X86ISD::FLD, Tys, Ops);
1872         Tys.clear();
1873         Tys.push_back(MVT::Other);
1874         Tys.push_back(MVT::Flag);
1875         Ops.clear();
1876         Ops.push_back(Copy.getValue(1));
1877         Ops.push_back(Copy);
1878         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
1879       }
1880       break;
1881     }
1882     case 3:
1883       Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EDX, Op.getOperand(2), 
1884                               SDOperand());
1885       Copy = DAG.getCopyToReg(Copy, X86::EAX,Op.getOperand(1),Copy.getValue(1));
1886       break;
1887     }
1888     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other,
1889                        Copy, DAG.getConstant(getBytesToPopOnReturn(), MVT::i16),
1890                        Copy.getValue(1));
1891   }
1892   }
1893 }
1894
1895 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
1896   switch (Opcode) {
1897   default: return NULL;
1898   case X86ISD::ADD_FLAG:           return "X86ISD::ADD_FLAG";
1899   case X86ISD::SUB_FLAG:           return "X86ISD::SUB_FLAG";
1900   case X86ISD::ADC:                return "X86ISD::ADC";
1901   case X86ISD::SBB:                return "X86ISD::SBB";
1902   case X86ISD::SHLD:               return "X86ISD::SHLD";
1903   case X86ISD::SHRD:               return "X86ISD::SHRD";
1904   case X86ISD::FILD:               return "X86ISD::FILD";
1905   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
1906   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
1907   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
1908   case X86ISD::FLD:                return "X86ISD::FLD";
1909   case X86ISD::FST:                return "X86ISD::FST";
1910   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
1911   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
1912   case X86ISD::CALL:               return "X86ISD::CALL";
1913   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
1914   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
1915   case X86ISD::CMP:                return "X86ISD::CMP";
1916   case X86ISD::TEST:               return "X86ISD::TEST";
1917   case X86ISD::SETCC:              return "X86ISD::SETCC";
1918   case X86ISD::CMOV:               return "X86ISD::CMOV";
1919   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
1920   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
1921   case X86ISD::REP_STOS:           return "X86ISD::RET_STOS";
1922   case X86ISD::REP_MOVS:           return "X86ISD::RET_MOVS";
1923   }
1924 }
1925
1926 bool X86TargetLowering::isMaskedValueZeroForTargetNode(const SDOperand &Op,
1927                                                        uint64_t Mask) const {
1928
1929   unsigned Opc = Op.getOpcode();
1930
1931   switch (Opc) {
1932   default:
1933     assert(Opc >= ISD::BUILTIN_OP_END && "Expected a target specific node");
1934     break;
1935   case X86ISD::SETCC: return (Mask & 1) == 0;
1936   }
1937
1938   return false;
1939 }