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