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