fix mmx handling bug
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/StringExtras.h"
37 using namespace llvm;
38
39 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
40   : TargetLowering(TM) {
41   Subtarget = &TM.getSubtarget<X86Subtarget>();
42   X86ScalarSSE = Subtarget->hasSSE2();
43   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
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(X86StackPtr);
54
55   if (Subtarget->isTargetDarwin()) {
56     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
57     setUseUnderscoreSetJmp(false);
58     setUseUnderscoreLongJmp(false);
59   } else if (Subtarget->isTargetMingw()) {
60     // MS runtime is weird: it exports _setjmp, but longjmp!
61     setUseUnderscoreSetJmp(true);
62     setUseUnderscoreLongJmp(false);
63   } else {
64     setUseUnderscoreSetJmp(true);
65     setUseUnderscoreLongJmp(true);
66   }
67   
68   // Set up the register classes.
69   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
70   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
71   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
72   if (Subtarget->is64Bit())
73     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
74
75   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
76
77   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
78   // operation.
79   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
80   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
81   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
82
83   if (Subtarget->is64Bit()) {
84     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
85     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
86   } else {
87     if (X86ScalarSSE)
88       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
89       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
90     else
91       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
92   }
93
94   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
95   // this operation.
96   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
97   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
98   // SSE has no i16 to fp conversion, only i32
99   if (X86ScalarSSE)
100     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
101   else {
102     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
103     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
104   }
105
106   if (!Subtarget->is64Bit()) {
107     // Custom lower SINT_TO_FP and FP_TO_SINT from/to i64 in 32-bit mode.
108     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
109     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
110   }
111
112   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
113   // this operation.
114   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
115   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
116
117   if (X86ScalarSSE) {
118     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
119   } else {
120     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
121     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
122   }
123
124   // Handle FP_TO_UINT by promoting the destination to a larger signed
125   // conversion.
126   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
127   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
128   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
129
130   if (Subtarget->is64Bit()) {
131     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
132     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
133   } else {
134     if (X86ScalarSSE && !Subtarget->hasSSE3())
135       // Expand FP_TO_UINT into a select.
136       // FIXME: We would like to use a Custom expander here eventually to do
137       // the optimal thing for SSE vs. the default expansion in the legalizer.
138       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
139     else
140       // With SSE3 we can use fisttpll to convert to a signed i64.
141       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
142   }
143
144   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
145   if (!X86ScalarSSE) {
146     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
147     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
148   }
149
150   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
151   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
152   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
153   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
154   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
155   if (Subtarget->is64Bit())
156     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
157   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
158   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
159   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
160   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
161   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
162
163   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
164   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
165   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
166   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
167   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
168   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
169   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
170   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
171   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
172   if (Subtarget->is64Bit()) {
173     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
174     setOperationAction(ISD::CTTZ           , MVT::i64  , Expand);
175     setOperationAction(ISD::CTLZ           , MVT::i64  , Expand);
176   }
177
178   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
179   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
180
181   // These should be promoted to a larger select which is supported.
182   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
183   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
184   // X86 wants to expand cmov itself.
185   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
186   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
187   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
188   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
189   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
190   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
191   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
192   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
193   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
194   if (Subtarget->is64Bit()) {
195     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
196     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
197   }
198   // X86 ret instruction may pop stack.
199   setOperationAction(ISD::RET             , MVT::Other, Custom);
200   // Darwin ABI issue.
201   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
202   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
203   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
204   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
205   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
206   if (Subtarget->is64Bit()) {
207     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
208     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
209     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
210     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
211   }
212   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
213   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
214   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
215   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
216   // X86 wants to expand memset / memcpy itself.
217   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
218   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
219
220   // We don't have line number support yet.
221   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
222   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
223   // FIXME - use subtarget debug flags
224   if (!Subtarget->isTargetDarwin() &&
225       !Subtarget->isTargetELF() &&
226       !Subtarget->isTargetCygMing())
227     setOperationAction(ISD::LABEL, MVT::Other, Expand);
228
229   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
230   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
231   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
232   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
233   if (Subtarget->is64Bit()) {
234     // FIXME: Verify
235     setExceptionPointerRegister(X86::RAX);
236     setExceptionSelectorRegister(X86::RDX);
237   } else {
238     setExceptionPointerRegister(X86::EAX);
239     setExceptionSelectorRegister(X86::EDX);
240   }
241   
242   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
243   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
244   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
245   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
246   if (Subtarget->is64Bit())
247     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
248   else
249     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
250
251   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
252   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
253   if (Subtarget->is64Bit())
254     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
255   if (Subtarget->isTargetCygMing())
256     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
257   else
258     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
259
260   if (X86ScalarSSE) {
261     // Set up the FP register classes.
262     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
263     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
264
265     // Use ANDPD to simulate FABS.
266     setOperationAction(ISD::FABS , MVT::f64, Custom);
267     setOperationAction(ISD::FABS , MVT::f32, Custom);
268
269     // Use XORP to simulate FNEG.
270     setOperationAction(ISD::FNEG , MVT::f64, Custom);
271     setOperationAction(ISD::FNEG , MVT::f32, Custom);
272
273     // Use ANDPD and ORPD to simulate FCOPYSIGN.
274     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
275     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
276
277     // We don't support sin/cos/fmod
278     setOperationAction(ISD::FSIN , MVT::f64, Expand);
279     setOperationAction(ISD::FCOS , MVT::f64, Expand);
280     setOperationAction(ISD::FREM , MVT::f64, Expand);
281     setOperationAction(ISD::FSIN , MVT::f32, Expand);
282     setOperationAction(ISD::FCOS , MVT::f32, Expand);
283     setOperationAction(ISD::FREM , MVT::f32, Expand);
284
285     // Expand FP immediates into loads from the stack, except for the special
286     // cases we handle.
287     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
288     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
289     addLegalFPImmediate(+0.0); // xorps / xorpd
290   } else {
291     // Set up the FP register classes.
292     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
293
294     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
295     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
296     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
297
298     if (!UnsafeFPMath) {
299       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
300       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
301     }
302
303     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
304     addLegalFPImmediate(+0.0); // FLD0
305     addLegalFPImmediate(+1.0); // FLD1
306     addLegalFPImmediate(-0.0); // FLD0/FCHS
307     addLegalFPImmediate(-1.0); // FLD1/FCHS
308   }
309
310   // First set operation action for all vector types to expand. Then we
311   // will selectively turn on ones that can be effectively codegen'd.
312   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
313        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
314     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
315     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
316     setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
317     setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
318     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
319     setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
320     setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
321     setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
322     setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
323     setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
324     setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
325     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
326     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
327     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
328     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
329   }
330
331   if (Subtarget->hasMMX()) {
332     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
333     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
334     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
335     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
336
337     // FIXME: add MMX packed arithmetics
338
339     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
340     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
341     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
342     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
343
344     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
345     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
346     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
347
348     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
349     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
350
351     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
352     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
353     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
354     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
355     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
356     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
357     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
358
359     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
360     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
361     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
362     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
363     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
364     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
365     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
366
367     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
368     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
369     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
370     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
371     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
372     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
373     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
374
375     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
376     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
377     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
378     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
379     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
380     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
381     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
382
383     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
384     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
385     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
386     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
387
388     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
389     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
390     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
391     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
392
393     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
394     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
395     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Custom);
396     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
397   }
398
399   if (Subtarget->hasSSE1()) {
400     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
401
402     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
403     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
404     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
405     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
406     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
407     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
408     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
409     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
410     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
411   }
412
413   if (Subtarget->hasSSE2()) {
414     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
415     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
416     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
417     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
418     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
419
420     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
421     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
422     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
423     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
424     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
425     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
426     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
427     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
428     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
429     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
430     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
431     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
432     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
433
434     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
435     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
436     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
437     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
438     // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
439     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
440
441     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
442     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
443       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
444       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
445       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
446     }
447     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
448     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
449     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
450     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
453
454     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
455     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
456       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
457       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
458       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
459       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
460       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
461       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
462       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
463       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
464       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
465       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
466     }
467
468     // Custom lower v2i64 and v2f64 selects.
469     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
470     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
471     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
472     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
473   }
474
475   // We want to custom lower some of our intrinsics.
476   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
477
478   // We have target-specific dag combine patterns for the following nodes:
479   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
480   setTargetDAGCombine(ISD::SELECT);
481
482   computeRegisterProperties();
483
484   // FIXME: These should be based on subtarget info. Plus, the values should
485   // be smaller when we are in optimizing for size mode.
486   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
487   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
488   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
489   allowUnalignedMemoryAccesses = true; // x86 supports it!
490 }
491
492
493 //===----------------------------------------------------------------------===//
494 //               Return Value Calling Convention Implementation
495 //===----------------------------------------------------------------------===//
496
497 #include "X86GenCallingConv.inc"
498     
499 /// LowerRET - Lower an ISD::RET node.
500 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
501   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
502   
503   SmallVector<CCValAssign, 16> RVLocs;
504   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
505   CCState CCInfo(CC, getTargetMachine(), RVLocs);
506   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
507   
508   
509   // If this is the first return lowered for this function, add the regs to the
510   // liveout set for the function.
511   if (DAG.getMachineFunction().liveout_empty()) {
512     for (unsigned i = 0; i != RVLocs.size(); ++i)
513       if (RVLocs[i].isRegLoc())
514         DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
515   }
516   
517   SDOperand Chain = Op.getOperand(0);
518   SDOperand Flag;
519   
520   // Copy the result values into the output registers.
521   if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
522       RVLocs[0].getLocReg() != X86::ST0) {
523     for (unsigned i = 0; i != RVLocs.size(); ++i) {
524       CCValAssign &VA = RVLocs[i];
525       assert(VA.isRegLoc() && "Can only return in registers!");
526       Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
527                                Flag);
528       Flag = Chain.getValue(1);
529     }
530   } else {
531     // We need to handle a destination of ST0 specially, because it isn't really
532     // a register.
533     SDOperand Value = Op.getOperand(1);
534     
535     // If this is an FP return with ScalarSSE, we need to move the value from
536     // an XMM register onto the fp-stack.
537     if (X86ScalarSSE) {
538       SDOperand MemLoc;
539       
540       // If this is a load into a scalarsse value, don't store the loaded value
541       // back to the stack, only to reload it: just replace the scalar-sse load.
542       if (ISD::isNON_EXTLoad(Value.Val) &&
543           (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
544         Chain  = Value.getOperand(0);
545         MemLoc = Value.getOperand(1);
546       } else {
547         // Spill the value to memory and reload it into top of stack.
548         unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
549         MachineFunction &MF = DAG.getMachineFunction();
550         int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
551         MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
552         Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
553       }
554       SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other);
555       SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
556       Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
557       Chain = Value.getValue(1);
558     }
559     
560     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
561     SDOperand Ops[] = { Chain, Value };
562     Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
563     Flag = Chain.getValue(1);
564   }
565   
566   SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
567   if (Flag.Val)
568     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
569   else
570     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
571 }
572
573
574 /// LowerCallResult - Lower the result values of an ISD::CALL into the
575 /// appropriate copies out of appropriate physical registers.  This assumes that
576 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
577 /// being lowered.  The returns a SDNode with the same number of values as the
578 /// ISD::CALL.
579 SDNode *X86TargetLowering::
580 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
581                 unsigned CallingConv, SelectionDAG &DAG) {
582   
583   // Assign locations to each value returned by this call.
584   SmallVector<CCValAssign, 16> RVLocs;
585   CCState CCInfo(CallingConv, getTargetMachine(), RVLocs);
586   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
587
588   
589   SmallVector<SDOperand, 8> ResultVals;
590   
591   // Copy all of the result registers out of their specified physreg.
592   if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
593     for (unsigned i = 0; i != RVLocs.size(); ++i) {
594       Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
595                                  RVLocs[i].getValVT(), InFlag).getValue(1);
596       InFlag = Chain.getValue(2);
597       ResultVals.push_back(Chain.getValue(0));
598     }
599   } else {
600     // Copies from the FP stack are special, as ST0 isn't a valid register
601     // before the fp stackifier runs.
602     
603     // Copy ST0 into an RFP register with FP_GET_RESULT.
604     SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
605     SDOperand GROps[] = { Chain, InFlag };
606     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
607     Chain  = RetVal.getValue(1);
608     InFlag = RetVal.getValue(2);
609     
610     // If we are using ScalarSSE, store ST(0) to the stack and reload it into
611     // an XMM register.
612     if (X86ScalarSSE) {
613       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
614       // shouldn't be necessary except that RFP cannot be live across
615       // multiple blocks. When stackifier is fixed, they can be uncoupled.
616       MachineFunction &MF = DAG.getMachineFunction();
617       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
618       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
619       SDOperand Ops[] = {
620         Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
621       };
622       Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
623       RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
624       Chain = RetVal.getValue(1);
625     }
626     
627     if (RVLocs[0].getValVT() == MVT::f32 && !X86ScalarSSE)
628       // FIXME: we would really like to remember that this FP_ROUND
629       // operation is okay to eliminate if we allow excess FP precision.
630       RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
631     ResultVals.push_back(RetVal);
632   }
633   
634   // Merge everything together with a MERGE_VALUES node.
635   ResultVals.push_back(Chain);
636   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
637                      &ResultVals[0], ResultVals.size()).Val;
638 }
639
640
641 //===----------------------------------------------------------------------===//
642 //                C & StdCall Calling Convention implementation
643 //===----------------------------------------------------------------------===//
644 //  StdCall calling convention seems to be standard for many Windows' API
645 //  routines and around. It differs from C calling convention just a little:
646 //  callee should clean up the stack, not caller. Symbols should be also
647 //  decorated in some fancy way :) It doesn't support any vector arguments.
648
649 /// AddLiveIn - This helper function adds the specified physical register to the
650 /// MachineFunction as a live in value.  It also creates a corresponding virtual
651 /// register for it.
652 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
653                           const TargetRegisterClass *RC) {
654   assert(RC->contains(PReg) && "Not the correct regclass!");
655   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
656   MF.addLiveIn(PReg, VReg);
657   return VReg;
658 }
659
660 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
661                                                bool isStdCall) {
662   unsigned NumArgs = Op.Val->getNumValues() - 1;
663   MachineFunction &MF = DAG.getMachineFunction();
664   MachineFrameInfo *MFI = MF.getFrameInfo();
665   SDOperand Root = Op.getOperand(0);
666   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
667
668   // Assign locations to all of the incoming arguments.
669   SmallVector<CCValAssign, 16> ArgLocs;
670   CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
671                  ArgLocs);
672   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
673    
674   SmallVector<SDOperand, 8> ArgValues;
675   unsigned LastVal = ~0U;
676   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
677     CCValAssign &VA = ArgLocs[i];
678     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
679     // places.
680     assert(VA.getValNo() != LastVal &&
681            "Don't support value assigned to multiple locs yet");
682     LastVal = VA.getValNo();
683     
684     if (VA.isRegLoc()) {
685       MVT::ValueType RegVT = VA.getLocVT();
686       TargetRegisterClass *RC;
687       if (RegVT == MVT::i32)
688         RC = X86::GR32RegisterClass;
689       else {
690         assert(MVT::isVector(RegVT));
691         RC = X86::VR128RegisterClass;
692       }
693       
694       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
695       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
696       
697       // If this is an 8 or 16-bit value, it is really passed promoted to 32
698       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
699       // right size.
700       if (VA.getLocInfo() == CCValAssign::SExt)
701         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
702                                DAG.getValueType(VA.getValVT()));
703       else if (VA.getLocInfo() == CCValAssign::ZExt)
704         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
705                                DAG.getValueType(VA.getValVT()));
706       
707       if (VA.getLocInfo() != CCValAssign::Full)
708         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
709       
710       ArgValues.push_back(ArgValue);
711     } else {
712       assert(VA.isMemLoc());
713       
714       // Create the nodes corresponding to a load from this parameter slot.
715       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
716                                       VA.getLocMemOffset());
717       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
718       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
719     }
720   }
721   
722   unsigned StackSize = CCInfo.getNextStackOffset();
723
724   ArgValues.push_back(Root);
725
726   // If the function takes variable number of arguments, make a frame index for
727   // the start of the first vararg value... for expansion of llvm.va_start.
728   if (isVarArg)
729     VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
730
731   if (isStdCall && !isVarArg) {
732     BytesToPopOnReturn  = StackSize;    // Callee pops everything..
733     BytesCallerReserves = 0;
734   } else {
735     BytesToPopOnReturn  = 0; // Callee pops nothing.
736     
737     // If this is an sret function, the return should pop the hidden pointer.
738     if (NumArgs &&
739         (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
740          ISD::ParamFlags::StructReturn))
741       BytesToPopOnReturn = 4;  
742     
743     BytesCallerReserves = StackSize;
744   }
745   
746   RegSaveFrameIndex = 0xAAAAAAA;  // X86-64 only.
747   ReturnAddrIndex = 0;            // No return address slot generated yet.
748
749   MF.getInfo<X86MachineFunctionInfo>()
750     ->setBytesToPopOnReturn(BytesToPopOnReturn);
751
752   // Return the new list of results.
753   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
754                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
755 }
756
757 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
758                                             unsigned CC) {
759   SDOperand Chain     = Op.getOperand(0);
760   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
761   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
762   SDOperand Callee    = Op.getOperand(4);
763   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
764
765   // Analyze operands of the call, assigning locations to each operand.
766   SmallVector<CCValAssign, 16> ArgLocs;
767   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
768   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
769   
770   // Get a count of how many bytes are to be pushed on the stack.
771   unsigned NumBytes = CCInfo.getNextStackOffset();
772
773   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
774
775   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
776   SmallVector<SDOperand, 8> MemOpChains;
777
778   SDOperand StackPtr;
779
780   // Walk the register/memloc assignments, inserting copies/loads.
781   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
782     CCValAssign &VA = ArgLocs[i];
783     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
784     
785     // Promote the value if needed.
786     switch (VA.getLocInfo()) {
787     default: assert(0 && "Unknown loc info!");
788     case CCValAssign::Full: break;
789     case CCValAssign::SExt:
790       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
791       break;
792     case CCValAssign::ZExt:
793       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
794       break;
795     case CCValAssign::AExt:
796       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
797       break;
798     }
799     
800     if (VA.isRegLoc()) {
801       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
802     } else {
803       assert(VA.isMemLoc());
804       if (StackPtr.Val == 0)
805         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
806       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
807       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
808       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
809     }
810   }
811
812   // If the first argument is an sret pointer, remember it.
813   bool isSRet = NumOps &&
814     (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
815      ISD::ParamFlags::StructReturn);
816   
817   if (!MemOpChains.empty())
818     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
819                         &MemOpChains[0], MemOpChains.size());
820
821   // Build a sequence of copy-to-reg nodes chained together with token chain
822   // and flag operands which copy the outgoing args into registers.
823   SDOperand InFlag;
824   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
825     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
826                              InFlag);
827     InFlag = Chain.getValue(1);
828   }
829
830   // ELF / PIC requires GOT in the EBX register before function calls via PLT
831   // GOT pointer.
832   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
833       Subtarget->isPICStyleGOT()) {
834     Chain = DAG.getCopyToReg(Chain, X86::EBX,
835                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
836                              InFlag);
837     InFlag = Chain.getValue(1);
838   }
839   
840   // If the callee is a GlobalAddress node (quite common, every direct call is)
841   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
842   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
843     // We should use extra load for direct calls to dllimported functions in
844     // non-JIT mode.
845     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
846                                         getTargetMachine(), true))
847       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
848   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
849     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
850
851   // Returns a chain & a flag for retval copy to use.
852   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
853   SmallVector<SDOperand, 8> Ops;
854   Ops.push_back(Chain);
855   Ops.push_back(Callee);
856
857   // Add argument registers to the end of the list so that they are known live
858   // into the call.
859   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
860     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
861                                   RegsToPass[i].second.getValueType()));
862
863   // Add an implicit use GOT pointer in EBX.
864   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
865       Subtarget->isPICStyleGOT())
866     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
867   
868   if (InFlag.Val)
869     Ops.push_back(InFlag);
870
871   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
872                       NodeTys, &Ops[0], Ops.size());
873   InFlag = Chain.getValue(1);
874
875   // Create the CALLSEQ_END node.
876   unsigned NumBytesForCalleeToPush = 0;
877
878   if (CC == CallingConv::X86_StdCall) {
879     if (isVarArg)
880       NumBytesForCalleeToPush = isSRet ? 4 : 0;
881     else
882       NumBytesForCalleeToPush = NumBytes;
883   } else {
884     // If this is is a call to a struct-return function, the callee
885     // pops the hidden struct pointer, so we have to push it back.
886     // This is common for Darwin/X86, Linux & Mingw32 targets.
887     NumBytesForCalleeToPush = isSRet ? 4 : 0;
888   }
889   
890   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
891   Ops.clear();
892   Ops.push_back(Chain);
893   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
894   Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
895   Ops.push_back(InFlag);
896   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
897   InFlag = Chain.getValue(1);
898
899   // Handle result values, copying them out of physregs into vregs that we
900   // return.
901   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
902 }
903
904
905 //===----------------------------------------------------------------------===//
906 //                   FastCall Calling Convention implementation
907 //===----------------------------------------------------------------------===//
908 //
909 // The X86 'fastcall' calling convention passes up to two integer arguments in
910 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
911 // and requires that the callee pop its arguments off the stack (allowing proper
912 // tail calls), and has the same return value conventions as C calling convs.
913 //
914 // This calling convention always arranges for the callee pop value to be 8n+4
915 // bytes, which is needed for tail recursion elimination and stack alignment
916 // reasons.
917 SDOperand
918 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
919   MachineFunction &MF = DAG.getMachineFunction();
920   MachineFrameInfo *MFI = MF.getFrameInfo();
921   SDOperand Root = Op.getOperand(0);
922
923   // Assign locations to all of the incoming arguments.
924   SmallVector<CCValAssign, 16> ArgLocs;
925   CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
926                  ArgLocs);
927   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
928   
929   SmallVector<SDOperand, 8> ArgValues;
930   unsigned LastVal = ~0U;
931   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
932     CCValAssign &VA = ArgLocs[i];
933     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
934     // places.
935     assert(VA.getValNo() != LastVal &&
936            "Don't support value assigned to multiple locs yet");
937     LastVal = VA.getValNo();
938     
939     if (VA.isRegLoc()) {
940       MVT::ValueType RegVT = VA.getLocVT();
941       TargetRegisterClass *RC;
942       if (RegVT == MVT::i32)
943         RC = X86::GR32RegisterClass;
944       else {
945         assert(MVT::isVector(RegVT));
946         RC = X86::VR128RegisterClass;
947       }
948       
949       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
950       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
951       
952       // If this is an 8 or 16-bit value, it is really passed promoted to 32
953       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
954       // right size.
955       if (VA.getLocInfo() == CCValAssign::SExt)
956         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
957                                DAG.getValueType(VA.getValVT()));
958       else if (VA.getLocInfo() == CCValAssign::ZExt)
959         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
960                                DAG.getValueType(VA.getValVT()));
961       
962       if (VA.getLocInfo() != CCValAssign::Full)
963         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
964       
965       ArgValues.push_back(ArgValue);
966     } else {
967       assert(VA.isMemLoc());
968       
969       // Create the nodes corresponding to a load from this parameter slot.
970       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
971                                       VA.getLocMemOffset());
972       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
973       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
974     }
975   }
976   
977   ArgValues.push_back(Root);
978
979   unsigned StackSize = CCInfo.getNextStackOffset();
980
981   if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
982     // Make sure the instruction takes 8n+4 bytes to make sure the start of the
983     // arguments and the arguments after the retaddr has been pushed are aligned.
984     if ((StackSize & 7) == 0)
985       StackSize += 4;
986   }
987
988   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
989   RegSaveFrameIndex = 0xAAAAAAA;   // X86-64 only.
990   ReturnAddrIndex = 0;             // No return address slot generated yet.
991   BytesToPopOnReturn = StackSize;  // Callee pops all stack arguments.
992   BytesCallerReserves = 0;
993
994   MF.getInfo<X86MachineFunctionInfo>()
995     ->setBytesToPopOnReturn(BytesToPopOnReturn);
996
997   // Return the new list of results.
998   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
999                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1000 }
1001
1002 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1003                                                unsigned CC) {
1004   SDOperand Chain     = Op.getOperand(0);
1005   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1006   SDOperand Callee    = Op.getOperand(4);
1007
1008   // Analyze operands of the call, assigning locations to each operand.
1009   SmallVector<CCValAssign, 16> ArgLocs;
1010   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
1011   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1012   
1013   // Get a count of how many bytes are to be pushed on the stack.
1014   unsigned NumBytes = CCInfo.getNextStackOffset();
1015
1016   if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1017     // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1018     // arguments and the arguments after the retaddr has been pushed are aligned.
1019     if ((NumBytes & 7) == 0)
1020       NumBytes += 4;
1021   }
1022
1023   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1024   
1025   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1026   SmallVector<SDOperand, 8> MemOpChains;
1027   
1028   SDOperand StackPtr;
1029   
1030   // Walk the register/memloc assignments, inserting copies/loads.
1031   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1032     CCValAssign &VA = ArgLocs[i];
1033     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1034     
1035     // Promote the value if needed.
1036     switch (VA.getLocInfo()) {
1037       default: assert(0 && "Unknown loc info!");
1038       case CCValAssign::Full: break;
1039       case CCValAssign::SExt:
1040         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1041         break;
1042       case CCValAssign::ZExt:
1043         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1044         break;
1045       case CCValAssign::AExt:
1046         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1047         break;
1048     }
1049     
1050     if (VA.isRegLoc()) {
1051       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1052     } else {
1053       assert(VA.isMemLoc());
1054       if (StackPtr.Val == 0)
1055         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1056       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1057       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1058       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1059     }
1060   }
1061
1062   if (!MemOpChains.empty())
1063     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1064                         &MemOpChains[0], MemOpChains.size());
1065
1066   // Build a sequence of copy-to-reg nodes chained together with token chain
1067   // and flag operands which copy the outgoing args into registers.
1068   SDOperand InFlag;
1069   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1070     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1071                              InFlag);
1072     InFlag = Chain.getValue(1);
1073   }
1074
1075   // If the callee is a GlobalAddress node (quite common, every direct call is)
1076   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1077   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1078     // We should use extra load for direct calls to dllimported functions in
1079     // non-JIT mode.
1080     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1081                                         getTargetMachine(), true))
1082       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1083   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1084     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1085
1086   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1087   // GOT pointer.
1088   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1089       Subtarget->isPICStyleGOT()) {
1090     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1091                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1092                              InFlag);
1093     InFlag = Chain.getValue(1);
1094   }
1095
1096   // Returns a chain & a flag for retval copy to use.
1097   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1098   SmallVector<SDOperand, 8> Ops;
1099   Ops.push_back(Chain);
1100   Ops.push_back(Callee);
1101
1102   // Add argument registers to the end of the list so that they are known live
1103   // into the call.
1104   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1105     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1106                                   RegsToPass[i].second.getValueType()));
1107
1108   // Add an implicit use GOT pointer in EBX.
1109   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1110       Subtarget->isPICStyleGOT())
1111     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1112
1113   if (InFlag.Val)
1114     Ops.push_back(InFlag);
1115
1116   // FIXME: Do not generate X86ISD::TAILCALL for now.
1117   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1118                       NodeTys, &Ops[0], Ops.size());
1119   InFlag = Chain.getValue(1);
1120
1121   // Returns a flag for retval copy to use.
1122   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1123   Ops.clear();
1124   Ops.push_back(Chain);
1125   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1126   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1127   Ops.push_back(InFlag);
1128   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1129   InFlag = Chain.getValue(1);
1130
1131   // Handle result values, copying them out of physregs into vregs that we
1132   // return.
1133   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1134 }
1135
1136
1137 //===----------------------------------------------------------------------===//
1138 //                 X86-64 C Calling Convention implementation
1139 //===----------------------------------------------------------------------===//
1140
1141 SDOperand
1142 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1143   MachineFunction &MF = DAG.getMachineFunction();
1144   MachineFrameInfo *MFI = MF.getFrameInfo();
1145   SDOperand Root = Op.getOperand(0);
1146   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1147
1148   static const unsigned GPR64ArgRegs[] = {
1149     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8,  X86::R9
1150   };
1151   static const unsigned XMMArgRegs[] = {
1152     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1153     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1154   };
1155
1156   
1157   // Assign locations to all of the incoming arguments.
1158   SmallVector<CCValAssign, 16> ArgLocs;
1159   CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
1160                  ArgLocs);
1161   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1162   
1163   SmallVector<SDOperand, 8> ArgValues;
1164   unsigned LastVal = ~0U;
1165   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1166     CCValAssign &VA = ArgLocs[i];
1167     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1168     // places.
1169     assert(VA.getValNo() != LastVal &&
1170            "Don't support value assigned to multiple locs yet");
1171     LastVal = VA.getValNo();
1172     
1173     if (VA.isRegLoc()) {
1174       MVT::ValueType RegVT = VA.getLocVT();
1175       TargetRegisterClass *RC;
1176       if (RegVT == MVT::i32)
1177         RC = X86::GR32RegisterClass;
1178       else if (RegVT == MVT::i64)
1179         RC = X86::GR64RegisterClass;
1180       else if (RegVT == MVT::f32)
1181         RC = X86::FR32RegisterClass;
1182       else if (RegVT == MVT::f64)
1183         RC = X86::FR64RegisterClass;
1184       else {
1185         assert(MVT::isVector(RegVT));
1186         if (MVT::getSizeInBits(RegVT) == 64)
1187           RC = X86::VR64RegisterClass;
1188         else
1189           RC = X86::VR128RegisterClass;
1190       }
1191
1192       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1193       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1194       
1195       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1196       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1197       // right size.
1198       if (VA.getLocInfo() == CCValAssign::SExt)
1199         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1200                                DAG.getValueType(VA.getValVT()));
1201       else if (VA.getLocInfo() == CCValAssign::ZExt)
1202         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1203                                DAG.getValueType(VA.getValVT()));
1204       
1205       if (VA.getLocInfo() != CCValAssign::Full)
1206         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1207       
1208       ArgValues.push_back(ArgValue);
1209     } else {
1210       assert(VA.isMemLoc());
1211     
1212       // Create the nodes corresponding to a load from this parameter slot.
1213       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1214                                       VA.getLocMemOffset());
1215       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1216       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
1217     }
1218   }
1219   
1220   unsigned StackSize = CCInfo.getNextStackOffset();
1221   
1222   // If the function takes variable number of arguments, make a frame index for
1223   // the start of the first vararg value... for expansion of llvm.va_start.
1224   if (isVarArg) {
1225     unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1226     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1227     
1228     // For X86-64, if there are vararg parameters that are passed via
1229     // registers, then we must store them to their spots on the stack so they
1230     // may be loaded by deferencing the result of va_next.
1231     VarArgsGPOffset = NumIntRegs * 8;
1232     VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1233     VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1234     RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1235
1236     // Store the integer parameter registers.
1237     SmallVector<SDOperand, 8> MemOps;
1238     SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1239     SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1240                               DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1241     for (; NumIntRegs != 6; ++NumIntRegs) {
1242       unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1243                                 X86::GR64RegisterClass);
1244       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1245       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1246       MemOps.push_back(Store);
1247       FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1248                         DAG.getConstant(8, getPointerTy()));
1249     }
1250
1251     // Now store the XMM (fp + vector) parameter registers.
1252     FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1253                       DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1254     for (; NumXMMRegs != 8; ++NumXMMRegs) {
1255       unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1256                                 X86::VR128RegisterClass);
1257       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1258       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1259       MemOps.push_back(Store);
1260       FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1261                         DAG.getConstant(16, getPointerTy()));
1262     }
1263     if (!MemOps.empty())
1264         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1265                            &MemOps[0], MemOps.size());
1266   }
1267
1268   ArgValues.push_back(Root);
1269
1270   ReturnAddrIndex = 0;     // No return address slot generated yet.
1271   BytesToPopOnReturn = 0;  // Callee pops nothing.
1272   BytesCallerReserves = StackSize;
1273
1274   // Return the new list of results.
1275   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1276                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1277 }
1278
1279 SDOperand
1280 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1281                                         unsigned CC) {
1282   SDOperand Chain     = Op.getOperand(0);
1283   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1284   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1285   SDOperand Callee    = Op.getOperand(4);
1286   
1287   // Analyze operands of the call, assigning locations to each operand.
1288   SmallVector<CCValAssign, 16> ArgLocs;
1289   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
1290   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1291     
1292   // Get a count of how many bytes are to be pushed on the stack.
1293   unsigned NumBytes = CCInfo.getNextStackOffset();
1294   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1295
1296   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1297   SmallVector<SDOperand, 8> MemOpChains;
1298
1299   SDOperand StackPtr;
1300   
1301   // Walk the register/memloc assignments, inserting copies/loads.
1302   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1303     CCValAssign &VA = ArgLocs[i];
1304     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1305     
1306     // Promote the value if needed.
1307     switch (VA.getLocInfo()) {
1308     default: assert(0 && "Unknown loc info!");
1309     case CCValAssign::Full: break;
1310     case CCValAssign::SExt:
1311       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1312       break;
1313     case CCValAssign::ZExt:
1314       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1315       break;
1316     case CCValAssign::AExt:
1317       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1318       break;
1319     }
1320     
1321     if (VA.isRegLoc()) {
1322       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1323     } else {
1324       assert(VA.isMemLoc());
1325       if (StackPtr.Val == 0)
1326         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1327       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1328       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1329       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1330     }
1331   }
1332   
1333   if (!MemOpChains.empty())
1334     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1335                         &MemOpChains[0], MemOpChains.size());
1336
1337   // Build a sequence of copy-to-reg nodes chained together with token chain
1338   // and flag operands which copy the outgoing args into registers.
1339   SDOperand InFlag;
1340   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1341     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1342                              InFlag);
1343     InFlag = Chain.getValue(1);
1344   }
1345
1346   if (isVarArg) {
1347     // From AMD64 ABI document:
1348     // For calls that may call functions that use varargs or stdargs
1349     // (prototype-less calls or calls to functions containing ellipsis (...) in
1350     // the declaration) %al is used as hidden argument to specify the number
1351     // of SSE registers used. The contents of %al do not need to match exactly
1352     // the number of registers, but must be an ubound on the number of SSE
1353     // registers used and is in the range 0 - 8 inclusive.
1354     
1355     // Count the number of XMM registers allocated.
1356     static const unsigned XMMArgRegs[] = {
1357       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1358       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1359     };
1360     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1361     
1362     Chain = DAG.getCopyToReg(Chain, X86::AL,
1363                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1364     InFlag = Chain.getValue(1);
1365   }
1366
1367   // If the callee is a GlobalAddress node (quite common, every direct call is)
1368   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1369   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1370     // We should use extra load for direct calls to dllimported functions in
1371     // non-JIT mode.
1372     if (getTargetMachine().getCodeModel() != CodeModel::Large
1373         && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1374                                            getTargetMachine(), true))
1375       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1376   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1377     if (getTargetMachine().getCodeModel() != CodeModel::Large)
1378       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1379
1380   // Returns a chain & a flag for retval copy to use.
1381   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1382   SmallVector<SDOperand, 8> Ops;
1383   Ops.push_back(Chain);
1384   Ops.push_back(Callee);
1385
1386   // Add argument registers to the end of the list so that they are known live
1387   // into the call.
1388   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1389     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1390                                   RegsToPass[i].second.getValueType()));
1391
1392   if (InFlag.Val)
1393     Ops.push_back(InFlag);
1394
1395   // FIXME: Do not generate X86ISD::TAILCALL for now.
1396   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1397                       NodeTys, &Ops[0], Ops.size());
1398   InFlag = Chain.getValue(1);
1399
1400   // Returns a flag for retval copy to use.
1401   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1402   Ops.clear();
1403   Ops.push_back(Chain);
1404   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1405   Ops.push_back(DAG.getConstant(0, getPointerTy()));
1406   Ops.push_back(InFlag);
1407   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1408   InFlag = Chain.getValue(1);
1409   
1410   // Handle result values, copying them out of physregs into vregs that we
1411   // return.
1412   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1413 }
1414
1415
1416 //===----------------------------------------------------------------------===//
1417 //                           Other Lowering Hooks
1418 //===----------------------------------------------------------------------===//
1419
1420
1421 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1422   if (ReturnAddrIndex == 0) {
1423     // Set up a frame object for the return address.
1424     MachineFunction &MF = DAG.getMachineFunction();
1425     if (Subtarget->is64Bit())
1426       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1427     else
1428       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1429   }
1430
1431   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1432 }
1433
1434
1435
1436 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1437 /// specific condition code. It returns a false if it cannot do a direct
1438 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1439 /// needed.
1440 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1441                            unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1442                            SelectionDAG &DAG) {
1443   X86CC = X86::COND_INVALID;
1444   if (!isFP) {
1445     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1446       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1447         // X > -1   -> X == 0, jump !sign.
1448         RHS = DAG.getConstant(0, RHS.getValueType());
1449         X86CC = X86::COND_NS;
1450         return true;
1451       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1452         // X < 0   -> X == 0, jump on sign.
1453         X86CC = X86::COND_S;
1454         return true;
1455       }
1456     }
1457
1458     switch (SetCCOpcode) {
1459     default: break;
1460     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1461     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1462     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1463     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1464     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1465     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1466     case ISD::SETULT: X86CC = X86::COND_B;  break;
1467     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1468     case ISD::SETULE: X86CC = X86::COND_BE; break;
1469     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1470     }
1471   } else {
1472     // On a floating point condition, the flags are set as follows:
1473     // ZF  PF  CF   op
1474     //  0 | 0 | 0 | X > Y
1475     //  0 | 0 | 1 | X < Y
1476     //  1 | 0 | 0 | X == Y
1477     //  1 | 1 | 1 | unordered
1478     bool Flip = false;
1479     switch (SetCCOpcode) {
1480     default: break;
1481     case ISD::SETUEQ:
1482     case ISD::SETEQ: X86CC = X86::COND_E;  break;
1483     case ISD::SETOLT: Flip = true; // Fallthrough
1484     case ISD::SETOGT:
1485     case ISD::SETGT: X86CC = X86::COND_A;  break;
1486     case ISD::SETOLE: Flip = true; // Fallthrough
1487     case ISD::SETOGE:
1488     case ISD::SETGE: X86CC = X86::COND_AE; break;
1489     case ISD::SETUGT: Flip = true; // Fallthrough
1490     case ISD::SETULT:
1491     case ISD::SETLT: X86CC = X86::COND_B;  break;
1492     case ISD::SETUGE: Flip = true; // Fallthrough
1493     case ISD::SETULE:
1494     case ISD::SETLE: X86CC = X86::COND_BE; break;
1495     case ISD::SETONE:
1496     case ISD::SETNE: X86CC = X86::COND_NE; break;
1497     case ISD::SETUO: X86CC = X86::COND_P;  break;
1498     case ISD::SETO:  X86CC = X86::COND_NP; break;
1499     }
1500     if (Flip)
1501       std::swap(LHS, RHS);
1502   }
1503
1504   return X86CC != X86::COND_INVALID;
1505 }
1506
1507 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1508 /// code. Current x86 isa includes the following FP cmov instructions:
1509 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1510 static bool hasFPCMov(unsigned X86CC) {
1511   switch (X86CC) {
1512   default:
1513     return false;
1514   case X86::COND_B:
1515   case X86::COND_BE:
1516   case X86::COND_E:
1517   case X86::COND_P:
1518   case X86::COND_A:
1519   case X86::COND_AE:
1520   case X86::COND_NE:
1521   case X86::COND_NP:
1522     return true;
1523   }
1524 }
1525
1526 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1527 /// true if Op is undef or if its value falls within the specified range (L, H].
1528 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1529   if (Op.getOpcode() == ISD::UNDEF)
1530     return true;
1531
1532   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1533   return (Val >= Low && Val < Hi);
1534 }
1535
1536 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
1537 /// true if Op is undef or if its value equal to the specified value.
1538 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1539   if (Op.getOpcode() == ISD::UNDEF)
1540     return true;
1541   return cast<ConstantSDNode>(Op)->getValue() == Val;
1542 }
1543
1544 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1545 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1546 bool X86::isPSHUFDMask(SDNode *N) {
1547   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1548
1549   if (N->getNumOperands() != 4)
1550     return false;
1551
1552   // Check if the value doesn't reference the second vector.
1553   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1554     SDOperand Arg = N->getOperand(i);
1555     if (Arg.getOpcode() == ISD::UNDEF) continue;
1556     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1557     if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1558       return false;
1559   }
1560
1561   return true;
1562 }
1563
1564 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1565 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1566 bool X86::isPSHUFHWMask(SDNode *N) {
1567   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1568
1569   if (N->getNumOperands() != 8)
1570     return false;
1571
1572   // Lower quadword copied in order.
1573   for (unsigned i = 0; i != 4; ++i) {
1574     SDOperand Arg = N->getOperand(i);
1575     if (Arg.getOpcode() == ISD::UNDEF) continue;
1576     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1577     if (cast<ConstantSDNode>(Arg)->getValue() != i)
1578       return false;
1579   }
1580
1581   // Upper quadword shuffled.
1582   for (unsigned i = 4; i != 8; ++i) {
1583     SDOperand Arg = N->getOperand(i);
1584     if (Arg.getOpcode() == ISD::UNDEF) continue;
1585     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1586     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1587     if (Val < 4 || Val > 7)
1588       return false;
1589   }
1590
1591   return true;
1592 }
1593
1594 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1595 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1596 bool X86::isPSHUFLWMask(SDNode *N) {
1597   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1598
1599   if (N->getNumOperands() != 8)
1600     return false;
1601
1602   // Upper quadword copied in order.
1603   for (unsigned i = 4; i != 8; ++i)
1604     if (!isUndefOrEqual(N->getOperand(i), i))
1605       return false;
1606
1607   // Lower quadword shuffled.
1608   for (unsigned i = 0; i != 4; ++i)
1609     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1610       return false;
1611
1612   return true;
1613 }
1614
1615 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1616 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
1617 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
1618   if (NumElems != 2 && NumElems != 4) return false;
1619
1620   unsigned Half = NumElems / 2;
1621   for (unsigned i = 0; i < Half; ++i)
1622     if (!isUndefOrInRange(Elems[i], 0, NumElems))
1623       return false;
1624   for (unsigned i = Half; i < NumElems; ++i)
1625     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
1626       return false;
1627
1628   return true;
1629 }
1630
1631 bool X86::isSHUFPMask(SDNode *N) {
1632   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1633   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
1634 }
1635
1636 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
1637 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1638 /// half elements to come from vector 1 (which would equal the dest.) and
1639 /// the upper half to come from vector 2.
1640 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
1641   if (NumOps != 2 && NumOps != 4) return false;
1642
1643   unsigned Half = NumOps / 2;
1644   for (unsigned i = 0; i < Half; ++i)
1645     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
1646       return false;
1647   for (unsigned i = Half; i < NumOps; ++i)
1648     if (!isUndefOrInRange(Ops[i], 0, NumOps))
1649       return false;
1650   return true;
1651 }
1652
1653 static bool isCommutedSHUFP(SDNode *N) {
1654   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1655   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
1656 }
1657
1658 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1659 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1660 bool X86::isMOVHLPSMask(SDNode *N) {
1661   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1662
1663   if (N->getNumOperands() != 4)
1664     return false;
1665
1666   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1667   return isUndefOrEqual(N->getOperand(0), 6) &&
1668          isUndefOrEqual(N->getOperand(1), 7) &&
1669          isUndefOrEqual(N->getOperand(2), 2) &&
1670          isUndefOrEqual(N->getOperand(3), 3);
1671 }
1672
1673 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
1674 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
1675 /// <2, 3, 2, 3>
1676 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
1677   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1678
1679   if (N->getNumOperands() != 4)
1680     return false;
1681
1682   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
1683   return isUndefOrEqual(N->getOperand(0), 2) &&
1684          isUndefOrEqual(N->getOperand(1), 3) &&
1685          isUndefOrEqual(N->getOperand(2), 2) &&
1686          isUndefOrEqual(N->getOperand(3), 3);
1687 }
1688
1689 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1690 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1691 bool X86::isMOVLPMask(SDNode *N) {
1692   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1693
1694   unsigned NumElems = N->getNumOperands();
1695   if (NumElems != 2 && NumElems != 4)
1696     return false;
1697
1698   for (unsigned i = 0; i < NumElems/2; ++i)
1699     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1700       return false;
1701
1702   for (unsigned i = NumElems/2; i < NumElems; ++i)
1703     if (!isUndefOrEqual(N->getOperand(i), i))
1704       return false;
1705
1706   return true;
1707 }
1708
1709 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1710 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1711 /// and MOVLHPS.
1712 bool X86::isMOVHPMask(SDNode *N) {
1713   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1714
1715   unsigned NumElems = N->getNumOperands();
1716   if (NumElems != 2 && NumElems != 4)
1717     return false;
1718
1719   for (unsigned i = 0; i < NumElems/2; ++i)
1720     if (!isUndefOrEqual(N->getOperand(i), i))
1721       return false;
1722
1723   for (unsigned i = 0; i < NumElems/2; ++i) {
1724     SDOperand Arg = N->getOperand(i + NumElems/2);
1725     if (!isUndefOrEqual(Arg, i + NumElems))
1726       return false;
1727   }
1728
1729   return true;
1730 }
1731
1732 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1733 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
1734 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
1735                          bool V2IsSplat = false) {
1736   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1737     return false;
1738
1739   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1740     SDOperand BitI  = Elts[i];
1741     SDOperand BitI1 = Elts[i+1];
1742     if (!isUndefOrEqual(BitI, j))
1743       return false;
1744     if (V2IsSplat) {
1745       if (isUndefOrEqual(BitI1, NumElts))
1746         return false;
1747     } else {
1748       if (!isUndefOrEqual(BitI1, j + NumElts))
1749         return false;
1750     }
1751   }
1752
1753   return true;
1754 }
1755
1756 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1757   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1758   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1759 }
1760
1761 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1762 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
1763 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
1764                          bool V2IsSplat = false) {
1765   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1766     return false;
1767
1768   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1769     SDOperand BitI  = Elts[i];
1770     SDOperand BitI1 = Elts[i+1];
1771     if (!isUndefOrEqual(BitI, j + NumElts/2))
1772       return false;
1773     if (V2IsSplat) {
1774       if (isUndefOrEqual(BitI1, NumElts))
1775         return false;
1776     } else {
1777       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
1778         return false;
1779     }
1780   }
1781
1782   return true;
1783 }
1784
1785 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1786   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1787   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1788 }
1789
1790 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1791 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1792 /// <0, 0, 1, 1>
1793 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1794   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1795
1796   unsigned NumElems = N->getNumOperands();
1797   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1798     return false;
1799
1800   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1801     SDOperand BitI  = N->getOperand(i);
1802     SDOperand BitI1 = N->getOperand(i+1);
1803
1804     if (!isUndefOrEqual(BitI, j))
1805       return false;
1806     if (!isUndefOrEqual(BitI1, j))
1807       return false;
1808   }
1809
1810   return true;
1811 }
1812
1813 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
1814 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
1815 /// <2, 2, 3, 3>
1816 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
1817   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1818
1819   unsigned NumElems = N->getNumOperands();
1820   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1821     return false;
1822
1823   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
1824     SDOperand BitI  = N->getOperand(i);
1825     SDOperand BitI1 = N->getOperand(i + 1);
1826
1827     if (!isUndefOrEqual(BitI, j))
1828       return false;
1829     if (!isUndefOrEqual(BitI1, j))
1830       return false;
1831   }
1832
1833   return true;
1834 }
1835
1836 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1837 /// specifies a shuffle of elements that is suitable for input to MOVSS,
1838 /// MOVSD, and MOVD, i.e. setting the lowest element.
1839 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
1840   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1841     return false;
1842
1843   if (!isUndefOrEqual(Elts[0], NumElts))
1844     return false;
1845
1846   for (unsigned i = 1; i < NumElts; ++i) {
1847     if (!isUndefOrEqual(Elts[i], i))
1848       return false;
1849   }
1850
1851   return true;
1852 }
1853
1854 bool X86::isMOVLMask(SDNode *N) {
1855   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1856   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
1857 }
1858
1859 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1860 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
1861 /// element of vector 2 and the other elements to come from vector 1 in order.
1862 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
1863                            bool V2IsSplat = false,
1864                            bool V2IsUndef = false) {
1865   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
1866     return false;
1867
1868   if (!isUndefOrEqual(Ops[0], 0))
1869     return false;
1870
1871   for (unsigned i = 1; i < NumOps; ++i) {
1872     SDOperand Arg = Ops[i];
1873     if (!(isUndefOrEqual(Arg, i+NumOps) ||
1874           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
1875           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
1876       return false;
1877   }
1878
1879   return true;
1880 }
1881
1882 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
1883                            bool V2IsUndef = false) {
1884   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1885   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
1886                         V2IsSplat, V2IsUndef);
1887 }
1888
1889 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1890 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1891 bool X86::isMOVSHDUPMask(SDNode *N) {
1892   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1893
1894   if (N->getNumOperands() != 4)
1895     return false;
1896
1897   // Expect 1, 1, 3, 3
1898   for (unsigned i = 0; i < 2; ++i) {
1899     SDOperand Arg = N->getOperand(i);
1900     if (Arg.getOpcode() == ISD::UNDEF) continue;
1901     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1902     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1903     if (Val != 1) return false;
1904   }
1905
1906   bool HasHi = false;
1907   for (unsigned i = 2; i < 4; ++i) {
1908     SDOperand Arg = N->getOperand(i);
1909     if (Arg.getOpcode() == ISD::UNDEF) continue;
1910     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1911     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1912     if (Val != 3) return false;
1913     HasHi = true;
1914   }
1915
1916   // Don't use movshdup if it can be done with a shufps.
1917   return HasHi;
1918 }
1919
1920 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1921 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1922 bool X86::isMOVSLDUPMask(SDNode *N) {
1923   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1924
1925   if (N->getNumOperands() != 4)
1926     return false;
1927
1928   // Expect 0, 0, 2, 2
1929   for (unsigned i = 0; i < 2; ++i) {
1930     SDOperand Arg = N->getOperand(i);
1931     if (Arg.getOpcode() == ISD::UNDEF) continue;
1932     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1933     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1934     if (Val != 0) return false;
1935   }
1936
1937   bool HasHi = false;
1938   for (unsigned i = 2; i < 4; ++i) {
1939     SDOperand Arg = N->getOperand(i);
1940     if (Arg.getOpcode() == ISD::UNDEF) continue;
1941     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1942     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1943     if (Val != 2) return false;
1944     HasHi = true;
1945   }
1946
1947   // Don't use movshdup if it can be done with a shufps.
1948   return HasHi;
1949 }
1950
1951 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1952 /// a splat of a single element.
1953 static bool isSplatMask(SDNode *N) {
1954   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1955
1956   // This is a splat operation if each element of the permute is the same, and
1957   // if the value doesn't reference the second vector.
1958   unsigned NumElems = N->getNumOperands();
1959   SDOperand ElementBase;
1960   unsigned i = 0;
1961   for (; i != NumElems; ++i) {
1962     SDOperand Elt = N->getOperand(i);
1963     if (isa<ConstantSDNode>(Elt)) {
1964       ElementBase = Elt;
1965       break;
1966     }
1967   }
1968
1969   if (!ElementBase.Val)
1970     return false;
1971
1972   for (; i != NumElems; ++i) {
1973     SDOperand Arg = N->getOperand(i);
1974     if (Arg.getOpcode() == ISD::UNDEF) continue;
1975     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1976     if (Arg != ElementBase) return false;
1977   }
1978
1979   // Make sure it is a splat of the first vector operand.
1980   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
1981 }
1982
1983 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1984 /// a splat of a single element and it's a 2 or 4 element mask.
1985 bool X86::isSplatMask(SDNode *N) {
1986   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1987
1988   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
1989   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
1990     return false;
1991   return ::isSplatMask(N);
1992 }
1993
1994 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
1995 /// specifies a splat of zero element.
1996 bool X86::isSplatLoMask(SDNode *N) {
1997   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1998
1999   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2000     if (!isUndefOrEqual(N->getOperand(i), 0))
2001       return false;
2002   return true;
2003 }
2004
2005 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2006 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2007 /// instructions.
2008 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2009   unsigned NumOperands = N->getNumOperands();
2010   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2011   unsigned Mask = 0;
2012   for (unsigned i = 0; i < NumOperands; ++i) {
2013     unsigned Val = 0;
2014     SDOperand Arg = N->getOperand(NumOperands-i-1);
2015     if (Arg.getOpcode() != ISD::UNDEF)
2016       Val = cast<ConstantSDNode>(Arg)->getValue();
2017     if (Val >= NumOperands) Val -= NumOperands;
2018     Mask |= Val;
2019     if (i != NumOperands - 1)
2020       Mask <<= Shift;
2021   }
2022
2023   return Mask;
2024 }
2025
2026 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2027 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2028 /// instructions.
2029 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2030   unsigned Mask = 0;
2031   // 8 nodes, but we only care about the last 4.
2032   for (unsigned i = 7; i >= 4; --i) {
2033     unsigned Val = 0;
2034     SDOperand Arg = N->getOperand(i);
2035     if (Arg.getOpcode() != ISD::UNDEF)
2036       Val = cast<ConstantSDNode>(Arg)->getValue();
2037     Mask |= (Val - 4);
2038     if (i != 4)
2039       Mask <<= 2;
2040   }
2041
2042   return Mask;
2043 }
2044
2045 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2046 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2047 /// instructions.
2048 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2049   unsigned Mask = 0;
2050   // 8 nodes, but we only care about the first 4.
2051   for (int i = 3; i >= 0; --i) {
2052     unsigned Val = 0;
2053     SDOperand Arg = N->getOperand(i);
2054     if (Arg.getOpcode() != ISD::UNDEF)
2055       Val = cast<ConstantSDNode>(Arg)->getValue();
2056     Mask |= Val;
2057     if (i != 0)
2058       Mask <<= 2;
2059   }
2060
2061   return Mask;
2062 }
2063
2064 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2065 /// specifies a 8 element shuffle that can be broken into a pair of
2066 /// PSHUFHW and PSHUFLW.
2067 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2068   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2069
2070   if (N->getNumOperands() != 8)
2071     return false;
2072
2073   // Lower quadword shuffled.
2074   for (unsigned i = 0; i != 4; ++i) {
2075     SDOperand Arg = N->getOperand(i);
2076     if (Arg.getOpcode() == ISD::UNDEF) continue;
2077     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2078     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2079     if (Val > 4)
2080       return false;
2081   }
2082
2083   // Upper quadword shuffled.
2084   for (unsigned i = 4; i != 8; ++i) {
2085     SDOperand Arg = N->getOperand(i);
2086     if (Arg.getOpcode() == ISD::UNDEF) continue;
2087     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2088     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2089     if (Val < 4 || Val > 7)
2090       return false;
2091   }
2092
2093   return true;
2094 }
2095
2096 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2097 /// values in ther permute mask.
2098 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2099                                       SDOperand &V2, SDOperand &Mask,
2100                                       SelectionDAG &DAG) {
2101   MVT::ValueType VT = Op.getValueType();
2102   MVT::ValueType MaskVT = Mask.getValueType();
2103   MVT::ValueType EltVT = MVT::getVectorBaseType(MaskVT);
2104   unsigned NumElems = Mask.getNumOperands();
2105   SmallVector<SDOperand, 8> MaskVec;
2106
2107   for (unsigned i = 0; i != NumElems; ++i) {
2108     SDOperand Arg = Mask.getOperand(i);
2109     if (Arg.getOpcode() == ISD::UNDEF) {
2110       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2111       continue;
2112     }
2113     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2114     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2115     if (Val < NumElems)
2116       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2117     else
2118       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2119   }
2120
2121   std::swap(V1, V2);
2122   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2123   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2124 }
2125
2126 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2127 /// match movhlps. The lower half elements should come from upper half of
2128 /// V1 (and in order), and the upper half elements should come from the upper
2129 /// half of V2 (and in order).
2130 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2131   unsigned NumElems = Mask->getNumOperands();
2132   if (NumElems != 4)
2133     return false;
2134   for (unsigned i = 0, e = 2; i != e; ++i)
2135     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2136       return false;
2137   for (unsigned i = 2; i != 4; ++i)
2138     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2139       return false;
2140   return true;
2141 }
2142
2143 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2144 /// is promoted to a vector.
2145 static inline bool isScalarLoadToVector(SDNode *N) {
2146   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2147     N = N->getOperand(0).Val;
2148     return ISD::isNON_EXTLoad(N);
2149   }
2150   return false;
2151 }
2152
2153 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2154 /// match movlp{s|d}. The lower half elements should come from lower half of
2155 /// V1 (and in order), and the upper half elements should come from the upper
2156 /// half of V2 (and in order). And since V1 will become the source of the
2157 /// MOVLP, it must be either a vector load or a scalar load to vector.
2158 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2159   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2160     return false;
2161   // Is V2 is a vector load, don't do this transformation. We will try to use
2162   // load folding shufps op.
2163   if (ISD::isNON_EXTLoad(V2))
2164     return false;
2165
2166   unsigned NumElems = Mask->getNumOperands();
2167   if (NumElems != 2 && NumElems != 4)
2168     return false;
2169   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2170     if (!isUndefOrEqual(Mask->getOperand(i), i))
2171       return false;
2172   for (unsigned i = NumElems/2; i != NumElems; ++i)
2173     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2174       return false;
2175   return true;
2176 }
2177
2178 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2179 /// all the same.
2180 static bool isSplatVector(SDNode *N) {
2181   if (N->getOpcode() != ISD::BUILD_VECTOR)
2182     return false;
2183
2184   SDOperand SplatValue = N->getOperand(0);
2185   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2186     if (N->getOperand(i) != SplatValue)
2187       return false;
2188   return true;
2189 }
2190
2191 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2192 /// to an undef.
2193 static bool isUndefShuffle(SDNode *N) {
2194   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2195     return false;
2196
2197   SDOperand V1 = N->getOperand(0);
2198   SDOperand V2 = N->getOperand(1);
2199   SDOperand Mask = N->getOperand(2);
2200   unsigned NumElems = Mask.getNumOperands();
2201   for (unsigned i = 0; i != NumElems; ++i) {
2202     SDOperand Arg = Mask.getOperand(i);
2203     if (Arg.getOpcode() != ISD::UNDEF) {
2204       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2205       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2206         return false;
2207       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2208         return false;
2209     }
2210   }
2211   return true;
2212 }
2213
2214 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2215 /// constant +0.0.
2216 static inline bool isZeroNode(SDOperand Elt) {
2217   return ((isa<ConstantSDNode>(Elt) &&
2218            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2219           (isa<ConstantFPSDNode>(Elt) &&
2220            cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2221 }
2222
2223 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2224 /// to an zero vector.
2225 static bool isZeroShuffle(SDNode *N) {
2226   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2227     return false;
2228
2229   SDOperand V1 = N->getOperand(0);
2230   SDOperand V2 = N->getOperand(1);
2231   SDOperand Mask = N->getOperand(2);
2232   unsigned NumElems = Mask.getNumOperands();
2233   for (unsigned i = 0; i != NumElems; ++i) {
2234     SDOperand Arg = Mask.getOperand(i);
2235     if (Arg.getOpcode() != ISD::UNDEF) {
2236       unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2237       if (Idx < NumElems) {
2238         unsigned Opc = V1.Val->getOpcode();
2239         if (Opc == ISD::UNDEF)
2240           continue;
2241         if (Opc != ISD::BUILD_VECTOR ||
2242             !isZeroNode(V1.Val->getOperand(Idx)))
2243           return false;
2244       } else if (Idx >= NumElems) {
2245         unsigned Opc = V2.Val->getOpcode();
2246         if (Opc == ISD::UNDEF)
2247           continue;
2248         if (Opc != ISD::BUILD_VECTOR ||
2249             !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2250           return false;
2251       }
2252     }
2253   }
2254   return true;
2255 }
2256
2257 /// getZeroVector - Returns a vector of specified type with all zero elements.
2258 ///
2259 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2260   assert(MVT::isVector(VT) && "Expected a vector type");
2261   unsigned NumElems = MVT::getVectorNumElements(VT);
2262   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2263   bool isFP = MVT::isFloatingPoint(EVT);
2264   SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2265   SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2266   return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2267 }
2268
2269 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2270 /// that point to V2 points to its first element.
2271 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2272   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2273
2274   bool Changed = false;
2275   SmallVector<SDOperand, 8> MaskVec;
2276   unsigned NumElems = Mask.getNumOperands();
2277   for (unsigned i = 0; i != NumElems; ++i) {
2278     SDOperand Arg = Mask.getOperand(i);
2279     if (Arg.getOpcode() != ISD::UNDEF) {
2280       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2281       if (Val > NumElems) {
2282         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2283         Changed = true;
2284       }
2285     }
2286     MaskVec.push_back(Arg);
2287   }
2288
2289   if (Changed)
2290     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2291                        &MaskVec[0], MaskVec.size());
2292   return Mask;
2293 }
2294
2295 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2296 /// operation of specified width.
2297 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2298   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2299   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2300
2301   SmallVector<SDOperand, 8> MaskVec;
2302   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2303   for (unsigned i = 1; i != NumElems; ++i)
2304     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2305   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2306 }
2307
2308 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2309 /// of specified width.
2310 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2311   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2312   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2313   SmallVector<SDOperand, 8> MaskVec;
2314   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2315     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2316     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2317   }
2318   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2319 }
2320
2321 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2322 /// of specified width.
2323 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2324   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2325   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2326   unsigned Half = NumElems/2;
2327   SmallVector<SDOperand, 8> MaskVec;
2328   for (unsigned i = 0; i != Half; ++i) {
2329     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2330     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2331   }
2332   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2333 }
2334
2335 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2336 ///
2337 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2338   SDOperand V1 = Op.getOperand(0);
2339   SDOperand Mask = Op.getOperand(2);
2340   MVT::ValueType VT = Op.getValueType();
2341   unsigned NumElems = Mask.getNumOperands();
2342   Mask = getUnpacklMask(NumElems, DAG);
2343   while (NumElems != 4) {
2344     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2345     NumElems >>= 1;
2346   }
2347   V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2348
2349   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2350   Mask = getZeroVector(MaskVT, DAG);
2351   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2352                                   DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2353   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2354 }
2355
2356 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2357 /// vector of zero or undef vector.
2358 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2359                                              unsigned NumElems, unsigned Idx,
2360                                              bool isZero, SelectionDAG &DAG) {
2361   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2362   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2363   MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2364   SDOperand Zero = DAG.getConstant(0, EVT);
2365   SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2366   MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2367   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2368                                &MaskVec[0], MaskVec.size());
2369   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2370 }
2371
2372 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2373 ///
2374 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2375                                        unsigned NumNonZero, unsigned NumZero,
2376                                        SelectionDAG &DAG, TargetLowering &TLI) {
2377   if (NumNonZero > 8)
2378     return SDOperand();
2379
2380   SDOperand V(0, 0);
2381   bool First = true;
2382   for (unsigned i = 0; i < 16; ++i) {
2383     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2384     if (ThisIsNonZero && First) {
2385       if (NumZero)
2386         V = getZeroVector(MVT::v8i16, DAG);
2387       else
2388         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2389       First = false;
2390     }
2391
2392     if ((i & 1) != 0) {
2393       SDOperand ThisElt(0, 0), LastElt(0, 0);
2394       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2395       if (LastIsNonZero) {
2396         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2397       }
2398       if (ThisIsNonZero) {
2399         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2400         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2401                               ThisElt, DAG.getConstant(8, MVT::i8));
2402         if (LastIsNonZero)
2403           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2404       } else
2405         ThisElt = LastElt;
2406
2407       if (ThisElt.Val)
2408         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2409                         DAG.getConstant(i/2, TLI.getPointerTy()));
2410     }
2411   }
2412
2413   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2414 }
2415
2416 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2417 ///
2418 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2419                                        unsigned NumNonZero, unsigned NumZero,
2420                                        SelectionDAG &DAG, TargetLowering &TLI) {
2421   if (NumNonZero > 4)
2422     return SDOperand();
2423
2424   SDOperand V(0, 0);
2425   bool First = true;
2426   for (unsigned i = 0; i < 8; ++i) {
2427     bool isNonZero = (NonZeros & (1 << i)) != 0;
2428     if (isNonZero) {
2429       if (First) {
2430         if (NumZero)
2431           V = getZeroVector(MVT::v8i16, DAG);
2432         else
2433           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2434         First = false;
2435       }
2436       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2437                       DAG.getConstant(i, TLI.getPointerTy()));
2438     }
2439   }
2440
2441   return V;
2442 }
2443
2444 SDOperand
2445 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2446   // All zero's are handled with pxor.
2447   if (ISD::isBuildVectorAllZeros(Op.Val))
2448     return Op;
2449
2450   // All one's are handled with pcmpeqd.
2451   if (ISD::isBuildVectorAllOnes(Op.Val))
2452     return Op;
2453
2454   MVT::ValueType VT = Op.getValueType();
2455   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2456   unsigned EVTBits = MVT::getSizeInBits(EVT);
2457
2458   unsigned NumElems = Op.getNumOperands();
2459   unsigned NumZero  = 0;
2460   unsigned NumNonZero = 0;
2461   unsigned NonZeros = 0;
2462   std::set<SDOperand> Values;
2463   for (unsigned i = 0; i < NumElems; ++i) {
2464     SDOperand Elt = Op.getOperand(i);
2465     if (Elt.getOpcode() != ISD::UNDEF) {
2466       Values.insert(Elt);
2467       if (isZeroNode(Elt))
2468         NumZero++;
2469       else {
2470         NonZeros |= (1 << i);
2471         NumNonZero++;
2472       }
2473     }
2474   }
2475
2476   if (NumNonZero == 0)
2477     // Must be a mix of zero and undef. Return a zero vector.
2478     return getZeroVector(VT, DAG);
2479
2480   // Splat is obviously ok. Let legalizer expand it to a shuffle.
2481   if (Values.size() == 1)
2482     return SDOperand();
2483
2484   // Special case for single non-zero element.
2485   if (NumNonZero == 1) {
2486     unsigned Idx = CountTrailingZeros_32(NonZeros);
2487     SDOperand Item = Op.getOperand(Idx);
2488     Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2489     if (Idx == 0)
2490       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2491       return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2492                                          NumZero > 0, DAG);
2493
2494     if (EVTBits == 32) {
2495       // Turn it into a shuffle of zero and zero-extended scalar to vector.
2496       Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2497                                          DAG);
2498       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
2499       MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2500       SmallVector<SDOperand, 8> MaskVec;
2501       for (unsigned i = 0; i < NumElems; i++)
2502         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2503       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2504                                    &MaskVec[0], MaskVec.size());
2505       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2506                          DAG.getNode(ISD::UNDEF, VT), Mask);
2507     }
2508   }
2509
2510   // Let legalizer expand 2-wide build_vectors.
2511   if (EVTBits == 64)
2512     return SDOperand();
2513
2514   // If element VT is < 32 bits, convert it to inserts into a zero vector.
2515   if (EVTBits == 8 && NumElems == 16) {
2516     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
2517                                         *this);
2518     if (V.Val) return V;
2519   }
2520
2521   if (EVTBits == 16 && NumElems == 8) {
2522     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
2523                                         *this);
2524     if (V.Val) return V;
2525   }
2526
2527   // If element VT is == 32 bits, turn it into a number of shuffles.
2528   SmallVector<SDOperand, 8> V;
2529   V.resize(NumElems);
2530   if (NumElems == 4 && NumZero > 0) {
2531     for (unsigned i = 0; i < 4; ++i) {
2532       bool isZero = !(NonZeros & (1 << i));
2533       if (isZero)
2534         V[i] = getZeroVector(VT, DAG);
2535       else
2536         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2537     }
2538
2539     for (unsigned i = 0; i < 2; ++i) {
2540       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2541         default: break;
2542         case 0:
2543           V[i] = V[i*2];  // Must be a zero vector.
2544           break;
2545         case 1:
2546           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2547                              getMOVLMask(NumElems, DAG));
2548           break;
2549         case 2:
2550           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2551                              getMOVLMask(NumElems, DAG));
2552           break;
2553         case 3:
2554           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2555                              getUnpacklMask(NumElems, DAG));
2556           break;
2557       }
2558     }
2559
2560     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2561     // clears the upper bits.
2562     // FIXME: we can do the same for v4f32 case when we know both parts of
2563     // the lower half come from scalar_to_vector (loadf32). We should do
2564     // that in post legalizer dag combiner with target specific hooks.
2565     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2566       return V[0];
2567     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2568     MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2569     SmallVector<SDOperand, 8> MaskVec;
2570     bool Reverse = (NonZeros & 0x3) == 2;
2571     for (unsigned i = 0; i < 2; ++i)
2572       if (Reverse)
2573         MaskVec.push_back(DAG.getConstant(1-i, EVT));
2574       else
2575         MaskVec.push_back(DAG.getConstant(i, EVT));
2576     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2577     for (unsigned i = 0; i < 2; ++i)
2578       if (Reverse)
2579         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2580       else
2581         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2582     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2583                                      &MaskVec[0], MaskVec.size());
2584     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2585   }
2586
2587   if (Values.size() > 2) {
2588     // Expand into a number of unpckl*.
2589     // e.g. for v4f32
2590     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2591     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2592     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
2593     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2594     for (unsigned i = 0; i < NumElems; ++i)
2595       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2596     NumElems >>= 1;
2597     while (NumElems != 0) {
2598       for (unsigned i = 0; i < NumElems; ++i)
2599         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2600                            UnpckMask);
2601       NumElems >>= 1;
2602     }
2603     return V[0];
2604   }
2605
2606   return SDOperand();
2607 }
2608
2609 SDOperand
2610 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2611   SDOperand V1 = Op.getOperand(0);
2612   SDOperand V2 = Op.getOperand(1);
2613   SDOperand PermMask = Op.getOperand(2);
2614   MVT::ValueType VT = Op.getValueType();
2615   unsigned NumElems = PermMask.getNumOperands();
2616   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2617   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2618   bool V1IsSplat = false;
2619   bool V2IsSplat = false;
2620
2621   if (isUndefShuffle(Op.Val))
2622     return DAG.getNode(ISD::UNDEF, VT);
2623
2624   if (isZeroShuffle(Op.Val))
2625     return getZeroVector(VT, DAG);
2626
2627   if (isSplatMask(PermMask.Val)) {
2628     if (NumElems <= 4) return Op;
2629     // Promote it to a v4i32 splat.
2630     return PromoteSplat(Op, DAG);
2631   }
2632
2633   if (X86::isMOVLMask(PermMask.Val))
2634     return (V1IsUndef) ? V2 : Op;
2635
2636   if (X86::isMOVSHDUPMask(PermMask.Val) ||
2637       X86::isMOVSLDUPMask(PermMask.Val) ||
2638       X86::isMOVHLPSMask(PermMask.Val) ||
2639       X86::isMOVHPMask(PermMask.Val) ||
2640       X86::isMOVLPMask(PermMask.Val))
2641     return Op;
2642
2643   if (ShouldXformToMOVHLPS(PermMask.Val) ||
2644       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
2645     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2646
2647   bool Commuted = false;
2648   V1IsSplat = isSplatVector(V1.Val);
2649   V2IsSplat = isSplatVector(V2.Val);
2650   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
2651     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2652     std::swap(V1IsSplat, V2IsSplat);
2653     std::swap(V1IsUndef, V2IsUndef);
2654     Commuted = true;
2655   }
2656
2657   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
2658     if (V2IsUndef) return V1;
2659     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2660     if (V2IsSplat) {
2661       // V2 is a splat, so the mask may be malformed. That is, it may point
2662       // to any V2 element. The instruction selectior won't like this. Get
2663       // a corrected mask and commute to form a proper MOVS{S|D}.
2664       SDOperand NewMask = getMOVLMask(NumElems, DAG);
2665       if (NewMask.Val != PermMask.Val)
2666         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2667     }
2668     return Op;
2669   }
2670
2671   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2672       X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
2673       X86::isUNPCKLMask(PermMask.Val) ||
2674       X86::isUNPCKHMask(PermMask.Val))
2675     return Op;
2676
2677   if (V2IsSplat) {
2678     // Normalize mask so all entries that point to V2 points to its first
2679     // element then try to match unpck{h|l} again. If match, return a
2680     // new vector_shuffle with the corrected mask.
2681     SDOperand NewMask = NormalizeMask(PermMask, DAG);
2682     if (NewMask.Val != PermMask.Val) {
2683       if (X86::isUNPCKLMask(PermMask.Val, true)) {
2684         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2685         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2686       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2687         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2688         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2689       }
2690     }
2691   }
2692
2693   // Normalize the node to match x86 shuffle ops if needed
2694   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
2695       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2696
2697   if (Commuted) {
2698     // Commute is back and try unpck* again.
2699     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2700     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2701         X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
2702         X86::isUNPCKLMask(PermMask.Val) ||
2703         X86::isUNPCKHMask(PermMask.Val))
2704       return Op;
2705   }
2706
2707   // If VT is integer, try PSHUF* first, then SHUFP*.
2708   if (MVT::isInteger(VT)) {
2709     if (X86::isPSHUFDMask(PermMask.Val) ||
2710         X86::isPSHUFHWMask(PermMask.Val) ||
2711         X86::isPSHUFLWMask(PermMask.Val)) {
2712       if (V2.getOpcode() != ISD::UNDEF)
2713         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2714                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2715       return Op;
2716     }
2717
2718     if (X86::isSHUFPMask(PermMask.Val) &&
2719         MVT::getSizeInBits(VT) != 64)    // Don't do this for MMX.
2720       return Op;
2721
2722     // Handle v8i16 shuffle high / low shuffle node pair.
2723     if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2724       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2725       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2726       SmallVector<SDOperand, 8> MaskVec;
2727       for (unsigned i = 0; i != 4; ++i)
2728         MaskVec.push_back(PermMask.getOperand(i));
2729       for (unsigned i = 4; i != 8; ++i)
2730         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2731       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2732                                    &MaskVec[0], MaskVec.size());
2733       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2734       MaskVec.clear();
2735       for (unsigned i = 0; i != 4; ++i)
2736         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2737       for (unsigned i = 4; i != 8; ++i)
2738         MaskVec.push_back(PermMask.getOperand(i));
2739       Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
2740       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2741     }
2742   } else {
2743     // Floating point cases in the other order.
2744     if (X86::isSHUFPMask(PermMask.Val))
2745       return Op;
2746     if (X86::isPSHUFDMask(PermMask.Val) ||
2747         X86::isPSHUFHWMask(PermMask.Val) ||
2748         X86::isPSHUFLWMask(PermMask.Val)) {
2749       if (V2.getOpcode() != ISD::UNDEF)
2750         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2751                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2752       return Op;
2753     }
2754   }
2755
2756   if (NumElems == 4 && 
2757       // Don't do this for MMX.
2758       MVT::getSizeInBits(VT) != 64) {
2759     MVT::ValueType MaskVT = PermMask.getValueType();
2760     MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2761     SmallVector<std::pair<int, int>, 8> Locs;
2762     Locs.reserve(NumElems);
2763     SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2764     SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2765     unsigned NumHi = 0;
2766     unsigned NumLo = 0;
2767     // If no more than two elements come from either vector. This can be
2768     // implemented with two shuffles. First shuffle gather the elements.
2769     // The second shuffle, which takes the first shuffle as both of its
2770     // vector operands, put the elements into the right order.
2771     for (unsigned i = 0; i != NumElems; ++i) {
2772       SDOperand Elt = PermMask.getOperand(i);
2773       if (Elt.getOpcode() == ISD::UNDEF) {
2774         Locs[i] = std::make_pair(-1, -1);
2775       } else {
2776         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2777         if (Val < NumElems) {
2778           Locs[i] = std::make_pair(0, NumLo);
2779           Mask1[NumLo] = Elt;
2780           NumLo++;
2781         } else {
2782           Locs[i] = std::make_pair(1, NumHi);
2783           if (2+NumHi < NumElems)
2784             Mask1[2+NumHi] = Elt;
2785           NumHi++;
2786         }
2787       }
2788     }
2789     if (NumLo <= 2 && NumHi <= 2) {
2790       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2791                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2792                                    &Mask1[0], Mask1.size()));
2793       for (unsigned i = 0; i != NumElems; ++i) {
2794         if (Locs[i].first == -1)
2795           continue;
2796         else {
2797           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2798           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2799           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2800         }
2801       }
2802
2803       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2804                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2805                                      &Mask2[0], Mask2.size()));
2806     }
2807
2808     // Break it into (shuffle shuffle_hi, shuffle_lo).
2809     Locs.clear();
2810     SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2811     SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2812     SmallVector<SDOperand,8> *MaskPtr = &LoMask;
2813     unsigned MaskIdx = 0;
2814     unsigned LoIdx = 0;
2815     unsigned HiIdx = NumElems/2;
2816     for (unsigned i = 0; i != NumElems; ++i) {
2817       if (i == NumElems/2) {
2818         MaskPtr = &HiMask;
2819         MaskIdx = 1;
2820         LoIdx = 0;
2821         HiIdx = NumElems/2;
2822       }
2823       SDOperand Elt = PermMask.getOperand(i);
2824       if (Elt.getOpcode() == ISD::UNDEF) {
2825         Locs[i] = std::make_pair(-1, -1);
2826       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2827         Locs[i] = std::make_pair(MaskIdx, LoIdx);
2828         (*MaskPtr)[LoIdx] = Elt;
2829         LoIdx++;
2830       } else {
2831         Locs[i] = std::make_pair(MaskIdx, HiIdx);
2832         (*MaskPtr)[HiIdx] = Elt;
2833         HiIdx++;
2834       }
2835     }
2836
2837     SDOperand LoShuffle =
2838       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2839                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2840                               &LoMask[0], LoMask.size()));
2841     SDOperand HiShuffle =
2842       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2843                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2844                               &HiMask[0], HiMask.size()));
2845     SmallVector<SDOperand, 8> MaskOps;
2846     for (unsigned i = 0; i != NumElems; ++i) {
2847       if (Locs[i].first == -1) {
2848         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2849       } else {
2850         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2851         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2852       }
2853     }
2854     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2855                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2856                                    &MaskOps[0], MaskOps.size()));
2857   }
2858
2859   return SDOperand();
2860 }
2861
2862 SDOperand
2863 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2864   if (!isa<ConstantSDNode>(Op.getOperand(1)))
2865     return SDOperand();
2866
2867   MVT::ValueType VT = Op.getValueType();
2868   // TODO: handle v16i8.
2869   if (MVT::getSizeInBits(VT) == 16) {
2870     // Transform it so it match pextrw which produces a 32-bit result.
2871     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2872     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2873                                     Op.getOperand(0), Op.getOperand(1));
2874     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
2875                                     DAG.getValueType(VT));
2876     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2877   } else if (MVT::getSizeInBits(VT) == 32) {
2878     SDOperand Vec = Op.getOperand(0);
2879     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2880     if (Idx == 0)
2881       return Op;
2882     // SHUFPS the element to the lowest double word, then movss.
2883     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2884     SmallVector<SDOperand, 8> IdxVec;
2885     IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorBaseType(MaskVT)));
2886     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2887     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2888     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2889     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2890                                  &IdxVec[0], IdxVec.size());
2891     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2892                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2893     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2894                        DAG.getConstant(0, getPointerTy()));
2895   } else if (MVT::getSizeInBits(VT) == 64) {
2896     SDOperand Vec = Op.getOperand(0);
2897     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2898     if (Idx == 0)
2899       return Op;
2900
2901     // UNPCKHPD the element to the lowest double word, then movsd.
2902     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2903     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2904     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2905     SmallVector<SDOperand, 8> IdxVec;
2906     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorBaseType(MaskVT)));
2907     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2908     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2909                                  &IdxVec[0], IdxVec.size());
2910     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2911                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2912     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2913                        DAG.getConstant(0, getPointerTy()));
2914   }
2915
2916   return SDOperand();
2917 }
2918
2919 SDOperand
2920 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2921   // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2922   // as its second argument.
2923   MVT::ValueType VT = Op.getValueType();
2924   MVT::ValueType BaseVT = MVT::getVectorBaseType(VT);
2925   SDOperand N0 = Op.getOperand(0);
2926   SDOperand N1 = Op.getOperand(1);
2927   SDOperand N2 = Op.getOperand(2);
2928   if (MVT::getSizeInBits(BaseVT) == 16) {
2929     if (N1.getValueType() != MVT::i32)
2930       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2931     if (N2.getValueType() != MVT::i32)
2932       N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(), MVT::i32);
2933     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2934   } else if (MVT::getSizeInBits(BaseVT) == 32) {
2935     unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2936     if (Idx == 0) {
2937       // Use a movss.
2938       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
2939       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2940       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2941       SmallVector<SDOperand, 8> MaskVec;
2942       MaskVec.push_back(DAG.getConstant(4, BaseVT));
2943       for (unsigned i = 1; i <= 3; ++i)
2944         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2945       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
2946                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2947                                      &MaskVec[0], MaskVec.size()));
2948     } else {
2949       // Use two pinsrw instructions to insert a 32 bit value.
2950       Idx <<= 1;
2951       if (MVT::isFloatingPoint(N1.getValueType())) {
2952         if (ISD::isNON_EXTLoad(N1.Val)) {
2953           // Just load directly from f32mem to GR32.
2954           LoadSDNode *LD = cast<LoadSDNode>(N1);
2955           N1 = DAG.getLoad(MVT::i32, LD->getChain(), LD->getBasePtr(),
2956                            LD->getSrcValue(), LD->getSrcValueOffset());
2957         } else {
2958           N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
2959           N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
2960           N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
2961                            DAG.getConstant(0, getPointerTy()));
2962         }
2963       }
2964       N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
2965       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2966                        DAG.getConstant(Idx, getPointerTy()));
2967       N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
2968       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2969                        DAG.getConstant(Idx+1, getPointerTy()));
2970       return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2971     }
2972   }
2973
2974   return SDOperand();
2975 }
2976
2977 SDOperand
2978 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2979   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
2980   return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
2981 }
2982
2983 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2984 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
2985 // one of the above mentioned nodes. It has to be wrapped because otherwise
2986 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2987 // be used to form addressing mode. These wrapped nodes will be selected
2988 // into MOV32ri.
2989 SDOperand
2990 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
2991   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2992   SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
2993                                                getPointerTy(),
2994                                                CP->getAlignment());
2995   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2996   // With PIC, the address is actually $g + Offset.
2997   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2998       !Subtarget->isPICStyleRIPRel()) {
2999     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3000                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3001                          Result);
3002   }
3003
3004   return Result;
3005 }
3006
3007 SDOperand
3008 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3009   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3010   SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3011   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3012   // With PIC, the address is actually $g + Offset.
3013   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3014       !Subtarget->isPICStyleRIPRel()) {
3015     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3016                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3017                          Result);
3018   }
3019   
3020   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3021   // load the value at address GV, not the value of GV itself. This means that
3022   // the GlobalAddress must be in the base or index register of the address, not
3023   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3024   // The same applies for external symbols during PIC codegen
3025   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3026     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3027
3028   return Result;
3029 }
3030
3031 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3032 static SDOperand
3033 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3034                               const MVT::ValueType PtrVT) {
3035   SDOperand InFlag;
3036   SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3037                                      DAG.getNode(X86ISD::GlobalBaseReg,
3038                                                  PtrVT), InFlag);
3039   InFlag = Chain.getValue(1);
3040
3041   // emit leal symbol@TLSGD(,%ebx,1), %eax
3042   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3043   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3044                                              GA->getValueType(0),
3045                                              GA->getOffset());
3046   SDOperand Ops[] = { Chain,  TGA, InFlag };
3047   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3048   InFlag = Result.getValue(2);
3049   Chain = Result.getValue(1);
3050
3051   // call ___tls_get_addr. This function receives its argument in
3052   // the register EAX.
3053   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3054   InFlag = Chain.getValue(1);
3055
3056   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3057   SDOperand Ops1[] = { Chain,
3058                       DAG.getTargetExternalSymbol("___tls_get_addr",
3059                                                   PtrVT),
3060                       DAG.getRegister(X86::EAX, PtrVT),
3061                       DAG.getRegister(X86::EBX, PtrVT),
3062                       InFlag };
3063   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3064   InFlag = Chain.getValue(1);
3065
3066   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3067 }
3068
3069 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3070 // "local exec" model.
3071 static SDOperand
3072 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3073                          const MVT::ValueType PtrVT) {
3074   // Get the Thread Pointer
3075   SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3076   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3077   // exec)
3078   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3079                                              GA->getValueType(0),
3080                                              GA->getOffset());
3081   SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3082
3083   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3084     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3085
3086   // The address of the thread local variable is the add of the thread
3087   // pointer with the offset of the variable.
3088   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3089 }
3090
3091 SDOperand
3092 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3093   // TODO: implement the "local dynamic" model
3094   // TODO: implement the "initial exec"model for pic executables
3095   assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3096          "TLS not implemented for non-ELF and 64-bit targets");
3097   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3098   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3099   // otherwise use the "Local Exec"TLS Model
3100   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3101     return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3102   else
3103     return LowerToTLSExecModel(GA, DAG, getPointerTy());
3104 }
3105
3106 SDOperand
3107 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3108   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3109   SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3110   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3111   // With PIC, the address is actually $g + Offset.
3112   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3113       !Subtarget->isPICStyleRIPRel()) {
3114     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3115                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3116                          Result);
3117   }
3118
3119   return Result;
3120 }
3121
3122 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3123   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3124   SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3125   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3126   // With PIC, the address is actually $g + Offset.
3127   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3128       !Subtarget->isPICStyleRIPRel()) {
3129     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3130                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3131                          Result);
3132   }
3133
3134   return Result;
3135 }
3136
3137 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3138     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3139            "Not an i64 shift!");
3140     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3141     SDOperand ShOpLo = Op.getOperand(0);
3142     SDOperand ShOpHi = Op.getOperand(1);
3143     SDOperand ShAmt  = Op.getOperand(2);
3144     SDOperand Tmp1 = isSRA ?
3145       DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3146       DAG.getConstant(0, MVT::i32);
3147
3148     SDOperand Tmp2, Tmp3;
3149     if (Op.getOpcode() == ISD::SHL_PARTS) {
3150       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3151       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3152     } else {
3153       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3154       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3155     }
3156
3157     const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3158     SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3159                                     DAG.getConstant(32, MVT::i8));
3160     SDOperand COps[]={DAG.getEntryNode(), AndNode, DAG.getConstant(0, MVT::i8)};
3161     SDOperand InFlag = DAG.getNode(X86ISD::CMP, VTs, 2, COps, 3).getValue(1);
3162
3163     SDOperand Hi, Lo;
3164     SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3165
3166     VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3167     SmallVector<SDOperand, 4> Ops;
3168     if (Op.getOpcode() == ISD::SHL_PARTS) {
3169       Ops.push_back(Tmp2);
3170       Ops.push_back(Tmp3);
3171       Ops.push_back(CC);
3172       Ops.push_back(InFlag);
3173       Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3174       InFlag = Hi.getValue(1);
3175
3176       Ops.clear();
3177       Ops.push_back(Tmp3);
3178       Ops.push_back(Tmp1);
3179       Ops.push_back(CC);
3180       Ops.push_back(InFlag);
3181       Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3182     } else {
3183       Ops.push_back(Tmp2);
3184       Ops.push_back(Tmp3);
3185       Ops.push_back(CC);
3186       Ops.push_back(InFlag);
3187       Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3188       InFlag = Lo.getValue(1);
3189
3190       Ops.clear();
3191       Ops.push_back(Tmp3);
3192       Ops.push_back(Tmp1);
3193       Ops.push_back(CC);
3194       Ops.push_back(InFlag);
3195       Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3196     }
3197
3198     VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3199     Ops.clear();
3200     Ops.push_back(Lo);
3201     Ops.push_back(Hi);
3202     return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3203 }
3204
3205 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3206   assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3207          Op.getOperand(0).getValueType() >= MVT::i16 &&
3208          "Unknown SINT_TO_FP to lower!");
3209
3210   SDOperand Result;
3211   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3212   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3213   MachineFunction &MF = DAG.getMachineFunction();
3214   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3215   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3216   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3217                                  StackSlot, NULL, 0);
3218
3219   // Build the FILD
3220   SDVTList Tys;
3221   if (X86ScalarSSE)
3222     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3223   else
3224     Tys = DAG.getVTList(MVT::f64, MVT::Other);
3225   SmallVector<SDOperand, 8> Ops;
3226   Ops.push_back(Chain);
3227   Ops.push_back(StackSlot);
3228   Ops.push_back(DAG.getValueType(SrcVT));
3229   Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3230                        Tys, &Ops[0], Ops.size());
3231
3232   if (X86ScalarSSE) {
3233     Chain = Result.getValue(1);
3234     SDOperand InFlag = Result.getValue(2);
3235
3236     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3237     // shouldn't be necessary except that RFP cannot be live across
3238     // multiple blocks. When stackifier is fixed, they can be uncoupled.
3239     MachineFunction &MF = DAG.getMachineFunction();
3240     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3241     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3242     Tys = DAG.getVTList(MVT::Other);
3243     SmallVector<SDOperand, 8> Ops;
3244     Ops.push_back(Chain);
3245     Ops.push_back(Result);
3246     Ops.push_back(StackSlot);
3247     Ops.push_back(DAG.getValueType(Op.getValueType()));
3248     Ops.push_back(InFlag);
3249     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3250     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3251   }
3252
3253   return Result;
3254 }
3255
3256 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3257   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3258          "Unknown FP_TO_SINT to lower!");
3259   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3260   // stack slot.
3261   MachineFunction &MF = DAG.getMachineFunction();
3262   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3263   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3264   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3265
3266   unsigned Opc;
3267   switch (Op.getValueType()) {
3268     default: assert(0 && "Invalid FP_TO_SINT to lower!");
3269     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3270     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3271     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3272   }
3273
3274   SDOperand Chain = DAG.getEntryNode();
3275   SDOperand Value = Op.getOperand(0);
3276   if (X86ScalarSSE) {
3277     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3278     Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3279     SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other);
3280     SDOperand Ops[] = {
3281       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3282     };
3283     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3284     Chain = Value.getValue(1);
3285     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3286     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3287   }
3288
3289   // Build the FP_TO_INT*_IN_MEM
3290   SDOperand Ops[] = { Chain, Value, StackSlot };
3291   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3292
3293   // Load the result.
3294   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3295 }
3296
3297 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3298   MVT::ValueType VT = Op.getValueType();
3299   const Type *OpNTy =  MVT::getTypeForValueType(VT);
3300   std::vector<Constant*> CV;
3301   if (VT == MVT::f64) {
3302     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63))));
3303     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3304   } else {
3305     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31))));
3306     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3307     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3308     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3309   }
3310   Constant *CS = ConstantStruct::get(CV);
3311   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3312   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3313   SmallVector<SDOperand, 3> Ops;
3314   Ops.push_back(DAG.getEntryNode());
3315   Ops.push_back(CPIdx);
3316   Ops.push_back(DAG.getSrcValue(NULL));
3317   SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3318   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3319 }
3320
3321 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3322   MVT::ValueType VT = Op.getValueType();
3323   const Type *OpNTy =  MVT::getTypeForValueType(VT);
3324   std::vector<Constant*> CV;
3325   if (VT == MVT::f64) {
3326     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63)));
3327     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3328   } else {
3329     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(1U << 31)));
3330     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3331     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3332     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3333   }
3334   Constant *CS = ConstantStruct::get(CV);
3335   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3336   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3337   SmallVector<SDOperand, 3> Ops;
3338   Ops.push_back(DAG.getEntryNode());
3339   Ops.push_back(CPIdx);
3340   Ops.push_back(DAG.getSrcValue(NULL));
3341   SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3342   return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3343 }
3344
3345 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
3346   SDOperand Op0 = Op.getOperand(0);
3347   SDOperand Op1 = Op.getOperand(1);
3348   MVT::ValueType VT = Op.getValueType();
3349   MVT::ValueType SrcVT = Op1.getValueType();
3350   const Type *SrcTy =  MVT::getTypeForValueType(SrcVT);
3351
3352   // If second operand is smaller, extend it first.
3353   if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
3354     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
3355     SrcVT = VT;
3356   }
3357
3358   // First get the sign bit of second operand.
3359   std::vector<Constant*> CV;
3360   if (SrcVT == MVT::f64) {
3361     CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(1ULL << 63)));
3362     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3363   } else {
3364     CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(1U << 31)));
3365     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3366     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3367     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3368   }
3369   Constant *CS = ConstantStruct::get(CV);
3370   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3371   SDVTList Tys = DAG.getVTList(SrcVT, MVT::Other);
3372   SmallVector<SDOperand, 3> Ops;
3373   Ops.push_back(DAG.getEntryNode());
3374   Ops.push_back(CPIdx);
3375   Ops.push_back(DAG.getSrcValue(NULL));
3376   SDOperand Mask1 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3377   SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
3378
3379   // Shift sign bit right or left if the two operands have different types.
3380   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
3381     // Op0 is MVT::f32, Op1 is MVT::f64.
3382     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
3383     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
3384                           DAG.getConstant(32, MVT::i32));
3385     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
3386     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
3387                           DAG.getConstant(0, getPointerTy()));
3388   }
3389
3390   // Clear first operand sign bit.
3391   CV.clear();
3392   if (VT == MVT::f64) {
3393     CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(~(1ULL << 63))));
3394     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3395   } else {
3396     CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(~(1U << 31))));
3397     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3398     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3399     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3400   }
3401   CS = ConstantStruct::get(CV);
3402   CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3403   Tys = DAG.getVTList(VT, MVT::Other);
3404   Ops.clear();
3405   Ops.push_back(DAG.getEntryNode());
3406   Ops.push_back(CPIdx);
3407   Ops.push_back(DAG.getSrcValue(NULL));
3408   SDOperand Mask2 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3409   SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
3410
3411   // Or the value with the sign bit.
3412   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
3413 }
3414
3415 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG,
3416                                         SDOperand Chain) {
3417   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3418   SDOperand Cond;
3419   SDOperand Op0 = Op.getOperand(0);
3420   SDOperand Op1 = Op.getOperand(1);
3421   SDOperand CC = Op.getOperand(2);
3422   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3423   const MVT::ValueType *VTs1 = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3424   const MVT::ValueType *VTs2 = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
3425   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3426   unsigned X86CC;
3427
3428   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
3429                      Op0, Op1, DAG)) {
3430     SDOperand Ops1[] = { Chain, Op0, Op1 };
3431     Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, Ops1, 3).getValue(1);
3432     SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
3433     return DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3434   }
3435
3436   assert(isFP && "Illegal integer SetCC!");
3437
3438   SDOperand COps[] = { Chain, Op0, Op1 };
3439   Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, COps, 3).getValue(1);
3440
3441   switch (SetCCOpcode) {
3442   default: assert(false && "Illegal floating point SetCC!");
3443   case ISD::SETOEQ: {  // !PF & ZF
3444     SDOperand Ops1[] = { DAG.getConstant(X86::COND_NP, MVT::i8), Cond };
3445     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3446     SDOperand Ops2[] = { DAG.getConstant(X86::COND_E, MVT::i8),
3447                          Tmp1.getValue(1) };
3448     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3449     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3450   }
3451   case ISD::SETUNE: {  // PF | !ZF
3452     SDOperand Ops1[] = { DAG.getConstant(X86::COND_P, MVT::i8), Cond };
3453     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3454     SDOperand Ops2[] = { DAG.getConstant(X86::COND_NE, MVT::i8),
3455                          Tmp1.getValue(1) };
3456     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3457     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3458   }
3459   }
3460 }
3461
3462 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3463   bool addTest = true;
3464   SDOperand Chain = DAG.getEntryNode();
3465   SDOperand Cond  = Op.getOperand(0);
3466   SDOperand CC;
3467   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3468
3469   if (Cond.getOpcode() == ISD::SETCC)
3470     Cond = LowerSETCC(Cond, DAG, Chain);
3471
3472   if (Cond.getOpcode() == X86ISD::SETCC) {
3473     CC = Cond.getOperand(0);
3474
3475     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3476     // (since flag operand cannot be shared). Use it as the condition setting
3477     // operand in place of the X86ISD::SETCC.
3478     // If the X86ISD::SETCC has more than one use, then perhaps it's better
3479     // to use a test instead of duplicating the X86ISD::CMP (for register
3480     // pressure reason)?
3481     SDOperand Cmp = Cond.getOperand(1);
3482     unsigned Opc = Cmp.getOpcode();
3483     bool IllegalFPCMov = !X86ScalarSSE &&
3484       MVT::isFloatingPoint(Op.getValueType()) &&
3485       !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3486     if ((Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) &&
3487         !IllegalFPCMov) {
3488       SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3489       Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3490       addTest = false;
3491     }
3492   }
3493
3494   if (addTest) {
3495     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3496     SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3497     Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3498   }
3499
3500   VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::Flag);
3501   SmallVector<SDOperand, 4> Ops;
3502   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3503   // condition is true.
3504   Ops.push_back(Op.getOperand(2));
3505   Ops.push_back(Op.getOperand(1));
3506   Ops.push_back(CC);
3507   Ops.push_back(Cond.getValue(1));
3508   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3509 }
3510
3511 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3512   bool addTest = true;
3513   SDOperand Chain = Op.getOperand(0);
3514   SDOperand Cond  = Op.getOperand(1);
3515   SDOperand Dest  = Op.getOperand(2);
3516   SDOperand CC;
3517   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3518
3519   if (Cond.getOpcode() == ISD::SETCC)
3520     Cond = LowerSETCC(Cond, DAG, Chain);
3521
3522   if (Cond.getOpcode() == X86ISD::SETCC) {
3523     CC = Cond.getOperand(0);
3524
3525     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3526     // (since flag operand cannot be shared). Use it as the condition setting
3527     // operand in place of the X86ISD::SETCC.
3528     // If the X86ISD::SETCC has more than one use, then perhaps it's better
3529     // to use a test instead of duplicating the X86ISD::CMP (for register
3530     // pressure reason)?
3531     SDOperand Cmp = Cond.getOperand(1);
3532     unsigned Opc = Cmp.getOpcode();
3533     if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) {
3534       SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3535       Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3536       addTest = false;
3537     }
3538   }
3539
3540   if (addTest) {
3541     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3542     SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3543     Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3544   }
3545   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3546                      Cond, Op.getOperand(2), CC, Cond.getValue(1));
3547 }
3548
3549 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3550   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3551
3552   if (Subtarget->is64Bit())
3553     return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
3554   else
3555     switch (CallingConv) {
3556     default:
3557       assert(0 && "Unsupported calling convention");
3558     case CallingConv::Fast:
3559       // TODO: Implement fastcc
3560       // Falls through
3561     case CallingConv::C:
3562     case CallingConv::X86_StdCall:
3563       return LowerCCCCallTo(Op, DAG, CallingConv);
3564     case CallingConv::X86_FastCall:
3565       return LowerFastCCCallTo(Op, DAG, CallingConv);
3566     }
3567 }
3568
3569
3570 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
3571 // Calls to _alloca is needed to probe the stack when allocating more than 4k
3572 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
3573 // that the guard pages used by the OS virtual memory manager are allocated in
3574 // correct sequence.
3575 SDOperand X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
3576                                                      SelectionDAG &DAG) {
3577   assert(Subtarget->isTargetCygMing() &&
3578          "This should be used only on Cygwin/Mingw targets");
3579   
3580   // Get the inputs.
3581   SDOperand Chain = Op.getOperand(0);
3582   SDOperand Size  = Op.getOperand(1);
3583   // FIXME: Ensure alignment here
3584
3585   TargetLowering::ArgListTy Args; 
3586   TargetLowering::ArgListEntry Entry;
3587   MVT::ValueType IntPtr = getPointerTy();
3588   MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
3589   const Type *IntPtrTy = getTargetData()->getIntPtrType();
3590   
3591   Entry.Node    = Size;
3592   Entry.Ty      = IntPtrTy;
3593   Entry.isInReg = true; // Should pass in EAX
3594   Args.push_back(Entry);
3595   std::pair<SDOperand, SDOperand> CallResult =
3596     LowerCallTo(Chain, IntPtrTy, false, false, CallingConv::C, false,
3597                 DAG.getExternalSymbol("_alloca", IntPtr), Args, DAG);
3598
3599   SDOperand SP = DAG.getCopyFromReg(CallResult.second, X86StackPtr, SPTy);
3600   
3601   std::vector<MVT::ValueType> Tys;
3602   Tys.push_back(SPTy);
3603   Tys.push_back(MVT::Other);
3604   SDOperand Ops[2] = { SP, CallResult.second };
3605   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
3606 }
3607
3608 SDOperand
3609 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3610   MachineFunction &MF = DAG.getMachineFunction();
3611   const Function* Fn = MF.getFunction();
3612   if (Fn->hasExternalLinkage() &&
3613       Subtarget->isTargetCygMing() &&
3614       Fn->getName() == "main")
3615     MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
3616
3617   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3618   if (Subtarget->is64Bit())
3619     return LowerX86_64CCCArguments(Op, DAG);
3620   else
3621     switch(CC) {
3622     default:
3623       assert(0 && "Unsupported calling convention");
3624     case CallingConv::Fast:
3625       // TODO: implement fastcc.
3626       
3627       // Falls through
3628     case CallingConv::C:
3629       return LowerCCCArguments(Op, DAG);
3630     case CallingConv::X86_StdCall:
3631       MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
3632       return LowerCCCArguments(Op, DAG, true);
3633     case CallingConv::X86_FastCall:
3634       MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
3635       return LowerFastCCArguments(Op, DAG);
3636     }
3637 }
3638
3639 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3640   SDOperand InFlag(0, 0);
3641   SDOperand Chain = Op.getOperand(0);
3642   unsigned Align =
3643     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3644   if (Align == 0) Align = 1;
3645
3646   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3647   // If not DWORD aligned, call memset if size is less than the threshold.
3648   // It knows how to align to the right boundary first.
3649   if ((Align & 3) != 0 ||
3650       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3651     MVT::ValueType IntPtr = getPointerTy();
3652     const Type *IntPtrTy = getTargetData()->getIntPtrType();
3653     TargetLowering::ArgListTy Args; 
3654     TargetLowering::ArgListEntry Entry;
3655     Entry.Node = Op.getOperand(1);
3656     Entry.Ty = IntPtrTy;
3657     Args.push_back(Entry);
3658     // Extend the unsigned i8 argument to be an int value for the call.
3659     Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3660     Entry.Ty = IntPtrTy;
3661     Args.push_back(Entry);
3662     Entry.Node = Op.getOperand(3);
3663     Args.push_back(Entry);
3664     std::pair<SDOperand,SDOperand> CallResult =
3665       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3666                   DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3667     return CallResult.second;
3668   }
3669
3670   MVT::ValueType AVT;
3671   SDOperand Count;
3672   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3673   unsigned BytesLeft = 0;
3674   bool TwoRepStos = false;
3675   if (ValC) {
3676     unsigned ValReg;
3677     uint64_t Val = ValC->getValue() & 255;
3678
3679     // If the value is a constant, then we can potentially use larger sets.
3680     switch (Align & 3) {
3681       case 2:   // WORD aligned
3682         AVT = MVT::i16;
3683         ValReg = X86::AX;
3684         Val = (Val << 8) | Val;
3685         break;
3686       case 0:  // DWORD aligned
3687         AVT = MVT::i32;
3688         ValReg = X86::EAX;
3689         Val = (Val << 8)  | Val;
3690         Val = (Val << 16) | Val;
3691         if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) {  // QWORD aligned
3692           AVT = MVT::i64;
3693           ValReg = X86::RAX;
3694           Val = (Val << 32) | Val;
3695         }
3696         break;
3697       default:  // Byte aligned
3698         AVT = MVT::i8;
3699         ValReg = X86::AL;
3700         Count = Op.getOperand(3);
3701         break;
3702     }
3703
3704     if (AVT > MVT::i8) {
3705       if (I) {
3706         unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3707         Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3708         BytesLeft = I->getValue() % UBytes;
3709       } else {
3710         assert(AVT >= MVT::i32 &&
3711                "Do not use rep;stos if not at least DWORD aligned");
3712         Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3713                             Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3714         TwoRepStos = true;
3715       }
3716     }
3717
3718     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3719                               InFlag);
3720     InFlag = Chain.getValue(1);
3721   } else {
3722     AVT = MVT::i8;
3723     Count  = Op.getOperand(3);
3724     Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3725     InFlag = Chain.getValue(1);
3726   }
3727
3728   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3729                             Count, InFlag);
3730   InFlag = Chain.getValue(1);
3731   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3732                             Op.getOperand(1), InFlag);
3733   InFlag = Chain.getValue(1);
3734
3735   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3736   SmallVector<SDOperand, 8> Ops;
3737   Ops.push_back(Chain);
3738   Ops.push_back(DAG.getValueType(AVT));
3739   Ops.push_back(InFlag);
3740   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3741
3742   if (TwoRepStos) {
3743     InFlag = Chain.getValue(1);
3744     Count = Op.getOperand(3);
3745     MVT::ValueType CVT = Count.getValueType();
3746     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3747                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3748     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3749                               Left, InFlag);
3750     InFlag = Chain.getValue(1);
3751     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3752     Ops.clear();
3753     Ops.push_back(Chain);
3754     Ops.push_back(DAG.getValueType(MVT::i8));
3755     Ops.push_back(InFlag);
3756     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3757   } else if (BytesLeft) {
3758     // Issue stores for the last 1 - 7 bytes.
3759     SDOperand Value;
3760     unsigned Val = ValC->getValue() & 255;
3761     unsigned Offset = I->getValue() - BytesLeft;
3762     SDOperand DstAddr = Op.getOperand(1);
3763     MVT::ValueType AddrVT = DstAddr.getValueType();
3764     if (BytesLeft >= 4) {
3765       Val = (Val << 8)  | Val;
3766       Val = (Val << 16) | Val;
3767       Value = DAG.getConstant(Val, MVT::i32);
3768       Chain = DAG.getStore(Chain, Value,
3769                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3770                                        DAG.getConstant(Offset, AddrVT)),
3771                            NULL, 0);
3772       BytesLeft -= 4;
3773       Offset += 4;
3774     }
3775     if (BytesLeft >= 2) {
3776       Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3777       Chain = DAG.getStore(Chain, Value,
3778                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3779                                        DAG.getConstant(Offset, AddrVT)),
3780                            NULL, 0);
3781       BytesLeft -= 2;
3782       Offset += 2;
3783     }
3784     if (BytesLeft == 1) {
3785       Value = DAG.getConstant(Val, MVT::i8);
3786       Chain = DAG.getStore(Chain, Value,
3787                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3788                                        DAG.getConstant(Offset, AddrVT)),
3789                            NULL, 0);
3790     }
3791   }
3792
3793   return Chain;
3794 }
3795
3796 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3797   SDOperand Chain = Op.getOperand(0);
3798   unsigned Align =
3799     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3800   if (Align == 0) Align = 1;
3801
3802   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3803   // If not DWORD aligned, call memcpy if size is less than the threshold.
3804   // It knows how to align to the right boundary first.
3805   if ((Align & 3) != 0 ||
3806       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3807     MVT::ValueType IntPtr = getPointerTy();
3808     TargetLowering::ArgListTy Args;
3809     TargetLowering::ArgListEntry Entry;
3810     Entry.Ty = getTargetData()->getIntPtrType();
3811     Entry.Node = Op.getOperand(1); Args.push_back(Entry);
3812     Entry.Node = Op.getOperand(2); Args.push_back(Entry);
3813     Entry.Node = Op.getOperand(3); Args.push_back(Entry);
3814     std::pair<SDOperand,SDOperand> CallResult =
3815       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3816                   DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3817     return CallResult.second;
3818   }
3819
3820   MVT::ValueType AVT;
3821   SDOperand Count;
3822   unsigned BytesLeft = 0;
3823   bool TwoRepMovs = false;
3824   switch (Align & 3) {
3825     case 2:   // WORD aligned
3826       AVT = MVT::i16;
3827       break;
3828     case 0:  // DWORD aligned
3829       AVT = MVT::i32;
3830       if (Subtarget->is64Bit() && ((Align & 0xF) == 0))  // QWORD aligned
3831         AVT = MVT::i64;
3832       break;
3833     default:  // Byte aligned
3834       AVT = MVT::i8;
3835       Count = Op.getOperand(3);
3836       break;
3837   }
3838
3839   if (AVT > MVT::i8) {
3840     if (I) {
3841       unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3842       Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3843       BytesLeft = I->getValue() % UBytes;
3844     } else {
3845       assert(AVT >= MVT::i32 &&
3846              "Do not use rep;movs if not at least DWORD aligned");
3847       Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3848                           Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3849       TwoRepMovs = true;
3850     }
3851   }
3852
3853   SDOperand InFlag(0, 0);
3854   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3855                             Count, InFlag);
3856   InFlag = Chain.getValue(1);
3857   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3858                             Op.getOperand(1), InFlag);
3859   InFlag = Chain.getValue(1);
3860   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
3861                             Op.getOperand(2), InFlag);
3862   InFlag = Chain.getValue(1);
3863
3864   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3865   SmallVector<SDOperand, 8> Ops;
3866   Ops.push_back(Chain);
3867   Ops.push_back(DAG.getValueType(AVT));
3868   Ops.push_back(InFlag);
3869   Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3870
3871   if (TwoRepMovs) {
3872     InFlag = Chain.getValue(1);
3873     Count = Op.getOperand(3);
3874     MVT::ValueType CVT = Count.getValueType();
3875     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3876                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3877     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3878                               Left, InFlag);
3879     InFlag = Chain.getValue(1);
3880     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3881     Ops.clear();
3882     Ops.push_back(Chain);
3883     Ops.push_back(DAG.getValueType(MVT::i8));
3884     Ops.push_back(InFlag);
3885     Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3886   } else if (BytesLeft) {
3887     // Issue loads and stores for the last 1 - 7 bytes.
3888     unsigned Offset = I->getValue() - BytesLeft;
3889     SDOperand DstAddr = Op.getOperand(1);
3890     MVT::ValueType DstVT = DstAddr.getValueType();
3891     SDOperand SrcAddr = Op.getOperand(2);
3892     MVT::ValueType SrcVT = SrcAddr.getValueType();
3893     SDOperand Value;
3894     if (BytesLeft >= 4) {
3895       Value = DAG.getLoad(MVT::i32, Chain,
3896                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3897                                       DAG.getConstant(Offset, SrcVT)),
3898                           NULL, 0);
3899       Chain = Value.getValue(1);
3900       Chain = DAG.getStore(Chain, Value,
3901                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
3902                                        DAG.getConstant(Offset, DstVT)),
3903                            NULL, 0);
3904       BytesLeft -= 4;
3905       Offset += 4;
3906     }
3907     if (BytesLeft >= 2) {
3908       Value = DAG.getLoad(MVT::i16, Chain,
3909                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3910                                       DAG.getConstant(Offset, SrcVT)),
3911                           NULL, 0);
3912       Chain = Value.getValue(1);
3913       Chain = DAG.getStore(Chain, Value,
3914                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
3915                                        DAG.getConstant(Offset, DstVT)),
3916                            NULL, 0);
3917       BytesLeft -= 2;
3918       Offset += 2;
3919     }
3920
3921     if (BytesLeft == 1) {
3922       Value = DAG.getLoad(MVT::i8, Chain,
3923                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3924                                       DAG.getConstant(Offset, SrcVT)),
3925                           NULL, 0);
3926       Chain = Value.getValue(1);
3927       Chain = DAG.getStore(Chain, Value,
3928                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
3929                                        DAG.getConstant(Offset, DstVT)),
3930                            NULL, 0);
3931     }
3932   }
3933
3934   return Chain;
3935 }
3936
3937 SDOperand
3938 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
3939   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3940   SDOperand TheOp = Op.getOperand(0);
3941   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
3942   if (Subtarget->is64Bit()) {
3943     SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
3944     SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
3945                                          MVT::i64, Copy1.getValue(2));
3946     SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
3947                                 DAG.getConstant(32, MVT::i8));
3948     SDOperand Ops[] = {
3949       DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
3950     };
3951     
3952     Tys = DAG.getVTList(MVT::i64, MVT::Other);
3953     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
3954   }
3955   
3956   SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
3957   SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
3958                                        MVT::i32, Copy1.getValue(2));
3959   SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
3960   Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
3961   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
3962 }
3963
3964 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
3965   SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
3966
3967   if (!Subtarget->is64Bit()) {
3968     // vastart just stores the address of the VarArgsFrameIndex slot into the
3969     // memory location argument.
3970     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
3971     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
3972                         SV->getOffset());
3973   }
3974
3975   // __va_list_tag:
3976   //   gp_offset         (0 - 6 * 8)
3977   //   fp_offset         (48 - 48 + 8 * 16)
3978   //   overflow_arg_area (point to parameters coming in memory).
3979   //   reg_save_area
3980   SmallVector<SDOperand, 8> MemOps;
3981   SDOperand FIN = Op.getOperand(1);
3982   // Store gp_offset
3983   SDOperand Store = DAG.getStore(Op.getOperand(0),
3984                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
3985                                  FIN, SV->getValue(), SV->getOffset());
3986   MemOps.push_back(Store);
3987
3988   // Store fp_offset
3989   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3990                     DAG.getConstant(4, getPointerTy()));
3991   Store = DAG.getStore(Op.getOperand(0),
3992                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
3993                        FIN, SV->getValue(), SV->getOffset());
3994   MemOps.push_back(Store);
3995
3996   // Store ptr to overflow_arg_area
3997   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3998                     DAG.getConstant(4, getPointerTy()));
3999   SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4000   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4001                        SV->getOffset());
4002   MemOps.push_back(Store);
4003
4004   // Store ptr to reg_save_area.
4005   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4006                     DAG.getConstant(8, getPointerTy()));
4007   SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4008   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4009                        SV->getOffset());
4010   MemOps.push_back(Store);
4011   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4012 }
4013
4014 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4015   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4016   SDOperand Chain = Op.getOperand(0);
4017   SDOperand DstPtr = Op.getOperand(1);
4018   SDOperand SrcPtr = Op.getOperand(2);
4019   SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4020   SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4021
4022   SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4023                        SrcSV->getValue(), SrcSV->getOffset());
4024   Chain = SrcPtr.getValue(1);
4025   for (unsigned i = 0; i < 3; ++i) {
4026     SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4027                                 SrcSV->getValue(), SrcSV->getOffset());
4028     Chain = Val.getValue(1);
4029     Chain = DAG.getStore(Chain, Val, DstPtr,
4030                          DstSV->getValue(), DstSV->getOffset());
4031     if (i == 2)
4032       break;
4033     SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr, 
4034                          DAG.getConstant(8, getPointerTy()));
4035     DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr, 
4036                          DAG.getConstant(8, getPointerTy()));
4037   }
4038   return Chain;
4039 }
4040
4041 SDOperand
4042 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4043   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4044   switch (IntNo) {
4045   default: return SDOperand();    // Don't custom lower most intrinsics.
4046     // Comparison intrinsics.
4047   case Intrinsic::x86_sse_comieq_ss:
4048   case Intrinsic::x86_sse_comilt_ss:
4049   case Intrinsic::x86_sse_comile_ss:
4050   case Intrinsic::x86_sse_comigt_ss:
4051   case Intrinsic::x86_sse_comige_ss:
4052   case Intrinsic::x86_sse_comineq_ss:
4053   case Intrinsic::x86_sse_ucomieq_ss:
4054   case Intrinsic::x86_sse_ucomilt_ss:
4055   case Intrinsic::x86_sse_ucomile_ss:
4056   case Intrinsic::x86_sse_ucomigt_ss:
4057   case Intrinsic::x86_sse_ucomige_ss:
4058   case Intrinsic::x86_sse_ucomineq_ss:
4059   case Intrinsic::x86_sse2_comieq_sd:
4060   case Intrinsic::x86_sse2_comilt_sd:
4061   case Intrinsic::x86_sse2_comile_sd:
4062   case Intrinsic::x86_sse2_comigt_sd:
4063   case Intrinsic::x86_sse2_comige_sd:
4064   case Intrinsic::x86_sse2_comineq_sd:
4065   case Intrinsic::x86_sse2_ucomieq_sd:
4066   case Intrinsic::x86_sse2_ucomilt_sd:
4067   case Intrinsic::x86_sse2_ucomile_sd:
4068   case Intrinsic::x86_sse2_ucomigt_sd:
4069   case Intrinsic::x86_sse2_ucomige_sd:
4070   case Intrinsic::x86_sse2_ucomineq_sd: {
4071     unsigned Opc = 0;
4072     ISD::CondCode CC = ISD::SETCC_INVALID;
4073     switch (IntNo) {
4074     default: break;
4075     case Intrinsic::x86_sse_comieq_ss:
4076     case Intrinsic::x86_sse2_comieq_sd:
4077       Opc = X86ISD::COMI;
4078       CC = ISD::SETEQ;
4079       break;
4080     case Intrinsic::x86_sse_comilt_ss:
4081     case Intrinsic::x86_sse2_comilt_sd:
4082       Opc = X86ISD::COMI;
4083       CC = ISD::SETLT;
4084       break;
4085     case Intrinsic::x86_sse_comile_ss:
4086     case Intrinsic::x86_sse2_comile_sd:
4087       Opc = X86ISD::COMI;
4088       CC = ISD::SETLE;
4089       break;
4090     case Intrinsic::x86_sse_comigt_ss:
4091     case Intrinsic::x86_sse2_comigt_sd:
4092       Opc = X86ISD::COMI;
4093       CC = ISD::SETGT;
4094       break;
4095     case Intrinsic::x86_sse_comige_ss:
4096     case Intrinsic::x86_sse2_comige_sd:
4097       Opc = X86ISD::COMI;
4098       CC = ISD::SETGE;
4099       break;
4100     case Intrinsic::x86_sse_comineq_ss:
4101     case Intrinsic::x86_sse2_comineq_sd:
4102       Opc = X86ISD::COMI;
4103       CC = ISD::SETNE;
4104       break;
4105     case Intrinsic::x86_sse_ucomieq_ss:
4106     case Intrinsic::x86_sse2_ucomieq_sd:
4107       Opc = X86ISD::UCOMI;
4108       CC = ISD::SETEQ;
4109       break;
4110     case Intrinsic::x86_sse_ucomilt_ss:
4111     case Intrinsic::x86_sse2_ucomilt_sd:
4112       Opc = X86ISD::UCOMI;
4113       CC = ISD::SETLT;
4114       break;
4115     case Intrinsic::x86_sse_ucomile_ss:
4116     case Intrinsic::x86_sse2_ucomile_sd:
4117       Opc = X86ISD::UCOMI;
4118       CC = ISD::SETLE;
4119       break;
4120     case Intrinsic::x86_sse_ucomigt_ss:
4121     case Intrinsic::x86_sse2_ucomigt_sd:
4122       Opc = X86ISD::UCOMI;
4123       CC = ISD::SETGT;
4124       break;
4125     case Intrinsic::x86_sse_ucomige_ss:
4126     case Intrinsic::x86_sse2_ucomige_sd:
4127       Opc = X86ISD::UCOMI;
4128       CC = ISD::SETGE;
4129       break;
4130     case Intrinsic::x86_sse_ucomineq_ss:
4131     case Intrinsic::x86_sse2_ucomineq_sd:
4132       Opc = X86ISD::UCOMI;
4133       CC = ISD::SETNE;
4134       break;
4135     }
4136
4137     unsigned X86CC;
4138     SDOperand LHS = Op.getOperand(1);
4139     SDOperand RHS = Op.getOperand(2);
4140     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4141
4142     const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4143     SDOperand Ops1[] = { DAG.getEntryNode(), LHS, RHS };
4144     SDOperand Cond = DAG.getNode(Opc, VTs, 2, Ops1, 3);
4145     VTs = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
4146     SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
4147     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, VTs, 2, Ops2, 2);
4148     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4149   }
4150   }
4151 }
4152
4153 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4154   // Depths > 0 not supported yet!
4155   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4156     return SDOperand();
4157   
4158   // Just load the return address
4159   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4160   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4161 }
4162
4163 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4164   // Depths > 0 not supported yet!
4165   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4166     return SDOperand();
4167     
4168   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4169   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
4170                      DAG.getConstant(4, getPointerTy()));
4171 }
4172
4173 /// LowerOperation - Provide custom lowering hooks for some operations.
4174 ///
4175 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4176   switch (Op.getOpcode()) {
4177   default: assert(0 && "Should not custom lower this!");
4178   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
4179   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
4180   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4181   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
4182   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
4183   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
4184   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
4185   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
4186   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
4187   case ISD::SHL_PARTS:
4188   case ISD::SRA_PARTS:
4189   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
4190   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
4191   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
4192   case ISD::FABS:               return LowerFABS(Op, DAG);
4193   case ISD::FNEG:               return LowerFNEG(Op, DAG);
4194   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
4195   case ISD::SETCC:              return LowerSETCC(Op, DAG, DAG.getEntryNode());
4196   case ISD::SELECT:             return LowerSELECT(Op, DAG);
4197   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
4198   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
4199   case ISD::CALL:               return LowerCALL(Op, DAG);
4200   case ISD::RET:                return LowerRET(Op, DAG);
4201   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
4202   case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
4203   case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
4204   case ISD::READCYCLECOUNTER:   return LowerREADCYCLCECOUNTER(Op, DAG);
4205   case ISD::VASTART:            return LowerVASTART(Op, DAG);
4206   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
4207   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4208   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
4209   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
4210   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
4211   }
4212   return SDOperand();
4213 }
4214
4215 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
4216   switch (Opcode) {
4217   default: return NULL;
4218   case X86ISD::SHLD:               return "X86ISD::SHLD";
4219   case X86ISD::SHRD:               return "X86ISD::SHRD";
4220   case X86ISD::FAND:               return "X86ISD::FAND";
4221   case X86ISD::FOR:                return "X86ISD::FOR";
4222   case X86ISD::FXOR:               return "X86ISD::FXOR";
4223   case X86ISD::FSRL:               return "X86ISD::FSRL";
4224   case X86ISD::FILD:               return "X86ISD::FILD";
4225   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
4226   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
4227   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
4228   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
4229   case X86ISD::FLD:                return "X86ISD::FLD";
4230   case X86ISD::FST:                return "X86ISD::FST";
4231   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
4232   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
4233   case X86ISD::CALL:               return "X86ISD::CALL";
4234   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
4235   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
4236   case X86ISD::CMP:                return "X86ISD::CMP";
4237   case X86ISD::COMI:               return "X86ISD::COMI";
4238   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
4239   case X86ISD::SETCC:              return "X86ISD::SETCC";
4240   case X86ISD::CMOV:               return "X86ISD::CMOV";
4241   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
4242   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
4243   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
4244   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
4245   case X86ISD::LOAD_PACK:          return "X86ISD::LOAD_PACK";
4246   case X86ISD::LOAD_UA:            return "X86ISD::LOAD_UA";
4247   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
4248   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
4249   case X86ISD::S2VEC:              return "X86ISD::S2VEC";
4250   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
4251   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
4252   case X86ISD::FMAX:               return "X86ISD::FMAX";
4253   case X86ISD::FMIN:               return "X86ISD::FMIN";
4254   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
4255   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
4256   }
4257 }
4258
4259 // isLegalAddressingMode - Return true if the addressing mode represented
4260 // by AM is legal for this target, for a load/store of the specified type.
4261 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
4262                                               const Type *Ty) const {
4263   // X86 supports extremely general addressing modes.
4264   
4265   // X86 allows a sign-extended 32-bit immediate field as a displacement.
4266   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
4267     return false;
4268   
4269   if (AM.BaseGV) {
4270     // X86-64 only supports addr of globals in small code model.
4271     if (Subtarget->is64Bit() &&
4272         getTargetMachine().getCodeModel() != CodeModel::Small)
4273       return false;
4274     
4275     // We can only fold this if we don't need a load either.
4276     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
4277       return false;
4278   }
4279   
4280   switch (AM.Scale) {
4281   case 0:
4282   case 1:
4283   case 2:
4284   case 4:
4285   case 8:
4286     // These scales always work.
4287     break;
4288   case 3:
4289   case 5:
4290   case 9:
4291     // These scales are formed with basereg+scalereg.  Only accept if there is
4292     // no basereg yet.
4293     if (AM.HasBaseReg)
4294       return false;
4295     break;
4296   default:  // Other stuff never works.
4297     return false;
4298   }
4299   
4300   return true;
4301 }
4302
4303
4304 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4305 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4306 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4307 /// are assumed to be legal.
4308 bool
4309 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
4310   // Only do shuffles on 128-bit vector types for now.
4311   if (MVT::getSizeInBits(VT) == 64) return false;
4312   return (Mask.Val->getNumOperands() <= 4 ||
4313           isSplatMask(Mask.Val)  ||
4314           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
4315           X86::isUNPCKLMask(Mask.Val) ||
4316           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
4317           X86::isUNPCKH_v_undef_Mask(Mask.Val) ||
4318           X86::isUNPCKHMask(Mask.Val));
4319 }
4320
4321 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
4322                                                MVT::ValueType EVT,
4323                                                SelectionDAG &DAG) const {
4324   unsigned NumElts = BVOps.size();
4325   // Only do shuffles on 128-bit vector types for now.
4326   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
4327   if (NumElts == 2) return true;
4328   if (NumElts == 4) {
4329     return (isMOVLMask(&BVOps[0], 4)  ||
4330             isCommutedMOVL(&BVOps[0], 4, true) ||
4331             isSHUFPMask(&BVOps[0], 4) || 
4332             isCommutedSHUFP(&BVOps[0], 4));
4333   }
4334   return false;
4335 }
4336
4337 //===----------------------------------------------------------------------===//
4338 //                           X86 Scheduler Hooks
4339 //===----------------------------------------------------------------------===//
4340
4341 MachineBasicBlock *
4342 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
4343                                            MachineBasicBlock *BB) {
4344   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4345   switch (MI->getOpcode()) {
4346   default: assert(false && "Unexpected instr type to insert");
4347   case X86::CMOV_FR32:
4348   case X86::CMOV_FR64:
4349   case X86::CMOV_V4F32:
4350   case X86::CMOV_V2F64:
4351   case X86::CMOV_V2I64: {
4352     // To "insert" a SELECT_CC instruction, we actually have to insert the
4353     // diamond control-flow pattern.  The incoming instruction knows the
4354     // destination vreg to set, the condition code register to branch on, the
4355     // true/false values to select between, and a branch opcode to use.
4356     const BasicBlock *LLVM_BB = BB->getBasicBlock();
4357     ilist<MachineBasicBlock>::iterator It = BB;
4358     ++It;
4359
4360     //  thisMBB:
4361     //  ...
4362     //   TrueVal = ...
4363     //   cmpTY ccX, r1, r2
4364     //   bCC copy1MBB
4365     //   fallthrough --> copy0MBB
4366     MachineBasicBlock *thisMBB = BB;
4367     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
4368     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
4369     unsigned Opc =
4370       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
4371     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
4372     MachineFunction *F = BB->getParent();
4373     F->getBasicBlockList().insert(It, copy0MBB);
4374     F->getBasicBlockList().insert(It, sinkMBB);
4375     // Update machine-CFG edges by first adding all successors of the current
4376     // block to the new block which will contain the Phi node for the select.
4377     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
4378         e = BB->succ_end(); i != e; ++i)
4379       sinkMBB->addSuccessor(*i);
4380     // Next, remove all successors of the current block, and add the true
4381     // and fallthrough blocks as its successors.
4382     while(!BB->succ_empty())
4383       BB->removeSuccessor(BB->succ_begin());
4384     BB->addSuccessor(copy0MBB);
4385     BB->addSuccessor(sinkMBB);
4386
4387     //  copy0MBB:
4388     //   %FalseValue = ...
4389     //   # fallthrough to sinkMBB
4390     BB = copy0MBB;
4391
4392     // Update machine-CFG edges
4393     BB->addSuccessor(sinkMBB);
4394
4395     //  sinkMBB:
4396     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4397     //  ...
4398     BB = sinkMBB;
4399     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
4400       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
4401       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4402
4403     delete MI;   // The pseudo instruction is gone now.
4404     return BB;
4405   }
4406
4407   case X86::FP_TO_INT16_IN_MEM:
4408   case X86::FP_TO_INT32_IN_MEM:
4409   case X86::FP_TO_INT64_IN_MEM: {
4410     // Change the floating point control register to use "round towards zero"
4411     // mode when truncating to an integer value.
4412     MachineFunction *F = BB->getParent();
4413     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4414     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
4415
4416     // Load the old value of the high byte of the control word...
4417     unsigned OldCW =
4418       F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
4419     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
4420
4421     // Set the high part to be round to zero...
4422     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
4423       .addImm(0xC7F);
4424
4425     // Reload the modified control word now...
4426     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4427
4428     // Restore the memory image of control word to original value
4429     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
4430       .addReg(OldCW);
4431
4432     // Get the X86 opcode to use.
4433     unsigned Opc;
4434     switch (MI->getOpcode()) {
4435     default: assert(0 && "illegal opcode!");
4436     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
4437     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
4438     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
4439     }
4440
4441     X86AddressMode AM;
4442     MachineOperand &Op = MI->getOperand(0);
4443     if (Op.isRegister()) {
4444       AM.BaseType = X86AddressMode::RegBase;
4445       AM.Base.Reg = Op.getReg();
4446     } else {
4447       AM.BaseType = X86AddressMode::FrameIndexBase;
4448       AM.Base.FrameIndex = Op.getFrameIndex();
4449     }
4450     Op = MI->getOperand(1);
4451     if (Op.isImmediate())
4452       AM.Scale = Op.getImm();
4453     Op = MI->getOperand(2);
4454     if (Op.isImmediate())
4455       AM.IndexReg = Op.getImm();
4456     Op = MI->getOperand(3);
4457     if (Op.isGlobalAddress()) {
4458       AM.GV = Op.getGlobal();
4459     } else {
4460       AM.Disp = Op.getImm();
4461     }
4462     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
4463                       .addReg(MI->getOperand(4).getReg());
4464
4465     // Reload the original control word now.
4466     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4467
4468     delete MI;   // The pseudo instruction is gone now.
4469     return BB;
4470   }
4471   }
4472 }
4473
4474 //===----------------------------------------------------------------------===//
4475 //                           X86 Optimization Hooks
4476 //===----------------------------------------------------------------------===//
4477
4478 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
4479                                                        uint64_t Mask,
4480                                                        uint64_t &KnownZero,
4481                                                        uint64_t &KnownOne,
4482                                                        unsigned Depth) const {
4483   unsigned Opc = Op.getOpcode();
4484   assert((Opc >= ISD::BUILTIN_OP_END ||
4485           Opc == ISD::INTRINSIC_WO_CHAIN ||
4486           Opc == ISD::INTRINSIC_W_CHAIN ||
4487           Opc == ISD::INTRINSIC_VOID) &&
4488          "Should use MaskedValueIsZero if you don't know whether Op"
4489          " is a target node!");
4490
4491   KnownZero = KnownOne = 0;   // Don't know anything.
4492   switch (Opc) {
4493   default: break;
4494   case X86ISD::SETCC:
4495     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
4496     break;
4497   }
4498 }
4499
4500 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4501 /// element of the result of the vector shuffle.
4502 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
4503   MVT::ValueType VT = N->getValueType(0);
4504   SDOperand PermMask = N->getOperand(2);
4505   unsigned NumElems = PermMask.getNumOperands();
4506   SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
4507   i %= NumElems;
4508   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4509     return (i == 0)
4510       ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(VT));
4511   } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
4512     SDOperand Idx = PermMask.getOperand(i);
4513     if (Idx.getOpcode() == ISD::UNDEF)
4514       return DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(VT));
4515     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
4516   }
4517   return SDOperand();
4518 }
4519
4520 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
4521 /// node is a GlobalAddress + an offset.
4522 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
4523   unsigned Opc = N->getOpcode();
4524   if (Opc == X86ISD::Wrapper) {
4525     if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
4526       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
4527       return true;
4528     }
4529   } else if (Opc == ISD::ADD) {
4530     SDOperand N1 = N->getOperand(0);
4531     SDOperand N2 = N->getOperand(1);
4532     if (isGAPlusOffset(N1.Val, GA, Offset)) {
4533       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
4534       if (V) {
4535         Offset += V->getSignExtended();
4536         return true;
4537       }
4538     } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
4539       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
4540       if (V) {
4541         Offset += V->getSignExtended();
4542         return true;
4543       }
4544     }
4545   }
4546   return false;
4547 }
4548
4549 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
4550 /// + Dist * Size.
4551 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
4552                               MachineFrameInfo *MFI) {
4553   if (N->getOperand(0).Val != Base->getOperand(0).Val)
4554     return false;
4555
4556   SDOperand Loc = N->getOperand(1);
4557   SDOperand BaseLoc = Base->getOperand(1);
4558   if (Loc.getOpcode() == ISD::FrameIndex) {
4559     if (BaseLoc.getOpcode() != ISD::FrameIndex)
4560       return false;
4561     int FI  = dyn_cast<FrameIndexSDNode>(Loc)->getIndex();
4562     int BFI = dyn_cast<FrameIndexSDNode>(BaseLoc)->getIndex();
4563     int FS  = MFI->getObjectSize(FI);
4564     int BFS = MFI->getObjectSize(BFI);
4565     if (FS != BFS || FS != Size) return false;
4566     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
4567   } else {
4568     GlobalValue *GV1 = NULL;
4569     GlobalValue *GV2 = NULL;
4570     int64_t Offset1 = 0;
4571     int64_t Offset2 = 0;
4572     bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
4573     bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
4574     if (isGA1 && isGA2 && GV1 == GV2)
4575       return Offset1 == (Offset2 + Dist*Size);
4576   }
4577
4578   return false;
4579 }
4580
4581 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
4582                               const X86Subtarget *Subtarget) {
4583   GlobalValue *GV;
4584   int64_t Offset;
4585   if (isGAPlusOffset(Base, GV, Offset))
4586     return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
4587   else {
4588     assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
4589     int BFI = dyn_cast<FrameIndexSDNode>(Base)->getIndex();
4590     if (BFI < 0)
4591       // Fixed objects do not specify alignment, however the offsets are known.
4592       return ((Subtarget->getStackAlignment() % 16) == 0 &&
4593               (MFI->getObjectOffset(BFI) % 16) == 0);
4594     else
4595       return MFI->getObjectAlignment(BFI) >= 16;
4596   }
4597   return false;
4598 }
4599
4600
4601 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
4602 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
4603 /// if the load addresses are consecutive, non-overlapping, and in the right
4604 /// order.
4605 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
4606                                        const X86Subtarget *Subtarget) {
4607   MachineFunction &MF = DAG.getMachineFunction();
4608   MachineFrameInfo *MFI = MF.getFrameInfo();
4609   MVT::ValueType VT = N->getValueType(0);
4610   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
4611   SDOperand PermMask = N->getOperand(2);
4612   int NumElems = (int)PermMask.getNumOperands();
4613   SDNode *Base = NULL;
4614   for (int i = 0; i < NumElems; ++i) {
4615     SDOperand Idx = PermMask.getOperand(i);
4616     if (Idx.getOpcode() == ISD::UNDEF) {
4617       if (!Base) return SDOperand();
4618     } else {
4619       SDOperand Arg =
4620         getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
4621       if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
4622         return SDOperand();
4623       if (!Base)
4624         Base = Arg.Val;
4625       else if (!isConsecutiveLoad(Arg.Val, Base,
4626                                   i, MVT::getSizeInBits(EVT)/8,MFI))
4627         return SDOperand();
4628     }
4629   }
4630
4631   bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
4632   if (isAlign16) {
4633     LoadSDNode *LD = cast<LoadSDNode>(Base);
4634     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
4635                        LD->getSrcValueOffset());
4636   } else {
4637     // Just use movups, it's shorter.
4638     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
4639     SmallVector<SDOperand, 3> Ops;
4640     Ops.push_back(Base->getOperand(0));
4641     Ops.push_back(Base->getOperand(1));
4642     Ops.push_back(Base->getOperand(2));
4643     return DAG.getNode(ISD::BIT_CONVERT, VT,
4644                        DAG.getNode(X86ISD::LOAD_UA, Tys, &Ops[0], Ops.size()));
4645   }
4646 }
4647
4648 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
4649 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
4650                                       const X86Subtarget *Subtarget) {
4651   SDOperand Cond = N->getOperand(0);
4652
4653   // If we have SSE[12] support, try to form min/max nodes.
4654   if (Subtarget->hasSSE2() &&
4655       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
4656     if (Cond.getOpcode() == ISD::SETCC) {
4657       // Get the LHS/RHS of the select.
4658       SDOperand LHS = N->getOperand(1);
4659       SDOperand RHS = N->getOperand(2);
4660       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
4661
4662       unsigned Opcode = 0;
4663       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
4664         switch (CC) {
4665         default: break;
4666         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
4667         case ISD::SETULE:
4668         case ISD::SETLE:
4669           if (!UnsafeFPMath) break;
4670           // FALL THROUGH.
4671         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
4672         case ISD::SETLT:
4673           Opcode = X86ISD::FMIN;
4674           break;
4675
4676         case ISD::SETOGT: // (X > Y) ? X : Y -> max
4677         case ISD::SETUGT:
4678         case ISD::SETGT:
4679           if (!UnsafeFPMath) break;
4680           // FALL THROUGH.
4681         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
4682         case ISD::SETGE:
4683           Opcode = X86ISD::FMAX;
4684           break;
4685         }
4686       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
4687         switch (CC) {
4688         default: break;
4689         case ISD::SETOGT: // (X > Y) ? Y : X -> min
4690         case ISD::SETUGT:
4691         case ISD::SETGT:
4692           if (!UnsafeFPMath) break;
4693           // FALL THROUGH.
4694         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
4695         case ISD::SETGE:
4696           Opcode = X86ISD::FMIN;
4697           break;
4698
4699         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
4700         case ISD::SETULE:
4701         case ISD::SETLE:
4702           if (!UnsafeFPMath) break;
4703           // FALL THROUGH.
4704         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
4705         case ISD::SETLT:
4706           Opcode = X86ISD::FMAX;
4707           break;
4708         }
4709       }
4710
4711       if (Opcode)
4712         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
4713     }
4714
4715   }
4716
4717   return SDOperand();
4718 }
4719
4720
4721 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
4722                                                DAGCombinerInfo &DCI) const {
4723   SelectionDAG &DAG = DCI.DAG;
4724   switch (N->getOpcode()) {
4725   default: break;
4726   case ISD::VECTOR_SHUFFLE:
4727     return PerformShuffleCombine(N, DAG, Subtarget);
4728   case ISD::SELECT:
4729     return PerformSELECTCombine(N, DAG, Subtarget);
4730   }
4731
4732   return SDOperand();
4733 }
4734
4735 //===----------------------------------------------------------------------===//
4736 //                           X86 Inline Assembly Support
4737 //===----------------------------------------------------------------------===//
4738
4739 /// getConstraintType - Given a constraint letter, return the type of
4740 /// constraint it is for this target.
4741 X86TargetLowering::ConstraintType
4742 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
4743   if (Constraint.size() == 1) {
4744     switch (Constraint[0]) {
4745     case 'A':
4746     case 'r':
4747     case 'R':
4748     case 'l':
4749     case 'q':
4750     case 'Q':
4751     case 'x':
4752     case 'Y':
4753       return C_RegisterClass;
4754     default:
4755       break;
4756     }
4757   }
4758   return TargetLowering::getConstraintType(Constraint);
4759 }
4760
4761 /// isOperandValidForConstraint - Return the specified operand (possibly
4762 /// modified) if the specified SDOperand is valid for the specified target
4763 /// constraint letter, otherwise return null.
4764 SDOperand X86TargetLowering::
4765 isOperandValidForConstraint(SDOperand Op, char Constraint, SelectionDAG &DAG) {
4766   switch (Constraint) {
4767   default: break;
4768   case 'I':
4769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4770       if (C->getValue() <= 31)
4771         return DAG.getTargetConstant(C->getValue(), Op.getValueType());
4772     }
4773     return SDOperand(0,0);
4774   case 'N':
4775     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4776       if (C->getValue() <= 255)
4777         return DAG.getTargetConstant(C->getValue(), Op.getValueType());
4778     }
4779     return SDOperand(0,0);
4780   case 'i': {
4781     // Literal immediates are always ok.
4782     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op))
4783       return DAG.getTargetConstant(CST->getValue(), Op.getValueType());
4784
4785     // If we are in non-pic codegen mode, we allow the address of a global (with
4786     // an optional displacement) to be used with 'i'.
4787     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
4788     int64_t Offset = 0;
4789     
4790     // Match either (GA) or (GA+C)
4791     if (GA) {
4792       Offset = GA->getOffset();
4793     } else if (Op.getOpcode() == ISD::ADD) {
4794       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4795       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
4796       if (C && GA) {
4797         Offset = GA->getOffset()+C->getValue();
4798       } else {
4799         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4800         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
4801         if (C && GA)
4802           Offset = GA->getOffset()+C->getValue();
4803         else
4804           C = 0, GA = 0;
4805       }
4806     }
4807     
4808     if (GA) {
4809       // If addressing this global requires a load (e.g. in PIC mode), we can't
4810       // match.
4811       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
4812                                          false))
4813         return SDOperand(0, 0);
4814
4815       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4816                                       Offset);
4817       return Op;
4818     }
4819
4820     // Otherwise, not valid for this mode.
4821     return SDOperand(0, 0);
4822   }
4823   }
4824   return TargetLowering::isOperandValidForConstraint(Op, Constraint, DAG);
4825 }
4826
4827 std::vector<unsigned> X86TargetLowering::
4828 getRegClassForInlineAsmConstraint(const std::string &Constraint,
4829                                   MVT::ValueType VT) const {
4830   if (Constraint.size() == 1) {
4831     // FIXME: not handling fp-stack yet!
4832     switch (Constraint[0]) {      // GCC X86 Constraint Letters
4833     default: break;  // Unknown constraint letter
4834     case 'A':   // EAX/EDX
4835       if (VT == MVT::i32 || VT == MVT::i64)
4836         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
4837       break;
4838     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
4839     case 'Q':   // Q_REGS
4840       if (VT == MVT::i32)
4841         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
4842       else if (VT == MVT::i16)
4843         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
4844       else if (VT == MVT::i8)
4845         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4846         break;
4847     }
4848   }
4849
4850   return std::vector<unsigned>();
4851 }
4852
4853 std::pair<unsigned, const TargetRegisterClass*>
4854 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4855                                                 MVT::ValueType VT) const {
4856   // First, see if this is a constraint that directly corresponds to an LLVM
4857   // register class.
4858   if (Constraint.size() == 1) {
4859     // GCC Constraint Letters
4860     switch (Constraint[0]) {
4861     default: break;
4862     case 'r':   // GENERAL_REGS
4863     case 'R':   // LEGACY_REGS
4864     case 'l':   // INDEX_REGS
4865       if (VT == MVT::i64 && Subtarget->is64Bit())
4866         return std::make_pair(0U, X86::GR64RegisterClass);
4867       if (VT == MVT::i32)
4868         return std::make_pair(0U, X86::GR32RegisterClass);
4869       else if (VT == MVT::i16)
4870         return std::make_pair(0U, X86::GR16RegisterClass);
4871       else if (VT == MVT::i8)
4872         return std::make_pair(0U, X86::GR8RegisterClass);
4873       break;
4874     case 'y':   // MMX_REGS if MMX allowed.
4875       if (!Subtarget->hasMMX()) break;
4876       return std::make_pair(0U, X86::VR64RegisterClass);
4877       break;
4878     case 'Y':   // SSE_REGS if SSE2 allowed
4879       if (!Subtarget->hasSSE2()) break;
4880       // FALL THROUGH.
4881     case 'x':   // SSE_REGS if SSE1 allowed
4882       if (!Subtarget->hasSSE1()) break;
4883       
4884       switch (VT) {
4885       default: break;
4886       // Scalar SSE types.
4887       case MVT::f32:
4888       case MVT::i32:
4889         return std::make_pair(0U, X86::FR32RegisterClass);
4890       case MVT::f64:
4891       case MVT::i64:
4892         return std::make_pair(0U, X86::FR64RegisterClass);
4893       // Vector types.
4894       case MVT::Vector:
4895       case MVT::v16i8:
4896       case MVT::v8i16:
4897       case MVT::v4i32:
4898       case MVT::v2i64:
4899       case MVT::v4f32:
4900       case MVT::v2f64:
4901         return std::make_pair(0U, X86::VR128RegisterClass);
4902       }
4903       break;
4904     }
4905   }
4906   
4907   // Use the default implementation in TargetLowering to convert the register
4908   // constraint into a member of a register class.
4909   std::pair<unsigned, const TargetRegisterClass*> Res;
4910   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4911
4912   // Not found as a standard register?
4913   if (Res.second == 0) {
4914     // GCC calls "st(0)" just plain "st".
4915     if (StringsEqualNoCase("{st}", Constraint)) {
4916       Res.first = X86::ST0;
4917       Res.second = X86::RSTRegisterClass;
4918     }
4919
4920     return Res;
4921   }
4922
4923   // Otherwise, check to see if this is a register class of the wrong value
4924   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
4925   // turn into {ax},{dx}.
4926   if (Res.second->hasType(VT))
4927     return Res;   // Correct type already, nothing to do.
4928
4929   // All of the single-register GCC register classes map their values onto
4930   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
4931   // really want an 8-bit or 32-bit register, map to the appropriate register
4932   // class and return the appropriate register.
4933   if (Res.second != X86::GR16RegisterClass)
4934     return Res;
4935
4936   if (VT == MVT::i8) {
4937     unsigned DestReg = 0;
4938     switch (Res.first) {
4939     default: break;
4940     case X86::AX: DestReg = X86::AL; break;
4941     case X86::DX: DestReg = X86::DL; break;
4942     case X86::CX: DestReg = X86::CL; break;
4943     case X86::BX: DestReg = X86::BL; break;
4944     }
4945     if (DestReg) {
4946       Res.first = DestReg;
4947       Res.second = Res.second = X86::GR8RegisterClass;
4948     }
4949   } else if (VT == MVT::i32) {
4950     unsigned DestReg = 0;
4951     switch (Res.first) {
4952     default: break;
4953     case X86::AX: DestReg = X86::EAX; break;
4954     case X86::DX: DestReg = X86::EDX; break;
4955     case X86::CX: DestReg = X86::ECX; break;
4956     case X86::BX: DestReg = X86::EBX; break;
4957     case X86::SI: DestReg = X86::ESI; break;
4958     case X86::DI: DestReg = X86::EDI; break;
4959     case X86::BP: DestReg = X86::EBP; break;
4960     case X86::SP: DestReg = X86::ESP; break;
4961     }
4962     if (DestReg) {
4963       Res.first = DestReg;
4964       Res.second = Res.second = X86::GR32RegisterClass;
4965     }
4966   } else if (VT == MVT::i64) {
4967     unsigned DestReg = 0;
4968     switch (Res.first) {
4969     default: break;
4970     case X86::AX: DestReg = X86::RAX; break;
4971     case X86::DX: DestReg = X86::RDX; break;
4972     case X86::CX: DestReg = X86::RCX; break;
4973     case X86::BX: DestReg = X86::RBX; break;
4974     case X86::SI: DestReg = X86::RSI; break;
4975     case X86::DI: DestReg = X86::RDI; break;
4976     case X86::BP: DestReg = X86::RBP; break;
4977     case X86::SP: DestReg = X86::RSP; break;
4978     }
4979     if (DestReg) {
4980       Res.first = DestReg;
4981       Res.second = Res.second = X86::GR64RegisterClass;
4982     }
4983   }
4984
4985   return Res;
4986 }