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