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