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