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