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