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