Added X86FunctionInfo subclass of MachineFunction to record whether the
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
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 "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/ADT/VectorExtras.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetOptions.h"
34 using namespace llvm;
35
36 // FIXME: temporary.
37 #include "llvm/Support/CommandLine.h"
38 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
39                                   cl::desc("Enable fastcc on X86"));
40
41 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
42   : TargetLowering(TM) {
43   Subtarget = &TM.getSubtarget<X86Subtarget>();
44   X86ScalarSSE = Subtarget->hasSSE2();
45
46   // Set up the TargetLowering object.
47
48   // X86 is weird, it always uses i8 for shift amounts and setcc results.
49   setShiftAmountType(MVT::i8);
50   setSetCCResultType(MVT::i8);
51   setSetCCResultContents(ZeroOrOneSetCCResult);
52   setSchedulingPreference(SchedulingForRegPressure);
53   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
54   setStackPointerRegisterToSaveRestore(X86::ESP);
55
56   if (!Subtarget->isTargetDarwin())
57     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
58     setUseUnderscoreSetJmpLongJmp(true);
59     
60   // Add legal addressing mode scale values.
61   addLegalAddressScale(8);
62   addLegalAddressScale(4);
63   addLegalAddressScale(2);
64   // Enter the ones which require both scale + index last. These are more
65   // expensive.
66   addLegalAddressScale(9);
67   addLegalAddressScale(5);
68   addLegalAddressScale(3);
69   
70   // Set up the register classes.
71   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
72   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
73   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
74
75   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
76   // operation.
77   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
78   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
79   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
80
81   if (X86ScalarSSE)
82     // No SSE i64 SINT_TO_FP, so expand i32 UINT_TO_FP instead.
83     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Expand);
84   else
85     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
86
87   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
88   // this operation.
89   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
90   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
91   // SSE has no i16 to fp conversion, only i32
92   if (X86ScalarSSE)
93     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
94   else {
95     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
96     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
97   }
98
99   // We can handle SINT_TO_FP and FP_TO_SINT from/to i64 even though i64
100   // isn't legal.
101   setOperationAction(ISD::SINT_TO_FP       , MVT::i64  , Custom);
102   setOperationAction(ISD::FP_TO_SINT       , MVT::i64  , Custom);
103
104   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
105   // this operation.
106   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
107   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
108
109   if (X86ScalarSSE) {
110     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
111   } else {
112     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
113     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
114   }
115
116   // Handle FP_TO_UINT by promoting the destination to a larger signed
117   // conversion.
118   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
119   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
120   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
121
122   if (X86ScalarSSE && !Subtarget->hasSSE3())
123     // Expand FP_TO_UINT into a select.
124     // FIXME: We would like to use a Custom expander here eventually to do
125     // the optimal thing for SSE vs. the default expansion in the legalizer.
126     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Expand);
127   else
128     // With SSE3 we can use fisttpll to convert to a signed i64.
129     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
130
131   setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
132   setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
133
134   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
135   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
136   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
137   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
138   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
140   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
141   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
142   setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
143   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
144   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
145   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
146   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
147   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
148   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
149   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
150   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
151   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
152   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
153   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
154   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
155
156   // These should be promoted to a larger select which is supported.
157   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
158   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
159
160   // X86 wants to expand cmov itself.
161   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
162   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
163   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
164   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
165   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
166   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
167   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
168   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
169   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
170   // X86 ret instruction may pop stack.
171   setOperationAction(ISD::RET             , MVT::Other, Custom);
172   // Darwin ABI issue.
173   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
174   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
175   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
176   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
177   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
178   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
179   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
180   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
181   // X86 wants to expand memset / memcpy itself.
182   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
183   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
184
185   // We don't have line number support yet.
186   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
187   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
188   // FIXME - use subtarget debug flags
189   if (!Subtarget->isTargetDarwin())
190     setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
191
192   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
193   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
194   
195   // Use the default implementation.
196   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
197   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
198   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
199   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
200   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
201   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
202
203   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
204   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
205
206   if (X86ScalarSSE) {
207     // Set up the FP register classes.
208     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
209     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
210
211     // Use ANDPD to simulate FABS.
212     setOperationAction(ISD::FABS , MVT::f64, Custom);
213     setOperationAction(ISD::FABS , MVT::f32, Custom);
214
215     // Use XORP to simulate FNEG.
216     setOperationAction(ISD::FNEG , MVT::f64, Custom);
217     setOperationAction(ISD::FNEG , MVT::f32, Custom);
218
219     // We don't support sin/cos/fmod
220     setOperationAction(ISD::FSIN , MVT::f64, Expand);
221     setOperationAction(ISD::FCOS , MVT::f64, Expand);
222     setOperationAction(ISD::FREM , MVT::f64, Expand);
223     setOperationAction(ISD::FSIN , MVT::f32, Expand);
224     setOperationAction(ISD::FCOS , MVT::f32, Expand);
225     setOperationAction(ISD::FREM , MVT::f32, Expand);
226
227     // Expand FP immediates into loads from the stack, except for the special
228     // cases we handle.
229     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
230     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
231     addLegalFPImmediate(+0.0); // xorps / xorpd
232   } else {
233     // Set up the FP register classes.
234     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
235     
236     setOperationAction(ISD::UNDEF, MVT::f64, Expand);
237     
238     if (!UnsafeFPMath) {
239       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
240       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
241     }
242
243     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
244     addLegalFPImmediate(+0.0); // FLD0
245     addLegalFPImmediate(+1.0); // FLD1
246     addLegalFPImmediate(-0.0); // FLD0/FCHS
247     addLegalFPImmediate(-1.0); // FLD1/FCHS
248   }
249
250   // First set operation action for all vector types to expand. Then we
251   // will selectively turn on ones that can be effectively codegen'd.
252   for (unsigned VT = (unsigned)MVT::Vector + 1;
253        VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
254     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
255     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
256     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
257     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
258     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
259     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
260     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
261   }
262
263   if (Subtarget->hasMMX()) {
264     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
265     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
266     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
267
268     // FIXME: add MMX packed arithmetics
269     setOperationAction(ISD::BUILD_VECTOR,     MVT::v8i8,  Expand);
270     setOperationAction(ISD::BUILD_VECTOR,     MVT::v4i16, Expand);
271     setOperationAction(ISD::BUILD_VECTOR,     MVT::v2i32, Expand);
272   }
273
274   if (Subtarget->hasSSE1()) {
275     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
276
277     setOperationAction(ISD::AND,                MVT::v4f32, Legal);
278     setOperationAction(ISD::OR,                 MVT::v4f32, Legal);
279     setOperationAction(ISD::XOR,                MVT::v4f32, Legal);
280     setOperationAction(ISD::ADD,                MVT::v4f32, Legal);
281     setOperationAction(ISD::SUB,                MVT::v4f32, Legal);
282     setOperationAction(ISD::MUL,                MVT::v4f32, Legal);
283     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
284     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
285     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
286     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
287     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
288   }
289
290   if (Subtarget->hasSSE2()) {
291     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
292     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
293     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
294     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
295     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
296
297     setOperationAction(ISD::ADD,                MVT::v2f64, Legal);
298     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
299     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
300     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
301     setOperationAction(ISD::SUB,                MVT::v2f64, Legal);
302     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
303     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
304     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
305     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
306     setOperationAction(ISD::MUL,                MVT::v2f64, Legal);
307
308     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
309     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
310     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
311     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
312     // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
313     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
314
315     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
316     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
317       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
318       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
319       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
320     }
321     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
322     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
323     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
324     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
325     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
326     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
327
328     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 
329     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
330       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
331       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
332       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
333       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
334       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
335       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
336       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
337       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
338       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
339       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
340     }
341
342     // Custom lower v2i64 and v2f64 selects.
343     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
344     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
345     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
346     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
347   }
348
349   // We want to custom lower some of our intrinsics.
350   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
351
352   computeRegisterProperties();
353
354   // FIXME: These should be based on subtarget info. Plus, the values should
355   // be smaller when we are in optimizing for size mode.
356   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
357   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
358   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
359   allowUnalignedMemoryAccesses = true; // x86 supports it!
360 }
361
362 //===----------------------------------------------------------------------===//
363 //                    C Calling Convention implementation
364 //===----------------------------------------------------------------------===//
365
366 /// AddLiveIn - This helper function adds the specified physical register to the
367 /// MachineFunction as a live in value.  It also creates a corresponding virtual
368 /// register for it.
369 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
370                           TargetRegisterClass *RC) {
371   assert(RC->contains(PReg) && "Not the correct regclass!");
372   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
373   MF.addLiveIn(PReg, VReg);
374   return VReg;
375 }
376
377 /// HowToPassCCCArgument - Returns how an formal argument of the specified type
378 /// should be passed. If it is through stack, returns the size of the stack
379 /// slot; if it is through XMM register, returns the number of XMM registers
380 /// are needed.
381 static void
382 HowToPassCCCArgument(MVT::ValueType ObjectVT, unsigned NumXMMRegs,
383                      unsigned &ObjSize, unsigned &ObjXMMRegs) {
384   ObjXMMRegs = 0;
385
386   switch (ObjectVT) {
387   default: assert(0 && "Unhandled argument type!");
388   case MVT::i8:  ObjSize = 1; break;
389   case MVT::i16: ObjSize = 2; break;
390   case MVT::i32: ObjSize = 4; break;
391   case MVT::i64: ObjSize = 8; break;
392   case MVT::f32: ObjSize = 4; break;
393   case MVT::f64: ObjSize = 8; break;
394   case MVT::v16i8:
395   case MVT::v8i16:
396   case MVT::v4i32:
397   case MVT::v2i64:
398   case MVT::v4f32:
399   case MVT::v2f64:
400     if (NumXMMRegs < 4)
401       ObjXMMRegs = 1;
402     else
403       ObjSize = 16;
404     break;
405   }
406 }
407
408 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG) {
409   unsigned NumArgs = Op.Val->getNumValues() - 1;
410   MachineFunction &MF = DAG.getMachineFunction();
411   MachineFrameInfo *MFI = MF.getFrameInfo();
412   SDOperand Root = Op.getOperand(0);
413   std::vector<SDOperand> ArgValues;
414
415   // Add DAG nodes to load the arguments...  On entry to a function on the X86,
416   // the stack frame looks like this:
417   //
418   // [ESP] -- return address
419   // [ESP + 4] -- first argument (leftmost lexically)
420   // [ESP + 8] -- second argument, if first argument is <= 4 bytes in size
421   //    ...
422   //
423   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
424   unsigned NumXMMRegs = 0;  // XMM regs used for parameter passing.
425   static const unsigned XMMArgRegs[] = {
426     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
427   };
428   for (unsigned i = 0; i < NumArgs; ++i) {
429     MVT::ValueType ObjectVT = Op.getValue(i).getValueType();
430     unsigned ArgIncrement = 4;
431     unsigned ObjSize = 0;
432     unsigned ObjXMMRegs = 0;
433     HowToPassCCCArgument(ObjectVT, NumXMMRegs, ObjSize, ObjXMMRegs);
434     if (ObjSize > 4)
435       ArgIncrement = ObjSize;
436
437     SDOperand ArgValue;
438     if (ObjXMMRegs) {
439       // Passed in a XMM register.
440       unsigned Reg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
441                                  X86::VR128RegisterClass);
442       ArgValue= DAG.getCopyFromReg(Root, Reg, ObjectVT);
443       ArgValues.push_back(ArgValue);
444       NumXMMRegs += ObjXMMRegs;
445     } else {
446       // XMM arguments have to be aligned on 16-byte boundary.
447       if (ObjSize == 16)
448         ArgOffset = ((ArgOffset + 15) / 16) * 16;
449       // Create the frame index object for this incoming parameter...
450       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
451       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
452       ArgValue = DAG.getLoad(Op.Val->getValueType(i), Root, FIN,
453                              DAG.getSrcValue(NULL));
454       ArgValues.push_back(ArgValue);
455       ArgOffset += ArgIncrement;   // Move on to the next argument...
456     }
457   }
458
459   ArgValues.push_back(Root);
460
461   // If the function takes variable number of arguments, make a frame index for
462   // the start of the first vararg value... for expansion of llvm.va_start.
463   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
464   if (isVarArg)
465     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
466   ReturnAddrIndex = 0;     // No return address slot generated yet.
467   BytesToPopOnReturn = 0;  // Callee pops nothing.
468   BytesCallerReserves = ArgOffset;
469
470   // If this is a struct return on Darwin/X86, the callee pops the hidden struct
471   // pointer.
472   if (MF.getFunction()->getCallingConv() == CallingConv::CSRet &&
473       Subtarget->isTargetDarwin())
474     BytesToPopOnReturn = 4;
475
476   // Return the new list of results.
477   std::vector<MVT::ValueType> RetVTs(Op.Val->value_begin(),
478                                      Op.Val->value_end());
479   return DAG.getNode(ISD::MERGE_VALUES, RetVTs, ArgValues);
480 }
481
482
483 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG) {
484   SDOperand Chain     = Op.getOperand(0);
485   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
486   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
487   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
488   SDOperand Callee    = Op.getOperand(4);
489   MVT::ValueType RetVT= Op.Val->getValueType(0);
490   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
491
492   // Keep track of the number of XMM regs passed so far.
493   unsigned NumXMMRegs = 0;
494   static const unsigned XMMArgRegs[] = {
495     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
496   };
497
498   // Count how many bytes are to be pushed on the stack.
499   unsigned NumBytes = 0;
500   for (unsigned i = 0; i != NumOps; ++i) {
501     SDOperand Arg = Op.getOperand(5+2*i);
502
503     switch (Arg.getValueType()) {
504     default: assert(0 && "Unexpected ValueType for argument!");
505     case MVT::i8:
506     case MVT::i16:
507     case MVT::i32:
508     case MVT::f32:
509       NumBytes += 4;
510       break;
511     case MVT::i64:
512     case MVT::f64:
513       NumBytes += 8;
514       break;
515     case MVT::v16i8:
516     case MVT::v8i16:
517     case MVT::v4i32:
518     case MVT::v2i64:
519     case MVT::v4f32:
520     case MVT::v2f64:
521       if (NumXMMRegs < 4)
522         ++NumXMMRegs;
523       else {
524         // XMM arguments have to be aligned on 16-byte boundary.
525         NumBytes = ((NumBytes + 15) / 16) * 16;
526         NumBytes += 16;
527       }
528       break;
529     }
530   }
531
532   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
533
534   // Arguments go on the stack in reverse order, as specified by the ABI.
535   unsigned ArgOffset = 0;
536   NumXMMRegs = 0;
537   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
538   std::vector<SDOperand> MemOpChains;
539   SDOperand StackPtr = DAG.getRegister(X86::ESP, getPointerTy());
540   for (unsigned i = 0; i != NumOps; ++i) {
541     SDOperand Arg = Op.getOperand(5+2*i);
542
543     switch (Arg.getValueType()) {
544     default: assert(0 && "Unexpected ValueType for argument!");
545     case MVT::i8:
546     case MVT::i16: {
547       // Promote the integer to 32 bits.  If the input type is signed use a
548       // sign extend, otherwise use a zero extend.
549       unsigned ExtOp =
550         dyn_cast<ConstantSDNode>(Op.getOperand(5+2*i+1))->getValue() ?
551         ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
552       Arg = DAG.getNode(ExtOp, MVT::i32, Arg);
553     }
554     // Fallthrough
555
556     case MVT::i32:
557     case MVT::f32: {
558       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
559       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
560       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
561                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
562       ArgOffset += 4;
563       break;
564     }
565     case MVT::i64:
566     case MVT::f64: {
567       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
568       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
569       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
570                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
571       ArgOffset += 8;
572       break;
573     }
574     case MVT::v16i8:
575     case MVT::v8i16:
576     case MVT::v4i32:
577     case MVT::v2i64:
578     case MVT::v4f32:
579     case MVT::v2f64:
580       if (NumXMMRegs < 4) {
581         RegsToPass.push_back(std::make_pair(XMMArgRegs[NumXMMRegs], Arg));
582         NumXMMRegs++;
583       } else {
584         // XMM arguments have to be aligned on 16-byte boundary.
585         ArgOffset = ((ArgOffset + 15) / 16) * 16;
586         SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
587         PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
588         MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
589                                           Arg, PtrOff, DAG.getSrcValue(NULL)));
590         ArgOffset += 16;
591       }
592     }
593   }
594
595   if (!MemOpChains.empty())
596     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains);
597
598   // Build a sequence of copy-to-reg nodes chained together with token chain
599   // and flag operands which copy the outgoing args into registers.
600   SDOperand InFlag;
601   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
602     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
603                              InFlag);
604     InFlag = Chain.getValue(1);
605   }
606
607   // If the callee is a GlobalAddress node (quite common, every direct call is)
608   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
609   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
610     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
611   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
612     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
613
614   std::vector<MVT::ValueType> NodeTys;
615   NodeTys.push_back(MVT::Other);   // Returns a chain
616   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
617   std::vector<SDOperand> Ops;
618   Ops.push_back(Chain);
619   Ops.push_back(Callee);
620   if (InFlag.Val)
621     Ops.push_back(InFlag);
622
623   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
624                       NodeTys, Ops);
625   InFlag = Chain.getValue(1);
626
627   // Create the CALLSEQ_END node.
628   unsigned NumBytesForCalleeToPush = 0;
629
630   // If this is is a call to a struct-return function on Darwin/X86, the callee
631   // pops the hidden struct pointer, so we have to push it back.
632   if (CallingConv == CallingConv::CSRet && Subtarget->isTargetDarwin())
633     NumBytesForCalleeToPush = 4;
634   
635   NodeTys.clear();
636   NodeTys.push_back(MVT::Other);   // Returns a chain
637   if (RetVT != MVT::Other)
638     NodeTys.push_back(MVT::Flag);  // Returns a flag for retval copy to use.
639   Ops.clear();
640   Ops.push_back(Chain);
641   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
642   Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
643   Ops.push_back(InFlag);
644   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
645   if (RetVT != MVT::Other)
646     InFlag = Chain.getValue(1);
647   
648   std::vector<SDOperand> ResultVals;
649   NodeTys.clear();
650   switch (RetVT) {
651   default: assert(0 && "Unknown value type to return!");
652   case MVT::Other: break;
653   case MVT::i8:
654     Chain = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag).getValue(1);
655     ResultVals.push_back(Chain.getValue(0));
656     NodeTys.push_back(MVT::i8);
657     break;
658   case MVT::i16:
659     Chain = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag).getValue(1);
660     ResultVals.push_back(Chain.getValue(0));
661     NodeTys.push_back(MVT::i16);
662     break;
663   case MVT::i32:
664     if (Op.Val->getValueType(1) == MVT::i32) {
665       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
666       ResultVals.push_back(Chain.getValue(0));
667       Chain = DAG.getCopyFromReg(Chain, X86::EDX, MVT::i32,
668                                  Chain.getValue(2)).getValue(1);
669       ResultVals.push_back(Chain.getValue(0));
670       NodeTys.push_back(MVT::i32);
671     } else {
672       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
673       ResultVals.push_back(Chain.getValue(0));
674     }
675     NodeTys.push_back(MVT::i32);
676     break;
677   case MVT::v16i8:
678   case MVT::v8i16:
679   case MVT::v4i32:
680   case MVT::v2i64:
681   case MVT::v4f32:
682   case MVT::v2f64:
683     Chain = DAG.getCopyFromReg(Chain, X86::XMM0, RetVT, InFlag).getValue(1);
684     ResultVals.push_back(Chain.getValue(0));
685     NodeTys.push_back(RetVT);
686     break;
687   case MVT::f32:
688   case MVT::f64: {
689     std::vector<MVT::ValueType> Tys;
690     Tys.push_back(MVT::f64);
691     Tys.push_back(MVT::Other);
692     Tys.push_back(MVT::Flag);
693     std::vector<SDOperand> Ops;
694     Ops.push_back(Chain);
695     Ops.push_back(InFlag);
696     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
697     Chain  = RetVal.getValue(1);
698     InFlag = RetVal.getValue(2);
699     if (X86ScalarSSE) {
700       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
701       // shouldn't be necessary except that RFP cannot be live across
702       // multiple blocks. When stackifier is fixed, they can be uncoupled.
703       MachineFunction &MF = DAG.getMachineFunction();
704       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
705       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
706       Tys.clear();
707       Tys.push_back(MVT::Other);
708       Ops.clear();
709       Ops.push_back(Chain);
710       Ops.push_back(RetVal);
711       Ops.push_back(StackSlot);
712       Ops.push_back(DAG.getValueType(RetVT));
713       Ops.push_back(InFlag);
714       Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
715       RetVal = DAG.getLoad(RetVT, Chain, StackSlot,
716                            DAG.getSrcValue(NULL));
717       Chain = RetVal.getValue(1);
718     }
719
720     if (RetVT == MVT::f32 && !X86ScalarSSE)
721       // FIXME: we would really like to remember that this FP_ROUND
722       // operation is okay to eliminate if we allow excess FP precision.
723       RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
724     ResultVals.push_back(RetVal);
725     NodeTys.push_back(RetVT);
726     break;
727   }
728   }
729
730   // If the function returns void, just return the chain.
731   if (ResultVals.empty())
732     return Chain;
733   
734   // Otherwise, merge everything together with a MERGE_VALUES node.
735   NodeTys.push_back(MVT::Other);
736   ResultVals.push_back(Chain);
737   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals);
738   return Res.getValue(Op.ResNo);
739 }
740
741 //===----------------------------------------------------------------------===//
742 //                    Fast Calling Convention implementation
743 //===----------------------------------------------------------------------===//
744 //
745 // The X86 'fast' calling convention passes up to two integer arguments in
746 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
747 // and requires that the callee pop its arguments off the stack (allowing proper
748 // tail calls), and has the same return value conventions as C calling convs.
749 //
750 // This calling convention always arranges for the callee pop value to be 8n+4
751 // bytes, which is needed for tail recursion elimination and stack alignment
752 // reasons.
753 //
754 // Note that this can be enhanced in the future to pass fp vals in registers
755 // (when we have a global fp allocator) and do other tricks.
756 //
757
758 // FASTCC_NUM_INT_ARGS_INREGS - This is the max number of integer arguments
759 // to pass in registers.  0 is none, 1 is is "use EAX", 2 is "use EAX and
760 // EDX".  Anything more is illegal.
761 //
762 // FIXME: The linscan register allocator currently has problem with
763 // coalescing.  At the time of this writing, whenever it decides to coalesce
764 // a physreg with a virtreg, this increases the size of the physreg's live
765 // range, and the live range cannot ever be reduced.  This causes problems if
766 // too many physregs are coaleced with virtregs, which can cause the register
767 // allocator to wedge itself.
768 //
769 // This code triggers this problem more often if we pass args in registers,
770 // so disable it until this is fixed.
771 //
772 // NOTE: this isn't marked const, so that GCC doesn't emit annoying warnings
773 // about code being dead.
774 //
775 static unsigned FASTCC_NUM_INT_ARGS_INREGS = 0;
776
777
778 /// HowToPassFastCCArgument - Returns how an formal argument of the specified
779 /// type should be passed. If it is through stack, returns the size of the stack
780 /// slot; if it is through integer or XMM register, returns the number of
781 /// integer or XMM registers are needed.
782 static void
783 HowToPassFastCCArgument(MVT::ValueType ObjectVT,
784                         unsigned NumIntRegs, unsigned NumXMMRegs,
785                         unsigned &ObjSize, unsigned &ObjIntRegs,
786                         unsigned &ObjXMMRegs) {
787   ObjSize = 0;
788   ObjIntRegs = 0;
789   ObjXMMRegs = 0;
790
791   switch (ObjectVT) {
792   default: assert(0 && "Unhandled argument type!");
793   case MVT::i8:
794     if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS)
795       ObjIntRegs = 1;
796     else
797       ObjSize = 1;
798     break;
799   case MVT::i16:
800     if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS)
801       ObjIntRegs = 1;
802     else
803       ObjSize = 2;
804     break;
805   case MVT::i32:
806     if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS)
807       ObjIntRegs = 1;
808     else
809       ObjSize = 4;
810     break;
811   case MVT::i64:
812     if (NumIntRegs+2 <= FASTCC_NUM_INT_ARGS_INREGS) {
813       ObjIntRegs = 2;
814     } else if (NumIntRegs+1 <= FASTCC_NUM_INT_ARGS_INREGS) {
815       ObjIntRegs = 1;
816       ObjSize = 4;
817     } else
818       ObjSize = 8;
819   case MVT::f32:
820     ObjSize = 4;
821     break;
822   case MVT::f64:
823     ObjSize = 8;
824     break;
825   case MVT::v16i8:
826   case MVT::v8i16:
827   case MVT::v4i32:
828   case MVT::v2i64:
829   case MVT::v4f32:
830   case MVT::v2f64:
831     if (NumXMMRegs < 4)
832       ObjXMMRegs = 1;
833     else
834       ObjSize = 16;
835     break;
836   }
837 }
838
839 SDOperand
840 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
841   unsigned NumArgs = Op.Val->getNumValues()-1;
842   MachineFunction &MF = DAG.getMachineFunction();
843   MachineFrameInfo *MFI = MF.getFrameInfo();
844   SDOperand Root = Op.getOperand(0);
845   std::vector<SDOperand> ArgValues;
846
847   // Add DAG nodes to load the arguments...  On entry to a function the stack
848   // frame looks like this:
849   //
850   // [ESP] -- return address
851   // [ESP + 4] -- first nonreg argument (leftmost lexically)
852   // [ESP + 8] -- second nonreg argument, if 1st argument is <= 4 bytes in size
853   //    ...
854   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
855
856   // Keep track of the number of integer regs passed so far.  This can be either
857   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
858   // used).
859   unsigned NumIntRegs = 0;
860   unsigned NumXMMRegs = 0;  // XMM regs used for parameter passing.
861
862   static const unsigned XMMArgRegs[] = {
863     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
864   };
865   
866   for (unsigned i = 0; i < NumArgs; ++i) {
867     MVT::ValueType ObjectVT = Op.getValue(i).getValueType();
868     unsigned ArgIncrement = 4;
869     unsigned ObjSize = 0;
870     unsigned ObjIntRegs = 0;
871     unsigned ObjXMMRegs = 0;
872
873     HowToPassFastCCArgument(ObjectVT, NumIntRegs, NumXMMRegs,
874                             ObjSize, ObjIntRegs, ObjXMMRegs);
875     if (ObjSize > 4)
876       ArgIncrement = ObjSize;
877
878     unsigned Reg = 0;
879     SDOperand ArgValue;
880     if (ObjIntRegs || ObjXMMRegs) {
881       switch (ObjectVT) {
882       default: assert(0 && "Unhandled argument type!");
883       case MVT::i8:
884         Reg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
885                         X86::GR8RegisterClass);
886         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i8);
887         break;
888       case MVT::i16:
889         Reg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
890                         X86::GR16RegisterClass);
891         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i16);
892         break;
893       case MVT::i32:
894         Reg = AddLiveIn(MF, NumIntRegs ? X86::EDX : X86::EAX,
895                         X86::GR32RegisterClass);
896         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i32);
897         break;
898       case MVT::i64:
899         Reg = AddLiveIn(MF, NumIntRegs ? X86::EDX : X86::EAX,
900                         X86::GR32RegisterClass);
901         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i32);
902         if (ObjIntRegs == 2) {
903           Reg = AddLiveIn(MF, X86::EDX, X86::GR32RegisterClass);
904           SDOperand ArgValue2 = DAG.getCopyFromReg(Root, Reg, MVT::i32);
905           ArgValue= DAG.getNode(ISD::BUILD_PAIR, MVT::i64, ArgValue, ArgValue2);
906         }
907         break;
908       case MVT::v16i8:
909       case MVT::v8i16:
910       case MVT::v4i32:
911       case MVT::v2i64:
912       case MVT::v4f32:
913       case MVT::v2f64:
914         Reg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs], X86::VR128RegisterClass);
915         ArgValue = DAG.getCopyFromReg(Root, Reg, ObjectVT);
916         break;
917       }
918       NumIntRegs += ObjIntRegs;
919       NumXMMRegs += ObjXMMRegs;
920     }
921
922     if (ObjSize) {
923       // XMM arguments have to be aligned on 16-byte boundary.
924       if (ObjSize == 16)
925         ArgOffset = ((ArgOffset + 15) / 16) * 16;
926       // Create the SelectionDAG nodes corresponding to a load from this
927       // parameter.
928       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
929       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
930       if (ObjectVT == MVT::i64 && ObjIntRegs) {
931         SDOperand ArgValue2 = DAG.getLoad(Op.Val->getValueType(i), Root, FIN,
932                                           DAG.getSrcValue(NULL));
933         ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, ArgValue, ArgValue2);
934       } else
935         ArgValue = DAG.getLoad(Op.Val->getValueType(i), Root, FIN,
936                                DAG.getSrcValue(NULL));
937       ArgOffset += ArgIncrement;   // Move on to the next argument.
938     }
939
940     ArgValues.push_back(ArgValue);
941   }
942
943   ArgValues.push_back(Root);
944
945   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
946   // arguments and the arguments after the retaddr has been pushed are aligned.
947   if ((ArgOffset & 7) == 0)
948     ArgOffset += 4;
949
950   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
951   ReturnAddrIndex = 0;             // No return address slot generated yet.
952   BytesToPopOnReturn = ArgOffset;  // Callee pops all stack arguments.
953   BytesCallerReserves = 0;
954
955   // Finally, inform the code generator which regs we return values in.
956   switch (getValueType(MF.getFunction()->getReturnType())) {
957   default: assert(0 && "Unknown type!");
958   case MVT::isVoid: break;
959   case MVT::i8:
960   case MVT::i16:
961   case MVT::i32:
962     MF.addLiveOut(X86::EAX);
963     break;
964   case MVT::i64:
965     MF.addLiveOut(X86::EAX);
966     MF.addLiveOut(X86::EDX);
967     break;
968   case MVT::f32:
969   case MVT::f64:
970     MF.addLiveOut(X86::ST0);
971     break;
972   case MVT::v16i8:
973   case MVT::v8i16:
974   case MVT::v4i32:
975   case MVT::v2i64:
976   case MVT::v4f32:
977   case MVT::v2f64:
978     MF.addLiveOut(X86::XMM0);
979     break;
980   }
981
982   // Return the new list of results.
983   std::vector<MVT::ValueType> RetVTs(Op.Val->value_begin(),
984                                      Op.Val->value_end());
985   return DAG.getNode(ISD::MERGE_VALUES, RetVTs, ArgValues);
986 }
987
988  SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG) {
989   SDOperand Chain     = Op.getOperand(0);
990   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
991   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
992   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
993   SDOperand Callee    = Op.getOperand(4);
994   MVT::ValueType RetVT= Op.Val->getValueType(0);
995   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
996
997   // Count how many bytes are to be pushed on the stack.
998   unsigned NumBytes = 0;
999
1000   // Keep track of the number of integer regs passed so far.  This can be either
1001   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
1002   // used).
1003   unsigned NumIntRegs = 0;
1004   unsigned NumXMMRegs = 0;  // XMM regs used for parameter passing.
1005
1006   static const unsigned GPRArgRegs[][2] = {
1007     { X86::AL,  X86::DL },
1008     { X86::AX,  X86::DX },
1009     { X86::EAX, X86::EDX }
1010   };
1011   static const unsigned XMMArgRegs[] = {
1012     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1013   };
1014
1015   for (unsigned i = 0; i != NumOps; ++i) {
1016     SDOperand Arg = Op.getOperand(5+2*i);
1017
1018     switch (Arg.getValueType()) {
1019     default: assert(0 && "Unknown value type!");
1020     case MVT::i8:
1021     case MVT::i16:
1022     case MVT::i32:
1023       if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS) {
1024         ++NumIntRegs;
1025         break;
1026       }
1027       // Fall through
1028     case MVT::f32:
1029       NumBytes += 4;
1030       break;
1031     case MVT::f64:
1032       NumBytes += 8;
1033       break;
1034     case MVT::v16i8:
1035     case MVT::v8i16:
1036     case MVT::v4i32:
1037     case MVT::v2i64:
1038     case MVT::v4f32:
1039     case MVT::v2f64:
1040       if (NumXMMRegs < 4)
1041         NumXMMRegs++;
1042       else {
1043         // XMM arguments have to be aligned on 16-byte boundary.
1044         NumBytes = ((NumBytes + 15) / 16) * 16;
1045         NumBytes += 16;
1046       }
1047       break;
1048     }
1049   }
1050
1051   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1052   // arguments and the arguments after the retaddr has been pushed are aligned.
1053   if ((NumBytes & 7) == 0)
1054     NumBytes += 4;
1055
1056   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1057
1058   // Arguments go on the stack in reverse order, as specified by the ABI.
1059   unsigned ArgOffset = 0;
1060   NumIntRegs = 0;
1061   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
1062   std::vector<SDOperand> MemOpChains;
1063   SDOperand StackPtr = DAG.getRegister(X86::ESP, getPointerTy());
1064   for (unsigned i = 0; i != NumOps; ++i) {
1065     SDOperand Arg = Op.getOperand(5+2*i);
1066
1067     switch (Arg.getValueType()) {
1068     default: assert(0 && "Unexpected ValueType for argument!");
1069     case MVT::i8:
1070     case MVT::i16:
1071     case MVT::i32:
1072       if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS) {
1073         RegsToPass.push_back(
1074               std::make_pair(GPRArgRegs[Arg.getValueType()-MVT::i8][NumIntRegs],
1075                              Arg));
1076         ++NumIntRegs;
1077         break;
1078       }
1079       // Fall through
1080     case MVT::f32: {
1081       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1082       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1083       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1084                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
1085       ArgOffset += 4;
1086       break;
1087     }
1088     case MVT::f64: {
1089       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1090       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1091       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1092                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
1093       ArgOffset += 8;
1094       break;
1095     }
1096     case MVT::v16i8:
1097     case MVT::v8i16:
1098     case MVT::v4i32:
1099     case MVT::v2i64:
1100     case MVT::v4f32:
1101     case MVT::v2f64:
1102       if (NumXMMRegs < 4) {
1103         RegsToPass.push_back(std::make_pair(XMMArgRegs[NumXMMRegs], Arg));
1104         NumXMMRegs++;
1105       } else {
1106         // XMM arguments have to be aligned on 16-byte boundary.
1107         ArgOffset = ((ArgOffset + 15) / 16) * 16;
1108         SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1109         PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1110         MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1111                                           Arg, PtrOff, DAG.getSrcValue(NULL)));
1112         ArgOffset += 16;
1113       }
1114     }
1115   }
1116
1117   if (!MemOpChains.empty())
1118     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains);
1119
1120   // Build a sequence of copy-to-reg nodes chained together with token chain
1121   // and flag operands which copy the outgoing args into registers.
1122   SDOperand InFlag;
1123   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1124     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1125                              InFlag);
1126     InFlag = Chain.getValue(1);
1127   }
1128
1129   // If the callee is a GlobalAddress node (quite common, every direct call is)
1130   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1131   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1132     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1133   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1134     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1135
1136   std::vector<MVT::ValueType> NodeTys;
1137   NodeTys.push_back(MVT::Other);   // Returns a chain
1138   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
1139   std::vector<SDOperand> Ops;
1140   Ops.push_back(Chain);
1141   Ops.push_back(Callee);
1142   if (InFlag.Val)
1143     Ops.push_back(InFlag);
1144
1145   // FIXME: Do not generate X86ISD::TAILCALL for now.
1146   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1147                       NodeTys, Ops);
1148   InFlag = Chain.getValue(1);
1149
1150   NodeTys.clear();
1151   NodeTys.push_back(MVT::Other);   // Returns a chain
1152   if (RetVT != MVT::Other)
1153     NodeTys.push_back(MVT::Flag);  // Returns a flag for retval copy to use.
1154   Ops.clear();
1155   Ops.push_back(Chain);
1156   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1157   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1158   Ops.push_back(InFlag);
1159   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
1160   if (RetVT != MVT::Other)
1161     InFlag = Chain.getValue(1);
1162   
1163   std::vector<SDOperand> ResultVals;
1164   NodeTys.clear();
1165   switch (RetVT) {
1166   default: assert(0 && "Unknown value type to return!");
1167   case MVT::Other: break;
1168   case MVT::i8:
1169     Chain = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag).getValue(1);
1170     ResultVals.push_back(Chain.getValue(0));
1171     NodeTys.push_back(MVT::i8);
1172     break;
1173   case MVT::i16:
1174     Chain = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag).getValue(1);
1175     ResultVals.push_back(Chain.getValue(0));
1176     NodeTys.push_back(MVT::i16);
1177     break;
1178   case MVT::i32:
1179     if (Op.Val->getValueType(1) == MVT::i32) {
1180       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
1181       ResultVals.push_back(Chain.getValue(0));
1182       Chain = DAG.getCopyFromReg(Chain, X86::EDX, MVT::i32,
1183                                  Chain.getValue(2)).getValue(1);
1184       ResultVals.push_back(Chain.getValue(0));
1185       NodeTys.push_back(MVT::i32);
1186     } else {
1187       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
1188       ResultVals.push_back(Chain.getValue(0));
1189     }
1190     NodeTys.push_back(MVT::i32);
1191     break;
1192   case MVT::v16i8:
1193   case MVT::v8i16:
1194   case MVT::v4i32:
1195   case MVT::v2i64:
1196   case MVT::v4f32:
1197   case MVT::v2f64:
1198     Chain = DAG.getCopyFromReg(Chain, X86::XMM0, RetVT, InFlag).getValue(1);
1199     ResultVals.push_back(Chain.getValue(0));
1200     NodeTys.push_back(RetVT);
1201     break;
1202   case MVT::f32:
1203   case MVT::f64: {
1204     std::vector<MVT::ValueType> Tys;
1205     Tys.push_back(MVT::f64);
1206     Tys.push_back(MVT::Other);
1207     Tys.push_back(MVT::Flag);
1208     std::vector<SDOperand> Ops;
1209     Ops.push_back(Chain);
1210     Ops.push_back(InFlag);
1211     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
1212     Chain  = RetVal.getValue(1);
1213     InFlag = RetVal.getValue(2);
1214     if (X86ScalarSSE) {
1215       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
1216       // shouldn't be necessary except that RFP cannot be live across
1217       // multiple blocks. When stackifier is fixed, they can be uncoupled.
1218       MachineFunction &MF = DAG.getMachineFunction();
1219       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
1220       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1221       Tys.clear();
1222       Tys.push_back(MVT::Other);
1223       Ops.clear();
1224       Ops.push_back(Chain);
1225       Ops.push_back(RetVal);
1226       Ops.push_back(StackSlot);
1227       Ops.push_back(DAG.getValueType(RetVT));
1228       Ops.push_back(InFlag);
1229       Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1230       RetVal = DAG.getLoad(RetVT, Chain, StackSlot,
1231                            DAG.getSrcValue(NULL));
1232       Chain = RetVal.getValue(1);
1233     }
1234
1235     if (RetVT == MVT::f32 && !X86ScalarSSE)
1236       // FIXME: we would really like to remember that this FP_ROUND
1237       // operation is okay to eliminate if we allow excess FP precision.
1238       RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
1239     ResultVals.push_back(RetVal);
1240     NodeTys.push_back(RetVT);
1241     break;
1242   }
1243   }
1244
1245
1246   // If the function returns void, just return the chain.
1247   if (ResultVals.empty())
1248     return Chain;
1249   
1250   // Otherwise, merge everything together with a MERGE_VALUES node.
1251   NodeTys.push_back(MVT::Other);
1252   ResultVals.push_back(Chain);
1253   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals);
1254   return Res.getValue(Op.ResNo);
1255 }
1256
1257 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1258   if (ReturnAddrIndex == 0) {
1259     // Set up a frame object for the return address.
1260     MachineFunction &MF = DAG.getMachineFunction();
1261     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1262   }
1263
1264   return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
1265 }
1266
1267
1268
1269 std::pair<SDOperand, SDOperand> X86TargetLowering::
1270 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
1271                         SelectionDAG &DAG) {
1272   SDOperand Result;
1273   if (Depth)        // Depths > 0 not supported yet!
1274     Result = DAG.getConstant(0, getPointerTy());
1275   else {
1276     SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
1277     if (!isFrameAddress)
1278       // Just load the return address
1279       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
1280                            DAG.getSrcValue(NULL));
1281     else
1282       Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
1283                            DAG.getConstant(4, MVT::i32));
1284   }
1285   return std::make_pair(Result, Chain);
1286 }
1287
1288 /// getCondBrOpcodeForX86CC - Returns the X86 conditional branch opcode
1289 /// which corresponds to the condition code.
1290 static unsigned getCondBrOpcodeForX86CC(unsigned X86CC) {
1291   switch (X86CC) {
1292   default: assert(0 && "Unknown X86 conditional code!");
1293   case X86ISD::COND_A:  return X86::JA;
1294   case X86ISD::COND_AE: return X86::JAE;
1295   case X86ISD::COND_B:  return X86::JB;
1296   case X86ISD::COND_BE: return X86::JBE;
1297   case X86ISD::COND_E:  return X86::JE;
1298   case X86ISD::COND_G:  return X86::JG;
1299   case X86ISD::COND_GE: return X86::JGE;
1300   case X86ISD::COND_L:  return X86::JL;
1301   case X86ISD::COND_LE: return X86::JLE;
1302   case X86ISD::COND_NE: return X86::JNE;
1303   case X86ISD::COND_NO: return X86::JNO;
1304   case X86ISD::COND_NP: return X86::JNP;
1305   case X86ISD::COND_NS: return X86::JNS;
1306   case X86ISD::COND_O:  return X86::JO;
1307   case X86ISD::COND_P:  return X86::JP;
1308   case X86ISD::COND_S:  return X86::JS;
1309   }
1310 }
1311
1312 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1313 /// specific condition code. It returns a false if it cannot do a direct
1314 /// translation. X86CC is the translated CondCode. Flip is set to true if the
1315 /// the order of comparison operands should be flipped.
1316 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1317                            unsigned &X86CC, bool &Flip) {
1318   Flip = false;
1319   X86CC = X86ISD::COND_INVALID;
1320   if (!isFP) {
1321     switch (SetCCOpcode) {
1322     default: break;
1323     case ISD::SETEQ:  X86CC = X86ISD::COND_E;  break;
1324     case ISD::SETGT:  X86CC = X86ISD::COND_G;  break;
1325     case ISD::SETGE:  X86CC = X86ISD::COND_GE; break;
1326     case ISD::SETLT:  X86CC = X86ISD::COND_L;  break;
1327     case ISD::SETLE:  X86CC = X86ISD::COND_LE; break;
1328     case ISD::SETNE:  X86CC = X86ISD::COND_NE; break;
1329     case ISD::SETULT: X86CC = X86ISD::COND_B;  break;
1330     case ISD::SETUGT: X86CC = X86ISD::COND_A;  break;
1331     case ISD::SETULE: X86CC = X86ISD::COND_BE; break;
1332     case ISD::SETUGE: X86CC = X86ISD::COND_AE; break;
1333     }
1334   } else {
1335     // On a floating point condition, the flags are set as follows:
1336     // ZF  PF  CF   op
1337     //  0 | 0 | 0 | X > Y
1338     //  0 | 0 | 1 | X < Y
1339     //  1 | 0 | 0 | X == Y
1340     //  1 | 1 | 1 | unordered
1341     switch (SetCCOpcode) {
1342     default: break;
1343     case ISD::SETUEQ:
1344     case ISD::SETEQ: X86CC = X86ISD::COND_E;  break;
1345     case ISD::SETOLT: Flip = true; // Fallthrough
1346     case ISD::SETOGT:
1347     case ISD::SETGT: X86CC = X86ISD::COND_A;  break;
1348     case ISD::SETOLE: Flip = true; // Fallthrough
1349     case ISD::SETOGE:
1350     case ISD::SETGE: X86CC = X86ISD::COND_AE; break;
1351     case ISD::SETUGT: Flip = true; // Fallthrough
1352     case ISD::SETULT:
1353     case ISD::SETLT: X86CC = X86ISD::COND_B;  break;
1354     case ISD::SETUGE: Flip = true; // Fallthrough
1355     case ISD::SETULE:
1356     case ISD::SETLE: X86CC = X86ISD::COND_BE; break;
1357     case ISD::SETONE:
1358     case ISD::SETNE: X86CC = X86ISD::COND_NE; break;
1359     case ISD::SETUO: X86CC = X86ISD::COND_P;  break;
1360     case ISD::SETO:  X86CC = X86ISD::COND_NP; break;
1361     }
1362   }
1363
1364   return X86CC != X86ISD::COND_INVALID;
1365 }
1366
1367 static bool translateX86CC(SDOperand CC, bool isFP, unsigned &X86CC,
1368                            bool &Flip) {
1369   return translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC, Flip);
1370 }
1371
1372 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1373 /// code. Current x86 isa includes the following FP cmov instructions:
1374 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1375 static bool hasFPCMov(unsigned X86CC) {
1376   switch (X86CC) {
1377   default:
1378     return false;
1379   case X86ISD::COND_B:
1380   case X86ISD::COND_BE:
1381   case X86ISD::COND_E:
1382   case X86ISD::COND_P:
1383   case X86ISD::COND_A:
1384   case X86ISD::COND_AE:
1385   case X86ISD::COND_NE:
1386   case X86ISD::COND_NP:
1387     return true;
1388   }
1389 }
1390
1391 MachineBasicBlock *
1392 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1393                                            MachineBasicBlock *BB) {
1394   switch (MI->getOpcode()) {
1395   default: assert(false && "Unexpected instr type to insert");
1396   case X86::CMOV_FR32:
1397   case X86::CMOV_FR64:
1398   case X86::CMOV_V4F32:
1399   case X86::CMOV_V2F64:
1400   case X86::CMOV_V2I64: {
1401     // To "insert" a SELECT_CC instruction, we actually have to insert the
1402     // diamond control-flow pattern.  The incoming instruction knows the
1403     // destination vreg to set, the condition code register to branch on, the
1404     // true/false values to select between, and a branch opcode to use.
1405     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1406     ilist<MachineBasicBlock>::iterator It = BB;
1407     ++It;
1408   
1409     //  thisMBB:
1410     //  ...
1411     //   TrueVal = ...
1412     //   cmpTY ccX, r1, r2
1413     //   bCC copy1MBB
1414     //   fallthrough --> copy0MBB
1415     MachineBasicBlock *thisMBB = BB;
1416     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1417     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1418     unsigned Opc = getCondBrOpcodeForX86CC(MI->getOperand(3).getImmedValue());
1419     BuildMI(BB, Opc, 1).addMBB(sinkMBB);
1420     MachineFunction *F = BB->getParent();
1421     F->getBasicBlockList().insert(It, copy0MBB);
1422     F->getBasicBlockList().insert(It, sinkMBB);
1423     // Update machine-CFG edges by first adding all successors of the current
1424     // block to the new block which will contain the Phi node for the select.
1425     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(), 
1426         e = BB->succ_end(); i != e; ++i)
1427       sinkMBB->addSuccessor(*i);
1428     // Next, remove all successors of the current block, and add the true
1429     // and fallthrough blocks as its successors.
1430     while(!BB->succ_empty())
1431       BB->removeSuccessor(BB->succ_begin());
1432     BB->addSuccessor(copy0MBB);
1433     BB->addSuccessor(sinkMBB);
1434   
1435     //  copy0MBB:
1436     //   %FalseValue = ...
1437     //   # fallthrough to sinkMBB
1438     BB = copy0MBB;
1439   
1440     // Update machine-CFG edges
1441     BB->addSuccessor(sinkMBB);
1442   
1443     //  sinkMBB:
1444     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1445     //  ...
1446     BB = sinkMBB;
1447     BuildMI(BB, X86::PHI, 4, MI->getOperand(0).getReg())
1448       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1449       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1450
1451     delete MI;   // The pseudo instruction is gone now.
1452     return BB;
1453   }
1454
1455   case X86::FP_TO_INT16_IN_MEM:
1456   case X86::FP_TO_INT32_IN_MEM:
1457   case X86::FP_TO_INT64_IN_MEM: {
1458     // Change the floating point control register to use "round towards zero"
1459     // mode when truncating to an integer value.
1460     MachineFunction *F = BB->getParent();
1461     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1462     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1463
1464     // Load the old value of the high byte of the control word...
1465     unsigned OldCW =
1466       F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
1467     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
1468
1469     // Set the high part to be round to zero...
1470     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
1471
1472     // Reload the modified control word now...
1473     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1474
1475     // Restore the memory image of control word to original value
1476     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
1477
1478     // Get the X86 opcode to use.
1479     unsigned Opc;
1480     switch (MI->getOpcode()) {
1481     default: assert(0 && "illegal opcode!");
1482     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
1483     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
1484     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
1485     }
1486
1487     X86AddressMode AM;
1488     MachineOperand &Op = MI->getOperand(0);
1489     if (Op.isRegister()) {
1490       AM.BaseType = X86AddressMode::RegBase;
1491       AM.Base.Reg = Op.getReg();
1492     } else {
1493       AM.BaseType = X86AddressMode::FrameIndexBase;
1494       AM.Base.FrameIndex = Op.getFrameIndex();
1495     }
1496     Op = MI->getOperand(1);
1497     if (Op.isImmediate())
1498       AM.Scale = Op.getImmedValue();
1499     Op = MI->getOperand(2);
1500     if (Op.isImmediate())
1501       AM.IndexReg = Op.getImmedValue();
1502     Op = MI->getOperand(3);
1503     if (Op.isGlobalAddress()) {
1504       AM.GV = Op.getGlobal();
1505     } else {
1506       AM.Disp = Op.getImmedValue();
1507     }
1508     addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(MI->getOperand(4).getReg());
1509
1510     // Reload the original control word now.
1511     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1512
1513     delete MI;   // The pseudo instruction is gone now.
1514     return BB;
1515   }
1516   }
1517 }
1518
1519
1520 //===----------------------------------------------------------------------===//
1521 //                           X86 Custom Lowering Hooks
1522 //===----------------------------------------------------------------------===//
1523
1524 /// DarwinGVRequiresExtraLoad - true if accessing the GV requires an extra
1525 /// load. For Darwin, external and weak symbols are indirect, loading the value
1526 /// at address GV rather then the value of GV itself. This means that the
1527 /// GlobalAddress must be in the base or index register of the address, not the
1528 /// GV offset field.
1529 static bool DarwinGVRequiresExtraLoad(GlobalValue *GV) {
1530   return (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
1531           (GV->isExternal() && !GV->hasNotBeenReadFromBytecode()));
1532 }
1533
1534 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1535 /// true if Op is undef or if its value falls within the specified range (L, H].
1536 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1537   if (Op.getOpcode() == ISD::UNDEF)
1538     return true;
1539
1540   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1541   return (Val >= Low && Val < Hi);
1542 }
1543
1544 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
1545 /// true if Op is undef or if its value equal to the specified value.
1546 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1547   if (Op.getOpcode() == ISD::UNDEF)
1548     return true;
1549   return cast<ConstantSDNode>(Op)->getValue() == Val;
1550 }
1551
1552 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1553 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1554 bool X86::isPSHUFDMask(SDNode *N) {
1555   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1556
1557   if (N->getNumOperands() != 4)
1558     return false;
1559
1560   // Check if the value doesn't reference the second vector.
1561   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1562     SDOperand Arg = N->getOperand(i);
1563     if (Arg.getOpcode() == ISD::UNDEF) continue;
1564     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1565     if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1566       return false;
1567   }
1568
1569   return true;
1570 }
1571
1572 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1573 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1574 bool X86::isPSHUFHWMask(SDNode *N) {
1575   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1576
1577   if (N->getNumOperands() != 8)
1578     return false;
1579
1580   // Lower quadword copied in order.
1581   for (unsigned i = 0; i != 4; ++i) {
1582     SDOperand Arg = N->getOperand(i);
1583     if (Arg.getOpcode() == ISD::UNDEF) continue;
1584     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1585     if (cast<ConstantSDNode>(Arg)->getValue() != i)
1586       return false;
1587   }
1588
1589   // Upper quadword shuffled.
1590   for (unsigned i = 4; i != 8; ++i) {
1591     SDOperand Arg = N->getOperand(i);
1592     if (Arg.getOpcode() == ISD::UNDEF) continue;
1593     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1594     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1595     if (Val < 4 || Val > 7)
1596       return false;
1597   }
1598
1599   return true;
1600 }
1601
1602 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1603 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1604 bool X86::isPSHUFLWMask(SDNode *N) {
1605   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1606
1607   if (N->getNumOperands() != 8)
1608     return false;
1609
1610   // Upper quadword copied in order.
1611   for (unsigned i = 4; i != 8; ++i)
1612     if (!isUndefOrEqual(N->getOperand(i), i))
1613       return false;
1614
1615   // Lower quadword shuffled.
1616   for (unsigned i = 0; i != 4; ++i)
1617     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1618       return false;
1619
1620   return true;
1621 }
1622
1623 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1624 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
1625 static bool isSHUFPMask(std::vector<SDOperand> &N) {
1626   unsigned NumElems = N.size();
1627   if (NumElems != 2 && NumElems != 4) return false;
1628
1629   unsigned Half = NumElems / 2;
1630   for (unsigned i = 0; i < Half; ++i)
1631     if (!isUndefOrInRange(N[i], 0, NumElems))
1632       return false;
1633   for (unsigned i = Half; i < NumElems; ++i)
1634     if (!isUndefOrInRange(N[i], NumElems, NumElems*2))
1635       return false;
1636
1637   return true;
1638 }
1639
1640 bool X86::isSHUFPMask(SDNode *N) {
1641   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1642   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1643   return ::isSHUFPMask(Ops);
1644 }
1645
1646 /// isCommutedSHUFP - Returns true if the shuffle mask is except
1647 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1648 /// half elements to come from vector 1 (which would equal the dest.) and
1649 /// the upper half to come from vector 2.
1650 static bool isCommutedSHUFP(std::vector<SDOperand> &Ops) {
1651   unsigned NumElems = Ops.size();
1652   if (NumElems != 2 && NumElems != 4) return false;
1653
1654   unsigned Half = NumElems / 2;
1655   for (unsigned i = 0; i < Half; ++i)
1656     if (!isUndefOrInRange(Ops[i], NumElems, NumElems*2))
1657       return false;
1658   for (unsigned i = Half; i < NumElems; ++i)
1659     if (!isUndefOrInRange(Ops[i], 0, NumElems))
1660       return false;
1661   return true;
1662 }
1663
1664 static bool isCommutedSHUFP(SDNode *N) {
1665   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1666   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1667   return isCommutedSHUFP(Ops);
1668 }
1669
1670 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1671 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1672 bool X86::isMOVHLPSMask(SDNode *N) {
1673   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1674
1675   if (N->getNumOperands() != 4)
1676     return false;
1677
1678   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1679   return isUndefOrEqual(N->getOperand(0), 6) &&
1680          isUndefOrEqual(N->getOperand(1), 7) &&
1681          isUndefOrEqual(N->getOperand(2), 2) &&
1682          isUndefOrEqual(N->getOperand(3), 3);
1683 }
1684
1685 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1686 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1687 bool X86::isMOVLPMask(SDNode *N) {
1688   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1689
1690   unsigned NumElems = N->getNumOperands();
1691   if (NumElems != 2 && NumElems != 4)
1692     return false;
1693
1694   for (unsigned i = 0; i < NumElems/2; ++i)
1695     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1696       return false;
1697
1698   for (unsigned i = NumElems/2; i < NumElems; ++i)
1699     if (!isUndefOrEqual(N->getOperand(i), i))
1700       return false;
1701
1702   return true;
1703 }
1704
1705 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1706 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1707 /// and MOVLHPS.
1708 bool X86::isMOVHPMask(SDNode *N) {
1709   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1710
1711   unsigned NumElems = N->getNumOperands();
1712   if (NumElems != 2 && NumElems != 4)
1713     return false;
1714
1715   for (unsigned i = 0; i < NumElems/2; ++i)
1716     if (!isUndefOrEqual(N->getOperand(i), i))
1717       return false;
1718
1719   for (unsigned i = 0; i < NumElems/2; ++i) {
1720     SDOperand Arg = N->getOperand(i + NumElems/2);
1721     if (!isUndefOrEqual(Arg, i + NumElems))
1722       return false;
1723   }
1724
1725   return true;
1726 }
1727
1728 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1729 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
1730 bool static isUNPCKLMask(std::vector<SDOperand> &N, bool V2IsSplat = false) {
1731   unsigned NumElems = N.size();
1732   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1733     return false;
1734
1735   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1736     SDOperand BitI  = N[i];
1737     SDOperand BitI1 = N[i+1];
1738     if (!isUndefOrEqual(BitI, j))
1739       return false;
1740     if (V2IsSplat) {
1741       if (isUndefOrEqual(BitI1, NumElems))
1742         return false;
1743     } else {
1744       if (!isUndefOrEqual(BitI1, j + NumElems))
1745         return false;
1746     }
1747   }
1748
1749   return true;
1750 }
1751
1752 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1753   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1754   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1755   return ::isUNPCKLMask(Ops, V2IsSplat);
1756 }
1757
1758 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1759 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
1760 bool static isUNPCKHMask(std::vector<SDOperand> &N, bool V2IsSplat = false) {
1761   unsigned NumElems = N.size();
1762   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1763     return false;
1764
1765   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1766     SDOperand BitI  = N[i];
1767     SDOperand BitI1 = N[i+1];
1768     if (!isUndefOrEqual(BitI, j + NumElems/2))
1769       return false;
1770     if (V2IsSplat) {
1771       if (isUndefOrEqual(BitI1, NumElems))
1772         return false;
1773     } else {
1774       if (!isUndefOrEqual(BitI1, j + NumElems/2 + NumElems))
1775         return false;
1776     }
1777   }
1778
1779   return true;
1780 }
1781
1782 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1783   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1784   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1785   return ::isUNPCKHMask(Ops, V2IsSplat);
1786 }
1787
1788 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1789 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1790 /// <0, 0, 1, 1>
1791 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1792   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1793
1794   unsigned NumElems = N->getNumOperands();
1795   if (NumElems != 4 && NumElems != 8 && NumElems != 16)
1796     return false;
1797
1798   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1799     SDOperand BitI  = N->getOperand(i);
1800     SDOperand BitI1 = N->getOperand(i+1);
1801
1802     if (!isUndefOrEqual(BitI, j))
1803       return false;
1804     if (!isUndefOrEqual(BitI1, j))
1805       return false;
1806   }
1807
1808   return true;
1809 }
1810
1811 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1812 /// specifies a shuffle of elements that is suitable for input to MOVSS,
1813 /// MOVSD, and MOVD, i.e. setting the lowest element.
1814 static bool isMOVLMask(std::vector<SDOperand> &N) {
1815   unsigned NumElems = N.size();
1816   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1817     return false;
1818
1819   if (!isUndefOrEqual(N[0], NumElems))
1820     return false;
1821
1822   for (unsigned i = 1; i < NumElems; ++i) {
1823     SDOperand Arg = N[i];
1824     if (!isUndefOrEqual(Arg, i))
1825       return false;
1826   }
1827
1828   return true;
1829 }
1830
1831 bool X86::isMOVLMask(SDNode *N) {
1832   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1833   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1834   return ::isMOVLMask(Ops);
1835 }
1836
1837 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1838 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
1839 /// element of vector 2 and the other elements to come from vector 1 in order.
1840 static bool isCommutedMOVL(std::vector<SDOperand> &Ops, bool V2IsSplat = false) {
1841   unsigned NumElems = Ops.size();
1842   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1843     return false;
1844
1845   if (!isUndefOrEqual(Ops[0], 0))
1846     return false;
1847
1848   for (unsigned i = 1; i < NumElems; ++i) {
1849     SDOperand Arg = Ops[i];
1850     if (V2IsSplat) {
1851       if (!isUndefOrEqual(Arg, NumElems))
1852         return false;
1853     } else {
1854       if (!isUndefOrEqual(Arg, i+NumElems))
1855         return false;
1856     }
1857   }
1858
1859   return true;
1860 }
1861
1862 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false) {
1863   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1864   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1865   return isCommutedMOVL(Ops, V2IsSplat);
1866 }
1867
1868 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1869 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1870 bool X86::isMOVSHDUPMask(SDNode *N) {
1871   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1872
1873   if (N->getNumOperands() != 4)
1874     return false;
1875
1876   // Expect 1, 1, 3, 3
1877   for (unsigned i = 0; i < 2; ++i) {
1878     SDOperand Arg = N->getOperand(i);
1879     if (Arg.getOpcode() == ISD::UNDEF) continue;
1880     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1881     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1882     if (Val != 1) return false;
1883   }
1884
1885   bool HasHi = false;
1886   for (unsigned i = 2; i < 4; ++i) {
1887     SDOperand Arg = N->getOperand(i);
1888     if (Arg.getOpcode() == ISD::UNDEF) continue;
1889     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1890     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1891     if (Val != 3) return false;
1892     HasHi = true;
1893   }
1894
1895   // Don't use movshdup if it can be done with a shufps.
1896   return HasHi;
1897 }
1898
1899 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1900 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1901 bool X86::isMOVSLDUPMask(SDNode *N) {
1902   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1903
1904   if (N->getNumOperands() != 4)
1905     return false;
1906
1907   // Expect 0, 0, 2, 2
1908   for (unsigned i = 0; i < 2; ++i) {
1909     SDOperand Arg = N->getOperand(i);
1910     if (Arg.getOpcode() == ISD::UNDEF) continue;
1911     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1912     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1913     if (Val != 0) return false;
1914   }
1915
1916   bool HasHi = false;
1917   for (unsigned i = 2; i < 4; ++i) {
1918     SDOperand Arg = N->getOperand(i);
1919     if (Arg.getOpcode() == ISD::UNDEF) continue;
1920     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1921     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1922     if (Val != 2) return false;
1923     HasHi = true;
1924   }
1925
1926   // Don't use movshdup if it can be done with a shufps.
1927   return HasHi;
1928 }
1929
1930 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1931 /// a splat of a single element.
1932 static bool isSplatMask(SDNode *N) {
1933   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1934
1935   // This is a splat operation if each element of the permute is the same, and
1936   // if the value doesn't reference the second vector.
1937   unsigned NumElems = N->getNumOperands();
1938   SDOperand ElementBase;
1939   unsigned i = 0;
1940   for (; i != NumElems; ++i) {
1941     SDOperand Elt = N->getOperand(i);
1942     if (ConstantSDNode *EltV = dyn_cast<ConstantSDNode>(Elt)) {
1943       ElementBase = Elt;
1944       break;
1945     }
1946   }
1947
1948   if (!ElementBase.Val)
1949     return false;
1950
1951   for (; i != NumElems; ++i) {
1952     SDOperand Arg = N->getOperand(i);
1953     if (Arg.getOpcode() == ISD::UNDEF) continue;
1954     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1955     if (Arg != ElementBase) return false;
1956   }
1957
1958   // Make sure it is a splat of the first vector operand.
1959   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
1960 }
1961
1962 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1963 /// a splat of a single element and it's a 2 or 4 element mask.
1964 bool X86::isSplatMask(SDNode *N) {
1965   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1966
1967   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
1968   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
1969     return false;
1970   return ::isSplatMask(N);
1971 }
1972
1973 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
1974 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
1975 /// instructions.
1976 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
1977   unsigned NumOperands = N->getNumOperands();
1978   unsigned Shift = (NumOperands == 4) ? 2 : 1;
1979   unsigned Mask = 0;
1980   for (unsigned i = 0; i < NumOperands; ++i) {
1981     unsigned Val = 0;
1982     SDOperand Arg = N->getOperand(NumOperands-i-1);
1983     if (Arg.getOpcode() != ISD::UNDEF)
1984       Val = cast<ConstantSDNode>(Arg)->getValue();
1985     if (Val >= NumOperands) Val -= NumOperands;
1986     Mask |= Val;
1987     if (i != NumOperands - 1)
1988       Mask <<= Shift;
1989   }
1990
1991   return Mask;
1992 }
1993
1994 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
1995 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
1996 /// instructions.
1997 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
1998   unsigned Mask = 0;
1999   // 8 nodes, but we only care about the last 4.
2000   for (unsigned i = 7; i >= 4; --i) {
2001     unsigned Val = 0;
2002     SDOperand Arg = N->getOperand(i);
2003     if (Arg.getOpcode() != ISD::UNDEF)
2004       Val = cast<ConstantSDNode>(Arg)->getValue();
2005     Mask |= (Val - 4);
2006     if (i != 4)
2007       Mask <<= 2;
2008   }
2009
2010   return Mask;
2011 }
2012
2013 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2014 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2015 /// instructions.
2016 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2017   unsigned Mask = 0;
2018   // 8 nodes, but we only care about the first 4.
2019   for (int i = 3; i >= 0; --i) {
2020     unsigned Val = 0;
2021     SDOperand Arg = N->getOperand(i);
2022     if (Arg.getOpcode() != ISD::UNDEF)
2023       Val = cast<ConstantSDNode>(Arg)->getValue();
2024     Mask |= Val;
2025     if (i != 0)
2026       Mask <<= 2;
2027   }
2028
2029   return Mask;
2030 }
2031
2032 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2033 /// specifies a 8 element shuffle that can be broken into a pair of
2034 /// PSHUFHW and PSHUFLW.
2035 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2036   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2037
2038   if (N->getNumOperands() != 8)
2039     return false;
2040
2041   // Lower quadword shuffled.
2042   for (unsigned i = 0; i != 4; ++i) {
2043     SDOperand Arg = N->getOperand(i);
2044     if (Arg.getOpcode() == ISD::UNDEF) continue;
2045     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2046     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2047     if (Val > 4)
2048       return false;
2049   }
2050
2051   // Upper quadword shuffled.
2052   for (unsigned i = 4; i != 8; ++i) {
2053     SDOperand Arg = N->getOperand(i);
2054     if (Arg.getOpcode() == ISD::UNDEF) continue;
2055     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2056     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2057     if (Val < 4 || Val > 7)
2058       return false;
2059   }
2060
2061   return true;
2062 }
2063
2064 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2065 /// values in ther permute mask.
2066 static SDOperand CommuteVectorShuffle(SDOperand Op, SelectionDAG &DAG) {
2067   SDOperand V1 = Op.getOperand(0);
2068   SDOperand V2 = Op.getOperand(1);
2069   SDOperand Mask = Op.getOperand(2);
2070   MVT::ValueType VT = Op.getValueType();
2071   MVT::ValueType MaskVT = Mask.getValueType();
2072   MVT::ValueType EltVT = MVT::getVectorBaseType(MaskVT);
2073   unsigned NumElems = Mask.getNumOperands();
2074   std::vector<SDOperand> MaskVec;
2075
2076   for (unsigned i = 0; i != NumElems; ++i) {
2077     SDOperand Arg = Mask.getOperand(i);
2078     if (Arg.getOpcode() == ISD::UNDEF) {
2079       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2080       continue;
2081     }
2082     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2083     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2084     if (Val < NumElems)
2085       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2086     else
2087       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2088   }
2089
2090   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2091   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1, Mask);
2092 }
2093
2094 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2095 /// match movhlps. The lower half elements should come from upper half of
2096 /// V1 (and in order), and the upper half elements should come from the upper
2097 /// half of V2 (and in order). 
2098 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2099   unsigned NumElems = Mask->getNumOperands();
2100   if (NumElems != 4)
2101     return false;
2102   for (unsigned i = 0, e = 2; i != e; ++i)
2103     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2104       return false;
2105   for (unsigned i = 2; i != 4; ++i)
2106     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2107       return false;
2108   return true;
2109 }
2110
2111 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2112 /// is promoted to a vector.
2113 static inline bool isScalarLoadToVector(SDNode *N) {
2114   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2115     N = N->getOperand(0).Val;
2116     return (N->getOpcode() == ISD::LOAD);
2117   }
2118   return false;
2119 }
2120
2121 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2122 /// match movlp{s|d}. The lower half elements should come from lower half of
2123 /// V1 (and in order), and the upper half elements should come from the upper
2124 /// half of V2 (and in order). And since V1 will become the source of the
2125 /// MOVLP, it must be either a vector load or a scalar load to vector.
2126 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *Mask) {
2127   if (V1->getOpcode() != ISD::LOAD && !isScalarLoadToVector(V1))
2128     return false;
2129
2130   unsigned NumElems = Mask->getNumOperands();
2131   if (NumElems != 2 && NumElems != 4)
2132     return false;
2133   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2134     if (!isUndefOrEqual(Mask->getOperand(i), i))
2135       return false;
2136   for (unsigned i = NumElems/2; i != NumElems; ++i)
2137     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2138       return false;
2139   return true;
2140 }
2141
2142 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2143 /// all the same.
2144 static bool isSplatVector(SDNode *N) {
2145   if (N->getOpcode() != ISD::BUILD_VECTOR)
2146     return false;
2147
2148   SDOperand SplatValue = N->getOperand(0);
2149   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2150     if (N->getOperand(i) != SplatValue)
2151       return false;
2152   return true;
2153 }
2154
2155 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2156 /// that point to V2 points to its first element.
2157 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2158   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2159
2160   bool Changed = false;
2161   std::vector<SDOperand> MaskVec;
2162   unsigned NumElems = Mask.getNumOperands();
2163   for (unsigned i = 0; i != NumElems; ++i) {
2164     SDOperand Arg = Mask.getOperand(i);
2165     if (Arg.getOpcode() != ISD::UNDEF) {
2166       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2167       if (Val > NumElems) {
2168         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2169         Changed = true;
2170       }
2171     }
2172     MaskVec.push_back(Arg);
2173   }
2174
2175   if (Changed)
2176     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(), MaskVec);
2177   return Mask;
2178 }
2179
2180 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2181 /// operation of specified width.
2182 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2183   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2184   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2185
2186   std::vector<SDOperand> MaskVec;
2187   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2188   for (unsigned i = 1; i != NumElems; ++i)
2189     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2190   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2191 }
2192
2193 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2194 /// of specified width.
2195 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2196   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2197   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2198   std::vector<SDOperand> MaskVec;
2199   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2200     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2201     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2202   }
2203   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2204 }
2205
2206 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2207 /// of specified width.
2208 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2209   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2210   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2211   unsigned Half = NumElems/2;
2212   std::vector<SDOperand> MaskVec;
2213   for (unsigned i = 0; i != Half; ++i) {
2214     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2215     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2216   }
2217   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2218 }
2219
2220 /// getZeroVector - Returns a vector of specified type with all zero elements.
2221 ///
2222 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2223   assert(MVT::isVector(VT) && "Expected a vector type");
2224   unsigned NumElems = getVectorNumElements(VT);
2225   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2226   bool isFP = MVT::isFloatingPoint(EVT);
2227   SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2228   std::vector<SDOperand> ZeroVec(NumElems, Zero);
2229   return DAG.getNode(ISD::BUILD_VECTOR, VT, ZeroVec);
2230 }
2231
2232 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2233 ///
2234 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2235   SDOperand V1 = Op.getOperand(0);
2236   SDOperand Mask = Op.getOperand(2);
2237   MVT::ValueType VT = Op.getValueType();
2238   unsigned NumElems = Mask.getNumOperands();
2239   Mask = getUnpacklMask(NumElems, DAG);
2240   while (NumElems != 4) {
2241     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2242     NumElems >>= 1;
2243   }
2244   V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2245
2246   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2247   Mask = getZeroVector(MaskVT, DAG);
2248   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2249                                   DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2250   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2251 }
2252
2253 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2254 /// constant +0.0.
2255 static inline bool isZeroNode(SDOperand Elt) {
2256   return ((isa<ConstantSDNode>(Elt) &&
2257            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2258           (isa<ConstantFPSDNode>(Elt) &&
2259            cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2260 }
2261
2262 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2263 /// vector and zero or undef vector.
2264 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2265                                              unsigned NumElems, unsigned Idx,
2266                                              bool isZero, SelectionDAG &DAG) {
2267   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2268   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2269   MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2270   SDOperand Zero = DAG.getConstant(0, EVT);
2271   std::vector<SDOperand> MaskVec(NumElems, Zero);
2272   MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2273   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2274   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2275 }
2276
2277 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2278 ///
2279 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2280                                        unsigned NumNonZero, unsigned NumZero,
2281                                        SelectionDAG &DAG) {
2282   if (NumNonZero > 8)
2283     return SDOperand();
2284
2285   SDOperand V(0, 0);
2286   bool First = true;
2287   for (unsigned i = 0; i < 16; ++i) {
2288     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2289     if (ThisIsNonZero && First) {
2290       if (NumZero)
2291         V = getZeroVector(MVT::v8i16, DAG);
2292       else
2293         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2294       First = false;
2295     }
2296
2297     if ((i & 1) != 0) {
2298       SDOperand ThisElt(0, 0), LastElt(0, 0);
2299       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2300       if (LastIsNonZero) {
2301         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2302       }
2303       if (ThisIsNonZero) {
2304         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2305         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2306                               ThisElt, DAG.getConstant(8, MVT::i8));
2307         if (LastIsNonZero)
2308           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2309       } else
2310         ThisElt = LastElt;
2311
2312       if (ThisElt.Val)
2313         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2314                         DAG.getConstant(i/2, MVT::i32));
2315     }
2316   }
2317
2318   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2319 }
2320
2321 /// LowerBuildVectorv16i8 - Custom lower build_vector of v8i16.
2322 ///
2323 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2324                                        unsigned NumNonZero, unsigned NumZero,
2325                                        SelectionDAG &DAG) {
2326   if (NumNonZero > 4)
2327     return SDOperand();
2328
2329   SDOperand V(0, 0);
2330   bool First = true;
2331   for (unsigned i = 0; i < 8; ++i) {
2332     bool isNonZero = (NonZeros & (1 << i)) != 0;
2333     if (isNonZero) {
2334       if (First) {
2335         if (NumZero)
2336           V = getZeroVector(MVT::v8i16, DAG);
2337         else
2338           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2339         First = false;
2340       }
2341       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2342                       DAG.getConstant(i, MVT::i32));
2343     }
2344   }
2345
2346   return V;
2347 }
2348
2349 SDOperand
2350 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2351   // All zero's are handled with pxor.
2352   if (ISD::isBuildVectorAllZeros(Op.Val))
2353     return Op;
2354
2355   // All one's are handled with pcmpeqd.
2356   if (ISD::isBuildVectorAllOnes(Op.Val))
2357     return Op;
2358
2359   MVT::ValueType VT = Op.getValueType();
2360   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2361   unsigned EVTBits = MVT::getSizeInBits(EVT);
2362
2363   unsigned NumElems = Op.getNumOperands();
2364   unsigned NumZero  = 0;
2365   unsigned NumNonZero = 0;
2366   unsigned NonZeros = 0;
2367   std::set<SDOperand> Values;
2368   for (unsigned i = 0; i < NumElems; ++i) {
2369     SDOperand Elt = Op.getOperand(i);
2370     if (Elt.getOpcode() != ISD::UNDEF) {
2371       Values.insert(Elt);
2372       if (isZeroNode(Elt))
2373         NumZero++;
2374       else {
2375         NonZeros |= (1 << i);
2376         NumNonZero++;
2377       }
2378     }
2379   }
2380
2381   if (NumNonZero == 0)
2382     // Must be a mix of zero and undef. Return a zero vector.
2383     return getZeroVector(VT, DAG);
2384
2385   // Splat is obviously ok. Let legalizer expand it to a shuffle.
2386   if (Values.size() == 1)
2387     return SDOperand();
2388
2389   // Special case for single non-zero element.
2390   if (NumNonZero == 1) {
2391     unsigned Idx = CountTrailingZeros_32(NonZeros);
2392     SDOperand Item = Op.getOperand(Idx);
2393     Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2394     if (Idx == 0)
2395       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2396       return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2397                                          NumZero > 0, DAG);
2398
2399     if (EVTBits == 32) {
2400       // Turn it into a shuffle of zero and zero-extended scalar to vector.
2401       Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2402                                          DAG);
2403       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
2404       MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2405       std::vector<SDOperand> MaskVec;
2406       for (unsigned i = 0; i < NumElems; i++)
2407         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2408       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2409       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2410                          DAG.getNode(ISD::UNDEF, VT), Mask);
2411     }
2412   }
2413
2414   // Let legalizer expand 2-widde build_vector's.
2415   if (EVTBits == 64)
2416     return SDOperand();
2417
2418   // If element VT is < 32 bits, convert it to inserts into a zero vector.
2419   if (EVTBits == 8) {
2420     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG);
2421     if (V.Val) return V;
2422   }
2423
2424   if (EVTBits == 16) {
2425     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG);
2426     if (V.Val) return V;
2427   }
2428
2429   // If element VT is == 32 bits, turn it into a number of shuffles.
2430   std::vector<SDOperand> V(NumElems);
2431   if (NumElems == 4 && NumZero > 0) {
2432     for (unsigned i = 0; i < 4; ++i) {
2433       bool isZero = !(NonZeros & (1 << i));
2434       if (isZero)
2435         V[i] = getZeroVector(VT, DAG);
2436       else
2437         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2438     }
2439
2440     for (unsigned i = 0; i < 2; ++i) {
2441       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2442         default: break;
2443         case 0:
2444           V[i] = V[i*2];  // Must be a zero vector.
2445           break;
2446         case 1:
2447           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2448                              getMOVLMask(NumElems, DAG));
2449           break;
2450         case 2:
2451           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2452                              getMOVLMask(NumElems, DAG));
2453           break;
2454         case 3:
2455           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2456                              getUnpacklMask(NumElems, DAG));
2457           break;
2458       }
2459     }
2460
2461     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2462     // clears the upper bits. 
2463     // FIXME: we can do the same for v4f32 case when we know both parts of
2464     // the lower half come from scalar_to_vector (loadf32). We should do
2465     // that in post legalizer dag combiner with target specific hooks.
2466     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2467       return V[0];
2468     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2469     MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2470     std::vector<SDOperand> MaskVec;
2471     bool Reverse = (NonZeros & 0x3) == 2;
2472     for (unsigned i = 0; i < 2; ++i)
2473       if (Reverse)
2474         MaskVec.push_back(DAG.getConstant(1-i, EVT));
2475       else
2476         MaskVec.push_back(DAG.getConstant(i, EVT));
2477     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2478     for (unsigned i = 0; i < 2; ++i)
2479       if (Reverse)
2480         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2481       else
2482         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2483     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2484     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2485   }
2486
2487   if (Values.size() > 2) {
2488     // Expand into a number of unpckl*.
2489     // e.g. for v4f32
2490     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2491     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2492     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
2493     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2494     for (unsigned i = 0; i < NumElems; ++i)
2495       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2496     NumElems >>= 1;
2497     while (NumElems != 0) {
2498       for (unsigned i = 0; i < NumElems; ++i)
2499         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2500                            UnpckMask);
2501       NumElems >>= 1;
2502     }
2503     return V[0];
2504   }
2505
2506   return SDOperand();
2507 }
2508
2509 SDOperand
2510 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2511   SDOperand V1 = Op.getOperand(0);
2512   SDOperand V2 = Op.getOperand(1);
2513   SDOperand PermMask = Op.getOperand(2);
2514   MVT::ValueType VT = Op.getValueType();
2515   unsigned NumElems = PermMask.getNumOperands();
2516   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2517   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2518
2519   if (isSplatMask(PermMask.Val)) {
2520     if (NumElems <= 4) return Op;
2521     // Promote it to a v4i32 splat.
2522     return PromoteSplat(Op, DAG);
2523   }
2524
2525   if (X86::isMOVLMask(PermMask.Val))
2526     return (V1IsUndef) ? V2 : Op;
2527       
2528   if (X86::isMOVSHDUPMask(PermMask.Val) ||
2529       X86::isMOVSLDUPMask(PermMask.Val) ||
2530       X86::isMOVHLPSMask(PermMask.Val) ||
2531       X86::isMOVHPMask(PermMask.Val) ||
2532       X86::isMOVLPMask(PermMask.Val))
2533     return Op;
2534
2535   if (ShouldXformToMOVHLPS(PermMask.Val) ||
2536       ShouldXformToMOVLP(V1.Val, PermMask.Val))
2537     return CommuteVectorShuffle(Op, DAG);
2538
2539   bool V1IsSplat = isSplatVector(V1.Val) || V1.getOpcode() == ISD::UNDEF;
2540   bool V2IsSplat = isSplatVector(V2.Val) || V2.getOpcode() == ISD::UNDEF;
2541   if (V1IsSplat && !V2IsSplat) {
2542     Op = CommuteVectorShuffle(Op, DAG);
2543     V1 = Op.getOperand(0);
2544     V2 = Op.getOperand(1);
2545     PermMask = Op.getOperand(2);
2546     V2IsSplat = true;
2547   }
2548
2549   if (isCommutedMOVL(PermMask.Val, V2IsSplat)) {
2550     if (V2IsUndef) return V1;
2551     Op = CommuteVectorShuffle(Op, DAG);
2552     V1 = Op.getOperand(0);
2553     V2 = Op.getOperand(1);
2554     PermMask = Op.getOperand(2);
2555     if (V2IsSplat) {
2556       // V2 is a splat, so the mask may be malformed. That is, it may point
2557       // to any V2 element. The instruction selectior won't like this. Get
2558       // a corrected mask and commute to form a proper MOVS{S|D}.
2559       SDOperand NewMask = getMOVLMask(NumElems, DAG);
2560       if (NewMask.Val != PermMask.Val)
2561         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2562     }
2563     return Op;
2564   }
2565
2566   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2567       X86::isUNPCKLMask(PermMask.Val) ||
2568       X86::isUNPCKHMask(PermMask.Val))
2569     return Op;
2570
2571   if (V2IsSplat) {
2572     // Normalize mask so all entries that point to V2 points to its first
2573     // element then try to match unpck{h|l} again. If match, return a 
2574     // new vector_shuffle with the corrected mask.
2575     SDOperand NewMask = NormalizeMask(PermMask, DAG);
2576     if (NewMask.Val != PermMask.Val) {
2577       if (X86::isUNPCKLMask(PermMask.Val, true)) {
2578         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2579         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2580       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2581         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2582         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2583       }
2584     }
2585   }
2586
2587   // Normalize the node to match x86 shuffle ops if needed
2588   if (V2.getOpcode() != ISD::UNDEF)
2589     if (isCommutedSHUFP(PermMask.Val)) {
2590       Op = CommuteVectorShuffle(Op, DAG);
2591       V1 = Op.getOperand(0);
2592       V2 = Op.getOperand(1);
2593       PermMask = Op.getOperand(2);
2594     }
2595
2596   // If VT is integer, try PSHUF* first, then SHUFP*.
2597   if (MVT::isInteger(VT)) {
2598     if (X86::isPSHUFDMask(PermMask.Val) ||
2599         X86::isPSHUFHWMask(PermMask.Val) ||
2600         X86::isPSHUFLWMask(PermMask.Val)) {
2601       if (V2.getOpcode() != ISD::UNDEF)
2602         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2603                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2604       return Op;
2605     }
2606
2607     if (X86::isSHUFPMask(PermMask.Val))
2608       return Op;
2609
2610     // Handle v8i16 shuffle high / low shuffle node pair.
2611     if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2612       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2613       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2614       std::vector<SDOperand> MaskVec;
2615       for (unsigned i = 0; i != 4; ++i)
2616         MaskVec.push_back(PermMask.getOperand(i));
2617       for (unsigned i = 4; i != 8; ++i)
2618         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2619       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2620       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2621       MaskVec.clear();
2622       for (unsigned i = 0; i != 4; ++i)
2623         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2624       for (unsigned i = 4; i != 8; ++i)
2625         MaskVec.push_back(PermMask.getOperand(i));
2626       Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2627       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2628     }
2629   } else {
2630     // Floating point cases in the other order.
2631     if (X86::isSHUFPMask(PermMask.Val))
2632       return Op;
2633     if (X86::isPSHUFDMask(PermMask.Val) ||
2634         X86::isPSHUFHWMask(PermMask.Val) ||
2635         X86::isPSHUFLWMask(PermMask.Val)) {
2636       if (V2.getOpcode() != ISD::UNDEF)
2637         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2638                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2639       return Op;
2640     }
2641   }
2642
2643   if (NumElems == 4) {
2644     MVT::ValueType MaskVT = PermMask.getValueType();
2645     MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2646     std::vector<std::pair<int, int> > Locs;
2647     Locs.reserve(NumElems);
2648     std::vector<SDOperand> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2649     std::vector<SDOperand> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2650     unsigned NumHi = 0;
2651     unsigned NumLo = 0;
2652     // If no more than two elements come from either vector. This can be
2653     // implemented with two shuffles. First shuffle gather the elements.
2654     // The second shuffle, which takes the first shuffle as both of its
2655     // vector operands, put the elements into the right order.
2656     for (unsigned i = 0; i != NumElems; ++i) {
2657       SDOperand Elt = PermMask.getOperand(i);
2658       if (Elt.getOpcode() == ISD::UNDEF) {
2659         Locs[i] = std::make_pair(-1, -1);
2660       } else {
2661         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2662         if (Val < NumElems) {
2663           Locs[i] = std::make_pair(0, NumLo);
2664           Mask1[NumLo] = Elt;
2665           NumLo++;
2666         } else {
2667           Locs[i] = std::make_pair(1, NumHi);
2668           if (2+NumHi < NumElems)
2669             Mask1[2+NumHi] = Elt;
2670           NumHi++;
2671         }
2672       }
2673     }
2674     if (NumLo <= 2 && NumHi <= 2) {
2675       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2676                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT, Mask1));
2677       for (unsigned i = 0; i != NumElems; ++i) {
2678         if (Locs[i].first == -1)
2679           continue;
2680         else {
2681           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2682           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2683           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2684         }
2685       }
2686
2687       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2688                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, Mask2));
2689     }
2690
2691     // Break it into (shuffle shuffle_hi, shuffle_lo).
2692     Locs.clear();
2693     std::vector<SDOperand> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2694     std::vector<SDOperand> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2695     std::vector<SDOperand> *MaskPtr = &LoMask;
2696     unsigned MaskIdx = 0;
2697     unsigned LoIdx = 0;
2698     unsigned HiIdx = NumElems/2;
2699     for (unsigned i = 0; i != NumElems; ++i) {
2700       if (i == NumElems/2) {
2701         MaskPtr = &HiMask;
2702         MaskIdx = 1;
2703         LoIdx = 0;
2704         HiIdx = NumElems/2;
2705       }
2706       SDOperand Elt = PermMask.getOperand(i);
2707       if (Elt.getOpcode() == ISD::UNDEF) {
2708         Locs[i] = std::make_pair(-1, -1);
2709       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2710         Locs[i] = std::make_pair(MaskIdx, LoIdx);
2711         (*MaskPtr)[LoIdx] = Elt;
2712         LoIdx++;
2713       } else {
2714         Locs[i] = std::make_pair(MaskIdx, HiIdx);
2715         (*MaskPtr)[HiIdx] = Elt;
2716         HiIdx++;
2717       }
2718     }
2719
2720     SDOperand LoShuffle =
2721       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2722                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT, LoMask));
2723     SDOperand HiShuffle = 
2724       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2725                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT, HiMask));
2726     std::vector<SDOperand> MaskOps;
2727     for (unsigned i = 0; i != NumElems; ++i) {
2728       if (Locs[i].first == -1) {
2729         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2730       } else {
2731         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2732         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2733       }
2734     }
2735     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2736                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskOps));
2737   }
2738
2739   return SDOperand();
2740 }
2741
2742 SDOperand
2743 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2744   if (!isa<ConstantSDNode>(Op.getOperand(1)))
2745     return SDOperand();
2746
2747   MVT::ValueType VT = Op.getValueType();
2748   // TODO: handle v16i8.
2749   if (MVT::getSizeInBits(VT) == 16) {
2750     // Transform it so it match pextrw which produces a 32-bit result.
2751     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2752     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2753                                     Op.getOperand(0), Op.getOperand(1));
2754     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
2755                                     DAG.getValueType(VT));
2756     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2757   } else if (MVT::getSizeInBits(VT) == 32) {
2758     SDOperand Vec = Op.getOperand(0);
2759     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2760     if (Idx == 0)
2761       return Op;
2762     // SHUFPS the element to the lowest double word, then movss.
2763     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2764     std::vector<SDOperand> IdxVec;
2765     IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorBaseType(MaskVT)));
2766     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2767     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2768     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2769     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, IdxVec);
2770     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2771                       Vec, Vec, Mask);
2772     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2773                        DAG.getConstant(0, MVT::i32));
2774   } else if (MVT::getSizeInBits(VT) == 64) {
2775     SDOperand Vec = Op.getOperand(0);
2776     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2777     if (Idx == 0)
2778       return Op;
2779
2780     // UNPCKHPD the element to the lowest double word, then movsd.
2781     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2782     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2783     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2784     std::vector<SDOperand> IdxVec;
2785     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorBaseType(MaskVT)));
2786     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2787     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, IdxVec);
2788     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2789                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2790     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2791                        DAG.getConstant(0, MVT::i32));
2792   }
2793
2794   return SDOperand();
2795 }
2796
2797 SDOperand
2798 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2799   // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2800   // as its second argument.
2801   MVT::ValueType VT = Op.getValueType();
2802   MVT::ValueType BaseVT = MVT::getVectorBaseType(VT);
2803   SDOperand N0 = Op.getOperand(0);
2804   SDOperand N1 = Op.getOperand(1);
2805   SDOperand N2 = Op.getOperand(2);
2806   if (MVT::getSizeInBits(BaseVT) == 16) {
2807     if (N1.getValueType() != MVT::i32)
2808       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2809     if (N2.getValueType() != MVT::i32)
2810       N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(), MVT::i32);
2811     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2812   } else if (MVT::getSizeInBits(BaseVT) == 32) {
2813     unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2814     if (Idx == 0) {
2815       // Use a movss.
2816       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
2817       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2818       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2819       std::vector<SDOperand> MaskVec;
2820       MaskVec.push_back(DAG.getConstant(4, BaseVT));
2821       for (unsigned i = 1; i <= 3; ++i)
2822         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2823       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
2824                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec));
2825     } else {
2826       // Use two pinsrw instructions to insert a 32 bit value.
2827       Idx <<= 1;
2828       if (MVT::isFloatingPoint(N1.getValueType())) {
2829         if (N1.getOpcode() == ISD::LOAD) {
2830           // Just load directly from f32mem to GR32.
2831           N1 = DAG.getLoad(MVT::i32, N1.getOperand(0), N1.getOperand(1),
2832                            N1.getOperand(2));
2833         } else {
2834           N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
2835           N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
2836           N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
2837                            DAG.getConstant(0, MVT::i32));
2838         }
2839       }
2840       N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
2841       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2842                        DAG.getConstant(Idx, MVT::i32));
2843       N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
2844       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2845                        DAG.getConstant(Idx+1, MVT::i32));
2846       return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2847     }
2848   }
2849
2850   return SDOperand();
2851 }
2852
2853 SDOperand
2854 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2855   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
2856   return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
2857 }
2858
2859 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 
2860 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
2861 // one of the above mentioned nodes. It has to be wrapped because otherwise
2862 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2863 // be used to form addressing mode. These wrapped nodes will be selected
2864 // into MOV32ri.
2865 SDOperand
2866 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
2867   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2868   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2869                             DAG.getTargetConstantPool(CP->get(), getPointerTy(),
2870                                                       CP->getAlignment()));
2871   if (Subtarget->isTargetDarwin()) {
2872     // With PIC, the address is actually $g + Offset.
2873     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2874       Result = DAG.getNode(ISD::ADD, getPointerTy(),
2875                     DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()), Result);
2876   }
2877
2878   return Result;
2879 }
2880
2881 SDOperand
2882 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
2883   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2884   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2885                                  DAG.getTargetGlobalAddress(GV,
2886                                                             getPointerTy()));
2887   if (Subtarget->isTargetDarwin()) {
2888     // With PIC, the address is actually $g + Offset.
2889     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2890       Result = DAG.getNode(ISD::ADD, getPointerTy(),
2891                            DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2892                            Result);
2893
2894     // For Darwin, external and weak symbols are indirect, so we want to load
2895     // the value at address GV, not the value of GV itself. This means that
2896     // the GlobalAddress must be in the base or index register of the address,
2897     // not the GV offset field.
2898     if (getTargetMachine().getRelocationModel() != Reloc::Static &&
2899         DarwinGVRequiresExtraLoad(GV))
2900       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(),
2901                            Result, DAG.getSrcValue(NULL));
2902   }
2903
2904   return Result;
2905 }
2906
2907 SDOperand
2908 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
2909   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
2910   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2911                                  DAG.getTargetExternalSymbol(Sym,
2912                                                              getPointerTy()));
2913   if (Subtarget->isTargetDarwin()) {
2914     // With PIC, the address is actually $g + Offset.
2915     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2916       Result = DAG.getNode(ISD::ADD, getPointerTy(),
2917                            DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2918                            Result);
2919   }
2920
2921   return Result;
2922 }
2923
2924 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
2925     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
2926            "Not an i64 shift!");
2927     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
2928     SDOperand ShOpLo = Op.getOperand(0);
2929     SDOperand ShOpHi = Op.getOperand(1);
2930     SDOperand ShAmt  = Op.getOperand(2);
2931     SDOperand Tmp1 = isSRA ? DAG.getNode(ISD::SRA, MVT::i32, ShOpHi,
2932                                          DAG.getConstant(31, MVT::i8))
2933                            : DAG.getConstant(0, MVT::i32);
2934
2935     SDOperand Tmp2, Tmp3;
2936     if (Op.getOpcode() == ISD::SHL_PARTS) {
2937       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
2938       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
2939     } else {
2940       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
2941       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
2942     }
2943
2944     SDOperand InFlag = DAG.getNode(X86ISD::TEST, MVT::Flag,
2945                                    ShAmt, DAG.getConstant(32, MVT::i8));
2946
2947     SDOperand Hi, Lo;
2948     SDOperand CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
2949
2950     std::vector<MVT::ValueType> Tys;
2951     Tys.push_back(MVT::i32);
2952     Tys.push_back(MVT::Flag);
2953     std::vector<SDOperand> Ops;
2954     if (Op.getOpcode() == ISD::SHL_PARTS) {
2955       Ops.push_back(Tmp2);
2956       Ops.push_back(Tmp3);
2957       Ops.push_back(CC);
2958       Ops.push_back(InFlag);
2959       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2960       InFlag = Hi.getValue(1);
2961
2962       Ops.clear();
2963       Ops.push_back(Tmp3);
2964       Ops.push_back(Tmp1);
2965       Ops.push_back(CC);
2966       Ops.push_back(InFlag);
2967       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2968     } else {
2969       Ops.push_back(Tmp2);
2970       Ops.push_back(Tmp3);
2971       Ops.push_back(CC);
2972       Ops.push_back(InFlag);
2973       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2974       InFlag = Lo.getValue(1);
2975
2976       Ops.clear();
2977       Ops.push_back(Tmp3);
2978       Ops.push_back(Tmp1);
2979       Ops.push_back(CC);
2980       Ops.push_back(InFlag);
2981       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2982     }
2983
2984     Tys.clear();
2985     Tys.push_back(MVT::i32);
2986     Tys.push_back(MVT::i32);
2987     Ops.clear();
2988     Ops.push_back(Lo);
2989     Ops.push_back(Hi);
2990     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
2991 }
2992
2993 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
2994   assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
2995          Op.getOperand(0).getValueType() >= MVT::i16 &&
2996          "Unknown SINT_TO_FP to lower!");
2997
2998   SDOperand Result;
2999   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3000   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3001   MachineFunction &MF = DAG.getMachineFunction();
3002   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3003   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3004   SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other,
3005                                 DAG.getEntryNode(), Op.getOperand(0),
3006                                 StackSlot, DAG.getSrcValue(NULL));
3007
3008   // Build the FILD
3009   std::vector<MVT::ValueType> Tys;
3010   Tys.push_back(MVT::f64);
3011   Tys.push_back(MVT::Other);
3012   if (X86ScalarSSE) Tys.push_back(MVT::Flag);
3013   std::vector<SDOperand> Ops;
3014   Ops.push_back(Chain);
3015   Ops.push_back(StackSlot);
3016   Ops.push_back(DAG.getValueType(SrcVT));
3017   Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3018                        Tys, Ops);
3019
3020   if (X86ScalarSSE) {
3021     Chain = Result.getValue(1);
3022     SDOperand InFlag = Result.getValue(2);
3023
3024     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3025     // shouldn't be necessary except that RFP cannot be live across
3026     // multiple blocks. When stackifier is fixed, they can be uncoupled.
3027     MachineFunction &MF = DAG.getMachineFunction();
3028     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3029     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3030     std::vector<MVT::ValueType> Tys;
3031     Tys.push_back(MVT::Other);
3032     std::vector<SDOperand> Ops;
3033     Ops.push_back(Chain);
3034     Ops.push_back(Result);
3035     Ops.push_back(StackSlot);
3036     Ops.push_back(DAG.getValueType(Op.getValueType()));
3037     Ops.push_back(InFlag);
3038     Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
3039     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
3040                          DAG.getSrcValue(NULL));
3041   }
3042
3043   return Result;
3044 }
3045
3046 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3047   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3048          "Unknown FP_TO_SINT to lower!");
3049   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3050   // stack slot.
3051   MachineFunction &MF = DAG.getMachineFunction();
3052   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3053   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3054   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3055
3056   unsigned Opc;
3057   switch (Op.getValueType()) {
3058     default: assert(0 && "Invalid FP_TO_SINT to lower!");
3059     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3060     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3061     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3062   }
3063
3064   SDOperand Chain = DAG.getEntryNode();
3065   SDOperand Value = Op.getOperand(0);
3066   if (X86ScalarSSE) {
3067     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3068     Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value, StackSlot, 
3069                         DAG.getSrcValue(0));
3070     std::vector<MVT::ValueType> Tys;
3071     Tys.push_back(MVT::f64);
3072     Tys.push_back(MVT::Other);
3073     std::vector<SDOperand> Ops;
3074     Ops.push_back(Chain);
3075     Ops.push_back(StackSlot);
3076     Ops.push_back(DAG.getValueType(Op.getOperand(0).getValueType()));
3077     Value = DAG.getNode(X86ISD::FLD, Tys, Ops);
3078     Chain = Value.getValue(1);
3079     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3080     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3081   }
3082
3083   // Build the FP_TO_INT*_IN_MEM
3084   std::vector<SDOperand> Ops;
3085   Ops.push_back(Chain);
3086   Ops.push_back(Value);
3087   Ops.push_back(StackSlot);
3088   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
3089
3090   // Load the result.
3091   return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
3092                      DAG.getSrcValue(NULL));
3093 }
3094
3095 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3096   MVT::ValueType VT = Op.getValueType();
3097   const Type *OpNTy =  MVT::getTypeForValueType(VT);
3098   std::vector<Constant*> CV;
3099   if (VT == MVT::f64) {
3100     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63))));
3101     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3102   } else {
3103     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31))));
3104     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3105     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3106     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3107   }
3108   Constant *CS = ConstantStruct::get(CV);
3109   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3110   SDOperand Mask 
3111     = DAG.getNode(X86ISD::LOAD_PACK,
3112                   VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
3113   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3114 }
3115
3116 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3117   MVT::ValueType VT = Op.getValueType();
3118   const Type *OpNTy =  MVT::getTypeForValueType(VT);
3119   std::vector<Constant*> CV;
3120   if (VT == MVT::f64) {
3121     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63)));
3122     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3123   } else {
3124     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(1U << 31)));
3125     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3126     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3127     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3128   }
3129   Constant *CS = ConstantStruct::get(CV);
3130   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3131   SDOperand Mask  = DAG.getNode(X86ISD::LOAD_PACK,
3132                           VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
3133   return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3134 }
3135
3136 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
3137   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3138   SDOperand Cond;
3139   SDOperand CC = Op.getOperand(2);
3140   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3141   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3142   bool Flip;
3143   unsigned X86CC;
3144   if (translateX86CC(CC, isFP, X86CC, Flip)) {
3145     if (Flip)
3146       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
3147                          Op.getOperand(1), Op.getOperand(0));
3148     else
3149       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
3150                          Op.getOperand(0), Op.getOperand(1));
3151     return DAG.getNode(X86ISD::SETCC, MVT::i8, 
3152                        DAG.getConstant(X86CC, MVT::i8), Cond);
3153   } else {
3154     assert(isFP && "Illegal integer SetCC!");
3155
3156     Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
3157                        Op.getOperand(0), Op.getOperand(1));
3158     std::vector<MVT::ValueType> Tys;
3159     std::vector<SDOperand> Ops;
3160     switch (SetCCOpcode) {
3161       default: assert(false && "Illegal floating point SetCC!");
3162       case ISD::SETOEQ: {  // !PF & ZF
3163         Tys.push_back(MVT::i8);
3164         Tys.push_back(MVT::Flag);
3165         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
3166         Ops.push_back(Cond);
3167         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3168         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
3169                                      DAG.getConstant(X86ISD::COND_E, MVT::i8),
3170                                      Tmp1.getValue(1));
3171         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3172       }
3173       case ISD::SETUNE: {  // PF | !ZF
3174         Tys.push_back(MVT::i8);
3175         Tys.push_back(MVT::Flag);
3176         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
3177         Ops.push_back(Cond);
3178         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3179         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
3180                                      DAG.getConstant(X86ISD::COND_NE, MVT::i8),
3181                                      Tmp1.getValue(1));
3182         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3183       }
3184     }
3185   }
3186 }
3187
3188 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3189   MVT::ValueType VT = Op.getValueType();
3190   bool isFPStack = MVT::isFloatingPoint(VT) && !X86ScalarSSE;
3191   bool addTest   = false;
3192   SDOperand Op0 = Op.getOperand(0);
3193   SDOperand Cond, CC;
3194   if (Op0.getOpcode() == ISD::SETCC)
3195     Op0 = LowerOperation(Op0, DAG);
3196
3197   if (Op0.getOpcode() == X86ISD::SETCC) {
3198     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3199     // (since flag operand cannot be shared). If the X86ISD::SETCC does not
3200     // have another use it will be eliminated.
3201     // If the X86ISD::SETCC has more than one use, then it's probably better
3202     // to use a test instead of duplicating the X86ISD::CMP (for register
3203     // pressure reason).
3204     unsigned CmpOpc = Op0.getOperand(1).getOpcode();
3205     if (CmpOpc == X86ISD::CMP || CmpOpc == X86ISD::COMI ||
3206         CmpOpc == X86ISD::UCOMI) {
3207       if (!Op0.hasOneUse()) {
3208         std::vector<MVT::ValueType> Tys;
3209         for (unsigned i = 0; i < Op0.Val->getNumValues(); ++i)
3210           Tys.push_back(Op0.Val->getValueType(i));
3211         std::vector<SDOperand> Ops;
3212         for (unsigned i = 0; i < Op0.getNumOperands(); ++i)
3213           Ops.push_back(Op0.getOperand(i));
3214         Op0 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3215       }
3216
3217       CC   = Op0.getOperand(0);
3218       Cond = Op0.getOperand(1);
3219       // Make a copy as flag result cannot be used by more than one.
3220       Cond = DAG.getNode(CmpOpc, MVT::Flag,
3221                          Cond.getOperand(0), Cond.getOperand(1));
3222       addTest =
3223         isFPStack && !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3224     } else
3225       addTest = true;
3226   } else
3227     addTest = true;
3228
3229   if (addTest) {
3230     CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
3231     Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Op0, Op0);
3232   }
3233
3234   std::vector<MVT::ValueType> Tys;
3235   Tys.push_back(Op.getValueType());
3236   Tys.push_back(MVT::Flag);
3237   std::vector<SDOperand> Ops;
3238   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3239   // condition is true.
3240   Ops.push_back(Op.getOperand(2));
3241   Ops.push_back(Op.getOperand(1));
3242   Ops.push_back(CC);
3243   Ops.push_back(Cond);
3244   return DAG.getNode(X86ISD::CMOV, Tys, Ops);
3245 }
3246
3247 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3248   bool addTest = false;
3249   SDOperand Cond  = Op.getOperand(1);
3250   SDOperand Dest  = Op.getOperand(2);
3251   SDOperand CC;
3252   if (Cond.getOpcode() == ISD::SETCC)
3253     Cond = LowerOperation(Cond, DAG);
3254
3255   if (Cond.getOpcode() == X86ISD::SETCC) {
3256     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3257     // (since flag operand cannot be shared). If the X86ISD::SETCC does not
3258     // have another use it will be eliminated.
3259     // If the X86ISD::SETCC has more than one use, then it's probably better
3260     // to use a test instead of duplicating the X86ISD::CMP (for register
3261     // pressure reason).
3262     unsigned CmpOpc = Cond.getOperand(1).getOpcode();
3263     if (CmpOpc == X86ISD::CMP || CmpOpc == X86ISD::COMI ||
3264         CmpOpc == X86ISD::UCOMI) {
3265       if (!Cond.hasOneUse()) {
3266         std::vector<MVT::ValueType> Tys;
3267         for (unsigned i = 0; i < Cond.Val->getNumValues(); ++i)
3268           Tys.push_back(Cond.Val->getValueType(i));
3269         std::vector<SDOperand> Ops;
3270         for (unsigned i = 0; i < Cond.getNumOperands(); ++i)
3271           Ops.push_back(Cond.getOperand(i));
3272         Cond = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3273       }
3274
3275       CC   = Cond.getOperand(0);
3276       Cond = Cond.getOperand(1);
3277       // Make a copy as flag result cannot be used by more than one.
3278       Cond = DAG.getNode(CmpOpc, MVT::Flag,
3279                          Cond.getOperand(0), Cond.getOperand(1));
3280     } else
3281       addTest = true;
3282   } else
3283     addTest = true;
3284
3285   if (addTest) {
3286     CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
3287     Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Cond, Cond);
3288   }
3289   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3290                      Op.getOperand(0), Op.getOperand(2), CC, Cond);
3291 }
3292
3293 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3294   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3295   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
3296                                  DAG.getTargetJumpTable(JT->getIndex(),
3297                                                         getPointerTy()));
3298   if (Subtarget->isTargetDarwin()) {
3299     // With PIC, the address is actually $g + Offset.
3300     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
3301       Result = DAG.getNode(ISD::ADD, getPointerTy(),
3302                            DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3303                            Result);    
3304   }
3305
3306   return Result;
3307 }
3308
3309 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3310   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3311   if (CallingConv == CallingConv::Fast && EnableFastCC)
3312     return LowerFastCCCallTo(Op, DAG);
3313   else
3314     return LowerCCCCallTo(Op, DAG);
3315 }
3316
3317 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
3318   SDOperand Copy;
3319     
3320   switch(Op.getNumOperands()) {
3321     default:
3322       assert(0 && "Do not know how to return this many arguments!");
3323       abort();
3324     case 1:    // ret void.
3325       return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Op.getOperand(0),
3326                         DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
3327     case 3: {
3328       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
3329       
3330       if (MVT::isVector(ArgVT)) {
3331         // Integer or FP vector result -> XMM0.
3332         if (DAG.getMachineFunction().liveout_empty())
3333           DAG.getMachineFunction().addLiveOut(X86::XMM0);
3334         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::XMM0, Op.getOperand(1),
3335                                 SDOperand());
3336       } else if (MVT::isInteger(ArgVT)) {
3337         // Integer result -> EAX
3338         if (DAG.getMachineFunction().liveout_empty())
3339           DAG.getMachineFunction().addLiveOut(X86::EAX);
3340
3341         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EAX, Op.getOperand(1),
3342                                 SDOperand());
3343       } else if (!X86ScalarSSE) {
3344         // FP return with fp-stack value.
3345         if (DAG.getMachineFunction().liveout_empty())
3346           DAG.getMachineFunction().addLiveOut(X86::ST0);
3347
3348         std::vector<MVT::ValueType> Tys;
3349         Tys.push_back(MVT::Other);
3350         Tys.push_back(MVT::Flag);
3351         std::vector<SDOperand> Ops;
3352         Ops.push_back(Op.getOperand(0));
3353         Ops.push_back(Op.getOperand(1));
3354         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
3355       } else {
3356         // FP return with ScalarSSE (return on fp-stack).
3357         if (DAG.getMachineFunction().liveout_empty())
3358           DAG.getMachineFunction().addLiveOut(X86::ST0);
3359
3360         SDOperand MemLoc;
3361         SDOperand Chain = Op.getOperand(0);
3362         SDOperand Value = Op.getOperand(1);
3363
3364         if (Value.getOpcode() == ISD::LOAD &&
3365             (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
3366           Chain  = Value.getOperand(0);
3367           MemLoc = Value.getOperand(1);
3368         } else {
3369           // Spill the value to memory and reload it into top of stack.
3370           unsigned Size = MVT::getSizeInBits(ArgVT)/8;
3371           MachineFunction &MF = DAG.getMachineFunction();
3372           int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3373           MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
3374           Chain = DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), 
3375                               Value, MemLoc, DAG.getSrcValue(0));
3376         }
3377         std::vector<MVT::ValueType> Tys;
3378         Tys.push_back(MVT::f64);
3379         Tys.push_back(MVT::Other);
3380         std::vector<SDOperand> Ops;
3381         Ops.push_back(Chain);
3382         Ops.push_back(MemLoc);
3383         Ops.push_back(DAG.getValueType(ArgVT));
3384         Copy = DAG.getNode(X86ISD::FLD, Tys, Ops);
3385         Tys.clear();
3386         Tys.push_back(MVT::Other);
3387         Tys.push_back(MVT::Flag);
3388         Ops.clear();
3389         Ops.push_back(Copy.getValue(1));
3390         Ops.push_back(Copy);
3391         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
3392       }
3393       break;
3394     }
3395     case 5:
3396       if (DAG.getMachineFunction().liveout_empty()) {
3397         DAG.getMachineFunction().addLiveOut(X86::EAX);
3398         DAG.getMachineFunction().addLiveOut(X86::EDX);
3399       }
3400
3401       Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EDX, Op.getOperand(3), 
3402                               SDOperand());
3403       Copy = DAG.getCopyToReg(Copy, X86::EAX,Op.getOperand(1),Copy.getValue(1));
3404       break;
3405   }
3406   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other,
3407                    Copy, DAG.getConstant(getBytesToPopOnReturn(), MVT::i16),
3408                      Copy.getValue(1));
3409 }
3410
3411 SDOperand
3412 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3413   MachineFunction &MF = DAG.getMachineFunction();
3414   const Function* Fn = MF.getFunction();
3415   if (Fn->hasExternalLinkage() &&
3416       Fn->getName() == "main" &&
3417       Subtarget->TargetType == X86Subtarget::isCygwin)
3418     MF.getInfo<X86FunctionInfo>()->setForceFramePointer(true);
3419
3420   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3421   if (CC == CallingConv::Fast && EnableFastCC)
3422     return LowerFastCCArguments(Op, DAG);
3423   else
3424     return LowerCCCArguments(Op, DAG);
3425 }
3426
3427 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3428   SDOperand InFlag(0, 0);
3429   SDOperand Chain = Op.getOperand(0);
3430   unsigned Align =
3431     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3432   if (Align == 0) Align = 1;
3433
3434   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3435   // If not DWORD aligned, call memset if size is less than the threshold.
3436   // It knows how to align to the right boundary first.
3437   if ((Align & 3) != 0 ||
3438       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3439     MVT::ValueType IntPtr = getPointerTy();
3440     const Type *IntPtrTy = getTargetData()->getIntPtrType();
3441     std::vector<std::pair<SDOperand, const Type*> > Args;
3442     Args.push_back(std::make_pair(Op.getOperand(1), IntPtrTy));
3443     // Extend the ubyte argument to be an int value for the call.
3444     SDOperand Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3445     Args.push_back(std::make_pair(Val, IntPtrTy));
3446     Args.push_back(std::make_pair(Op.getOperand(3), IntPtrTy));
3447     std::pair<SDOperand,SDOperand> CallResult =
3448       LowerCallTo(Chain, Type::VoidTy, false, CallingConv::C, false,
3449                   DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3450     return CallResult.second;
3451   }
3452
3453   MVT::ValueType AVT;
3454   SDOperand Count;
3455   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3456   unsigned BytesLeft = 0;
3457   bool TwoRepStos = false;
3458   if (ValC) {
3459     unsigned ValReg;
3460     unsigned Val = ValC->getValue() & 255;
3461
3462     // If the value is a constant, then we can potentially use larger sets.
3463     switch (Align & 3) {
3464       case 2:   // WORD aligned
3465         AVT = MVT::i16;
3466         Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
3467         BytesLeft = I->getValue() % 2;
3468         Val    = (Val << 8) | Val;
3469         ValReg = X86::AX;
3470         break;
3471       case 0:   // DWORD aligned
3472         AVT = MVT::i32;
3473         if (I) {
3474           Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
3475           BytesLeft = I->getValue() % 4;
3476         } else {
3477           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
3478                               DAG.getConstant(2, MVT::i8));
3479           TwoRepStos = true;
3480         }
3481         Val = (Val << 8)  | Val;
3482         Val = (Val << 16) | Val;
3483         ValReg = X86::EAX;
3484         break;
3485       default:  // Byte aligned
3486         AVT = MVT::i8;
3487         Count = Op.getOperand(3);
3488         ValReg = X86::AL;
3489         break;
3490     }
3491
3492     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3493                               InFlag);
3494     InFlag = Chain.getValue(1);
3495   } else {
3496     AVT = MVT::i8;
3497     Count  = Op.getOperand(3);
3498     Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3499     InFlag = Chain.getValue(1);
3500   }
3501
3502   Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
3503   InFlag = Chain.getValue(1);
3504   Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
3505   InFlag = Chain.getValue(1);
3506
3507   std::vector<MVT::ValueType> Tys;
3508   Tys.push_back(MVT::Other);
3509   Tys.push_back(MVT::Flag);
3510   std::vector<SDOperand> Ops;
3511   Ops.push_back(Chain);
3512   Ops.push_back(DAG.getValueType(AVT));
3513   Ops.push_back(InFlag);
3514   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, Ops);
3515
3516   if (TwoRepStos) {
3517     InFlag = Chain.getValue(1);
3518     Count = Op.getOperand(3);
3519     MVT::ValueType CVT = Count.getValueType();
3520     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3521                                  DAG.getConstant(3, CVT));
3522     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Left, InFlag);
3523     InFlag = Chain.getValue(1);
3524     Tys.clear();
3525     Tys.push_back(MVT::Other);
3526     Tys.push_back(MVT::Flag);
3527     Ops.clear();
3528     Ops.push_back(Chain);
3529     Ops.push_back(DAG.getValueType(MVT::i8));
3530     Ops.push_back(InFlag);
3531     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, Ops);
3532   } else if (BytesLeft) {
3533     // Issue stores for the last 1 - 3 bytes.
3534     SDOperand Value;
3535     unsigned Val = ValC->getValue() & 255;
3536     unsigned Offset = I->getValue() - BytesLeft;
3537     SDOperand DstAddr = Op.getOperand(1);
3538     MVT::ValueType AddrVT = DstAddr.getValueType();
3539     if (BytesLeft >= 2) {
3540       Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3541       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3542                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3543                                       DAG.getConstant(Offset, AddrVT)),
3544                           DAG.getSrcValue(NULL));
3545       BytesLeft -= 2;
3546       Offset += 2;
3547     }
3548
3549     if (BytesLeft == 1) {
3550       Value = DAG.getConstant(Val, MVT::i8);
3551       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3552                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3553                                       DAG.getConstant(Offset, AddrVT)),
3554                           DAG.getSrcValue(NULL));
3555     }
3556   }
3557
3558   return Chain;
3559 }
3560
3561 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3562   SDOperand Chain = Op.getOperand(0);
3563   unsigned Align =
3564     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3565   if (Align == 0) Align = 1;
3566
3567   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3568   // If not DWORD aligned, call memcpy if size is less than the threshold.
3569   // It knows how to align to the right boundary first.
3570   if ((Align & 3) != 0 ||
3571       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3572     MVT::ValueType IntPtr = getPointerTy();
3573     const Type *IntPtrTy = getTargetData()->getIntPtrType();
3574     std::vector<std::pair<SDOperand, const Type*> > Args;
3575     Args.push_back(std::make_pair(Op.getOperand(1), IntPtrTy));
3576     Args.push_back(std::make_pair(Op.getOperand(2), IntPtrTy));
3577     Args.push_back(std::make_pair(Op.getOperand(3), IntPtrTy));
3578     std::pair<SDOperand,SDOperand> CallResult =
3579       LowerCallTo(Chain, Type::VoidTy, false, CallingConv::C, false,
3580                   DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3581     return CallResult.second;
3582   }
3583
3584   MVT::ValueType AVT;
3585   SDOperand Count;
3586   unsigned BytesLeft = 0;
3587   bool TwoRepMovs = false;
3588   switch (Align & 3) {
3589     case 2:   // WORD aligned
3590       AVT = MVT::i16;
3591       Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
3592       BytesLeft = I->getValue() % 2;
3593       break;
3594     case 0:   // DWORD aligned
3595       AVT = MVT::i32;
3596       if (I) {
3597         Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
3598         BytesLeft = I->getValue() % 4;
3599       } else {
3600         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
3601                             DAG.getConstant(2, MVT::i8));
3602         TwoRepMovs = true;
3603       }
3604       break;
3605     default:  // Byte aligned
3606       AVT = MVT::i8;
3607       Count = Op.getOperand(3);
3608       break;
3609   }
3610
3611   SDOperand InFlag(0, 0);
3612   Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
3613   InFlag = Chain.getValue(1);
3614   Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
3615   InFlag = Chain.getValue(1);
3616   Chain  = DAG.getCopyToReg(Chain, X86::ESI, Op.getOperand(2), InFlag);
3617   InFlag = Chain.getValue(1);
3618
3619   std::vector<MVT::ValueType> Tys;
3620   Tys.push_back(MVT::Other);
3621   Tys.push_back(MVT::Flag);
3622   std::vector<SDOperand> Ops;
3623   Ops.push_back(Chain);
3624   Ops.push_back(DAG.getValueType(AVT));
3625   Ops.push_back(InFlag);
3626   Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, Ops);
3627
3628   if (TwoRepMovs) {
3629     InFlag = Chain.getValue(1);
3630     Count = Op.getOperand(3);
3631     MVT::ValueType CVT = Count.getValueType();
3632     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3633                                  DAG.getConstant(3, CVT));
3634     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Left, InFlag);
3635     InFlag = Chain.getValue(1);
3636     Tys.clear();
3637     Tys.push_back(MVT::Other);
3638     Tys.push_back(MVT::Flag);
3639     Ops.clear();
3640     Ops.push_back(Chain);
3641     Ops.push_back(DAG.getValueType(MVT::i8));
3642     Ops.push_back(InFlag);
3643     Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, Ops);
3644   } else if (BytesLeft) {
3645     // Issue loads and stores for the last 1 - 3 bytes.
3646     unsigned Offset = I->getValue() - BytesLeft;
3647     SDOperand DstAddr = Op.getOperand(1);
3648     MVT::ValueType DstVT = DstAddr.getValueType();
3649     SDOperand SrcAddr = Op.getOperand(2);
3650     MVT::ValueType SrcVT = SrcAddr.getValueType();
3651     SDOperand Value;
3652     if (BytesLeft >= 2) {
3653       Value = DAG.getLoad(MVT::i16, Chain,
3654                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3655                                       DAG.getConstant(Offset, SrcVT)),
3656                           DAG.getSrcValue(NULL));
3657       Chain = Value.getValue(1);
3658       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3659                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
3660                                       DAG.getConstant(Offset, DstVT)),
3661                           DAG.getSrcValue(NULL));
3662       BytesLeft -= 2;
3663       Offset += 2;
3664     }
3665
3666     if (BytesLeft == 1) {
3667       Value = DAG.getLoad(MVT::i8, Chain,
3668                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3669                                       DAG.getConstant(Offset, SrcVT)),
3670                           DAG.getSrcValue(NULL));
3671       Chain = Value.getValue(1);
3672       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3673                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
3674                                       DAG.getConstant(Offset, DstVT)),
3675                           DAG.getSrcValue(NULL));
3676     }
3677   }
3678
3679   return Chain;
3680 }
3681
3682 SDOperand
3683 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
3684   std::vector<MVT::ValueType> Tys;
3685   Tys.push_back(MVT::Other);
3686   Tys.push_back(MVT::Flag);
3687   std::vector<SDOperand> Ops;
3688   Ops.push_back(Op.getOperand(0));
3689   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, Ops);
3690   Ops.clear();
3691   Ops.push_back(DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1)));
3692   Ops.push_back(DAG.getCopyFromReg(Ops[0].getValue(1), X86::EDX, 
3693                                    MVT::i32, Ops[0].getValue(2)));
3694   Ops.push_back(Ops[1].getValue(1));
3695   Tys[0] = Tys[1] = MVT::i32;
3696   Tys.push_back(MVT::Other);
3697   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
3698 }
3699
3700 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
3701   // vastart just stores the address of the VarArgsFrameIndex slot into the
3702   // memory location argument.
3703   // FIXME: Replace MVT::i32 with PointerTy
3704   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
3705   return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
3706                      Op.getOperand(1), Op.getOperand(2));
3707 }
3708
3709 SDOperand
3710 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
3711   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
3712   switch (IntNo) {
3713   default: return SDOperand();    // Don't custom lower most intrinsics.
3714     // Comparison intrinsics.
3715   case Intrinsic::x86_sse_comieq_ss:
3716   case Intrinsic::x86_sse_comilt_ss:
3717   case Intrinsic::x86_sse_comile_ss:
3718   case Intrinsic::x86_sse_comigt_ss:
3719   case Intrinsic::x86_sse_comige_ss:
3720   case Intrinsic::x86_sse_comineq_ss:
3721   case Intrinsic::x86_sse_ucomieq_ss:
3722   case Intrinsic::x86_sse_ucomilt_ss:
3723   case Intrinsic::x86_sse_ucomile_ss:
3724   case Intrinsic::x86_sse_ucomigt_ss:
3725   case Intrinsic::x86_sse_ucomige_ss:
3726   case Intrinsic::x86_sse_ucomineq_ss:
3727   case Intrinsic::x86_sse2_comieq_sd:
3728   case Intrinsic::x86_sse2_comilt_sd:
3729   case Intrinsic::x86_sse2_comile_sd:
3730   case Intrinsic::x86_sse2_comigt_sd:
3731   case Intrinsic::x86_sse2_comige_sd:
3732   case Intrinsic::x86_sse2_comineq_sd:
3733   case Intrinsic::x86_sse2_ucomieq_sd:
3734   case Intrinsic::x86_sse2_ucomilt_sd:
3735   case Intrinsic::x86_sse2_ucomile_sd:
3736   case Intrinsic::x86_sse2_ucomigt_sd:
3737   case Intrinsic::x86_sse2_ucomige_sd:
3738   case Intrinsic::x86_sse2_ucomineq_sd: {
3739     unsigned Opc = 0;
3740     ISD::CondCode CC = ISD::SETCC_INVALID;
3741     switch (IntNo) {
3742     default: break;
3743     case Intrinsic::x86_sse_comieq_ss: 
3744     case Intrinsic::x86_sse2_comieq_sd: 
3745       Opc = X86ISD::COMI;
3746       CC = ISD::SETEQ;
3747       break;
3748     case Intrinsic::x86_sse_comilt_ss:
3749     case Intrinsic::x86_sse2_comilt_sd:
3750       Opc = X86ISD::COMI;
3751       CC = ISD::SETLT;
3752       break;
3753     case Intrinsic::x86_sse_comile_ss:
3754     case Intrinsic::x86_sse2_comile_sd:
3755       Opc = X86ISD::COMI;
3756       CC = ISD::SETLE;
3757       break;
3758     case Intrinsic::x86_sse_comigt_ss:
3759     case Intrinsic::x86_sse2_comigt_sd:
3760       Opc = X86ISD::COMI;
3761       CC = ISD::SETGT;
3762       break;
3763     case Intrinsic::x86_sse_comige_ss:
3764     case Intrinsic::x86_sse2_comige_sd:
3765       Opc = X86ISD::COMI;
3766       CC = ISD::SETGE;
3767       break;
3768     case Intrinsic::x86_sse_comineq_ss:
3769     case Intrinsic::x86_sse2_comineq_sd:
3770       Opc = X86ISD::COMI;
3771       CC = ISD::SETNE;
3772       break;
3773     case Intrinsic::x86_sse_ucomieq_ss:
3774     case Intrinsic::x86_sse2_ucomieq_sd:
3775       Opc = X86ISD::UCOMI;
3776       CC = ISD::SETEQ;
3777       break;
3778     case Intrinsic::x86_sse_ucomilt_ss:
3779     case Intrinsic::x86_sse2_ucomilt_sd:
3780       Opc = X86ISD::UCOMI;
3781       CC = ISD::SETLT;
3782       break;
3783     case Intrinsic::x86_sse_ucomile_ss:
3784     case Intrinsic::x86_sse2_ucomile_sd:
3785       Opc = X86ISD::UCOMI;
3786       CC = ISD::SETLE;
3787       break;
3788     case Intrinsic::x86_sse_ucomigt_ss:
3789     case Intrinsic::x86_sse2_ucomigt_sd:
3790       Opc = X86ISD::UCOMI;
3791       CC = ISD::SETGT;
3792       break;
3793     case Intrinsic::x86_sse_ucomige_ss:
3794     case Intrinsic::x86_sse2_ucomige_sd:
3795       Opc = X86ISD::UCOMI;
3796       CC = ISD::SETGE;
3797       break;
3798     case Intrinsic::x86_sse_ucomineq_ss:
3799     case Intrinsic::x86_sse2_ucomineq_sd:
3800       Opc = X86ISD::UCOMI;
3801       CC = ISD::SETNE;
3802       break;
3803     }
3804     bool Flip;
3805     unsigned X86CC;
3806     translateX86CC(CC, true, X86CC, Flip);
3807     SDOperand Cond = DAG.getNode(Opc, MVT::Flag, Op.getOperand(Flip?2:1),
3808                                  Op.getOperand(Flip?1:2));
3809     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8, 
3810                                   DAG.getConstant(X86CC, MVT::i8), Cond);
3811     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
3812   }
3813   }
3814 }
3815
3816 /// LowerOperation - Provide custom lowering hooks for some operations.
3817 ///
3818 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3819   switch (Op.getOpcode()) {
3820   default: assert(0 && "Should not custom lower this!");
3821   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
3822   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
3823   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3824   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
3825   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
3826   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
3827   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
3828   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
3829   case ISD::SHL_PARTS:
3830   case ISD::SRA_PARTS:
3831   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
3832   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
3833   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
3834   case ISD::FABS:               return LowerFABS(Op, DAG);
3835   case ISD::FNEG:               return LowerFNEG(Op, DAG);
3836   case ISD::SETCC:              return LowerSETCC(Op, DAG);
3837   case ISD::SELECT:             return LowerSELECT(Op, DAG);
3838   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
3839   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
3840   case ISD::CALL:               return LowerCALL(Op, DAG);
3841   case ISD::RET:                return LowerRET(Op, DAG);
3842   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
3843   case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
3844   case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
3845   case ISD::READCYCLECOUNTER:   return LowerREADCYCLCECOUNTER(Op, DAG);
3846   case ISD::VASTART:            return LowerVASTART(Op, DAG);
3847   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3848   }
3849 }
3850
3851 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
3852   switch (Opcode) {
3853   default: return NULL;
3854   case X86ISD::SHLD:               return "X86ISD::SHLD";
3855   case X86ISD::SHRD:               return "X86ISD::SHRD";
3856   case X86ISD::FAND:               return "X86ISD::FAND";
3857   case X86ISD::FXOR:               return "X86ISD::FXOR";
3858   case X86ISD::FILD:               return "X86ISD::FILD";
3859   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
3860   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
3861   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
3862   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
3863   case X86ISD::FLD:                return "X86ISD::FLD";
3864   case X86ISD::FST:                return "X86ISD::FST";
3865   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
3866   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
3867   case X86ISD::CALL:               return "X86ISD::CALL";
3868   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
3869   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
3870   case X86ISD::CMP:                return "X86ISD::CMP";
3871   case X86ISD::TEST:               return "X86ISD::TEST";
3872   case X86ISD::COMI:               return "X86ISD::COMI";
3873   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
3874   case X86ISD::SETCC:              return "X86ISD::SETCC";
3875   case X86ISD::CMOV:               return "X86ISD::CMOV";
3876   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
3877   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
3878   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
3879   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
3880   case X86ISD::LOAD_PACK:          return "X86ISD::LOAD_PACK";
3881   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
3882   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
3883   case X86ISD::S2VEC:              return "X86ISD::S2VEC";
3884   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
3885   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
3886   }
3887 }
3888
3889 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
3890                                                        uint64_t Mask,
3891                                                        uint64_t &KnownZero, 
3892                                                        uint64_t &KnownOne,
3893                                                        unsigned Depth) const {
3894   unsigned Opc = Op.getOpcode();
3895   assert((Opc >= ISD::BUILTIN_OP_END ||
3896           Opc == ISD::INTRINSIC_WO_CHAIN ||
3897           Opc == ISD::INTRINSIC_W_CHAIN ||
3898           Opc == ISD::INTRINSIC_VOID) &&
3899          "Should use MaskedValueIsZero if you don't know whether Op"
3900          " is a target node!");
3901
3902   KnownZero = KnownOne = 0;   // Don't know anything.
3903   switch (Opc) {
3904   default: break;
3905   case X86ISD::SETCC: 
3906     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
3907     break;
3908   }
3909 }
3910
3911 std::vector<unsigned> X86TargetLowering::
3912 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3913                                   MVT::ValueType VT) const {
3914   if (Constraint.size() == 1) {
3915     // FIXME: not handling fp-stack yet!
3916     // FIXME: not handling MMX registers yet ('y' constraint).
3917     switch (Constraint[0]) {      // GCC X86 Constraint Letters
3918     default: break;  // Unknown constriant letter
3919     case 'r':   // GENERAL_REGS
3920     case 'R':   // LEGACY_REGS
3921       if (VT == MVT::i32)
3922         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
3923                                      X86::ESI, X86::EDI, X86::EBP, X86::ESP, 0);
3924       else if (VT == MVT::i16)
3925         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 
3926                                      X86::SI, X86::DI, X86::BP, X86::SP, 0);
3927       else if (VT == MVT::i8)
3928         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
3929       break;
3930     case 'l':   // INDEX_REGS
3931       if (VT == MVT::i32)
3932         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
3933                                      X86::ESI, X86::EDI, X86::EBP, 0);
3934       else if (VT == MVT::i16)
3935         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 
3936                                      X86::SI, X86::DI, X86::BP, 0);
3937       else if (VT == MVT::i8)
3938         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
3939       break;
3940     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
3941     case 'Q':   // Q_REGS
3942       if (VT == MVT::i32)
3943         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
3944       else if (VT == MVT::i16)
3945         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
3946       else if (VT == MVT::i8)
3947         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
3948         break;
3949     case 'x':   // SSE_REGS if SSE1 allowed
3950       if (Subtarget->hasSSE1())
3951         return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3952                                      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
3953                                      0);
3954       return std::vector<unsigned>();
3955     case 'Y':   // SSE_REGS if SSE2 allowed
3956       if (Subtarget->hasSSE2())
3957         return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3958                                      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
3959                                      0);
3960       return std::vector<unsigned>();
3961     }
3962   }
3963   
3964   return std::vector<unsigned>();
3965 }
3966
3967 /// isLegalAddressImmediate - Return true if the integer value or
3968 /// GlobalValue can be used as the offset of the target addressing mode.
3969 bool X86TargetLowering::isLegalAddressImmediate(int64_t V) const {
3970   // X86 allows a sign-extended 32-bit immediate field.
3971   return (V > -(1LL << 32) && V < (1LL << 32)-1);
3972 }
3973
3974 bool X86TargetLowering::isLegalAddressImmediate(GlobalValue *GV) const {
3975   if (Subtarget->isTargetDarwin()) {
3976     Reloc::Model RModel = getTargetMachine().getRelocationModel();
3977     if (RModel == Reloc::Static)
3978       return true;
3979     else if (RModel == Reloc::DynamicNoPIC)
3980       return !DarwinGVRequiresExtraLoad(GV);
3981     else
3982       return false;
3983   } else
3984     return true;
3985 }
3986
3987 /// isShuffleMaskLegal - Targets can use this to indicate that they only
3988 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
3989 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
3990 /// are assumed to be legal.
3991 bool
3992 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
3993   // Only do shuffles on 128-bit vector types for now.
3994   if (MVT::getSizeInBits(VT) == 64) return false;
3995   return (Mask.Val->getNumOperands() <= 4 ||
3996           isSplatMask(Mask.Val)  ||
3997           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
3998           X86::isUNPCKLMask(Mask.Val) ||
3999           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
4000           X86::isUNPCKHMask(Mask.Val));
4001 }
4002
4003 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
4004                                                MVT::ValueType EVT,
4005                                                SelectionDAG &DAG) const {
4006   unsigned NumElts = BVOps.size();
4007   // Only do shuffles on 128-bit vector types for now.
4008   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
4009   if (NumElts == 2) return true;
4010   if (NumElts == 4) {
4011     return (isMOVLMask(BVOps)  || isCommutedMOVL(BVOps, true) ||
4012             isSHUFPMask(BVOps) || isCommutedSHUFP(BVOps));
4013   }
4014   return false;
4015 }