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