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