X86ISelLowering.cpp revision 6fa2f9c63688ff240d58c80bc0e433bb27a53c85
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86ISelLowering.h"
18#include "X86MachineFunctionInfo.h"
19#include "X86TargetMachine.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Function.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/ADT/BitVector.h"
27#include "llvm/ADT/VectorExtras.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/CodeGen/CallingConvLower.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/PseudoSourceValue.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/Support/MathExtras.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Target/TargetOptions.h"
40#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/ParamAttrsList.h"
43using namespace llvm;
44
45X86TargetLowering::X86TargetLowering(TargetMachine &TM)
46  : TargetLowering(TM) {
47  Subtarget = &TM.getSubtarget<X86Subtarget>();
48  X86ScalarSSEf64 = Subtarget->hasSSE2();
49  X86ScalarSSEf32 = Subtarget->hasSSE1();
50  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
51
52  bool Fast = false;
53
54  RegInfo = TM.getRegisterInfo();
55
56  // Set up the TargetLowering object.
57
58  // X86 is weird, it always uses i8 for shift amounts and setcc results.
59  setShiftAmountType(MVT::i8);
60  setSetCCResultType(MVT::i8);
61  setSetCCResultContents(ZeroOrOneSetCCResult);
62  setSchedulingPreference(SchedulingForRegPressure);
63  setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
64  setStackPointerRegisterToSaveRestore(X86StackPtr);
65
66  if (Subtarget->isTargetDarwin()) {
67    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68    setUseUnderscoreSetJmp(false);
69    setUseUnderscoreLongJmp(false);
70  } else if (Subtarget->isTargetMingw()) {
71    // MS runtime is weird: it exports _setjmp, but longjmp!
72    setUseUnderscoreSetJmp(true);
73    setUseUnderscoreLongJmp(false);
74  } else {
75    setUseUnderscoreSetJmp(true);
76    setUseUnderscoreLongJmp(true);
77  }
78
79  // Set up the register classes.
80  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83  if (Subtarget->is64Bit())
84    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
85
86  setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
87
88  // We don't accept any truncstore of integer registers.
89  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94  setTruncStoreAction(MVT::i16, MVT::i8, Expand);
95
96  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
97  // operation.
98  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
99  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
100  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
101
102  if (Subtarget->is64Bit()) {
103    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
104    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
105  } else {
106    if (X86ScalarSSEf64)
107      // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108      setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
109    else
110      setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
111  }
112
113  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
114  // this operation.
115  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
116  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
117  // SSE has no i16 to fp conversion, only i32
118  if (X86ScalarSSEf32) {
119    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
120    // f32 and f64 cases are Legal, f80 case is not
121    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
122  } else {
123    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
124    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
125  }
126
127  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
128  // are Legal, f80 is custom lowered.
129  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
130  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
131
132  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
133  // this operation.
134  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
135  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
136
137  if (X86ScalarSSEf32) {
138    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
139    // f32 and f64 cases are Legal, f80 case is not
140    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
141  } else {
142    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
143    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
144  }
145
146  // Handle FP_TO_UINT by promoting the destination to a larger signed
147  // conversion.
148  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
149  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
150  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
151
152  if (Subtarget->is64Bit()) {
153    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
154    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
155  } else {
156    if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157      // Expand FP_TO_UINT into a select.
158      // FIXME: We would like to use a Custom expander here eventually to do
159      // the optimal thing for SSE vs. the default expansion in the legalizer.
160      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
161    else
162      // With SSE3 we can use fisttpll to convert to a signed i64.
163      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
164  }
165
166  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167  if (!X86ScalarSSEf64) {
168    setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
169    setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
170  }
171
172  // Scalar integer divide and remainder are lowered to use operations that
173  // produce two results, to match the available instructions. This exposes
174  // the two-result form to trivial CSE, which is able to combine x/y and x%y
175  // into a single instruction.
176  //
177  // Scalar integer multiply-high is also lowered to use two-result
178  // operations, to match the available instructions. However, plain multiply
179  // (low) operations are left as Legal, as there are single-result
180  // instructions for this in x86. Using the two-result multiply instructions
181  // when both high and low results are needed must be arranged by dagcombine.
182  setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
183  setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
184  setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
185  setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
186  setOperationAction(ISD::SREM            , MVT::i8    , Expand);
187  setOperationAction(ISD::UREM            , MVT::i8    , Expand);
188  setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
189  setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
190  setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
191  setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
192  setOperationAction(ISD::SREM            , MVT::i16   , Expand);
193  setOperationAction(ISD::UREM            , MVT::i16   , Expand);
194  setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
195  setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
196  setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
197  setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
198  setOperationAction(ISD::SREM            , MVT::i32   , Expand);
199  setOperationAction(ISD::UREM            , MVT::i32   , Expand);
200  setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
201  setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
202  setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
203  setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
204  setOperationAction(ISD::SREM            , MVT::i64   , Expand);
205  setOperationAction(ISD::UREM            , MVT::i64   , Expand);
206
207  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
208  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
209  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
210  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
211  setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
212  if (Subtarget->is64Bit())
213    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
215  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
216  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
217  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
218  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
219  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
220  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
221  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
222
223  setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
224  setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
225  setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
226  setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
227  setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
228  setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
229  setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
230  setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
231  setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
232  if (Subtarget->is64Bit()) {
233    setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
234    setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
235    setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
236  }
237
238  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
239  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
240
241  // These should be promoted to a larger select which is supported.
242  setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
243  setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
244  // X86 wants to expand cmov itself.
245  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
246  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
247  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
248  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
249  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
250  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
251  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
252  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
253  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
254  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
255  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
256  if (Subtarget->is64Bit()) {
257    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
258    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
259  }
260  // X86 ret instruction may pop stack.
261  setOperationAction(ISD::RET             , MVT::Other, Custom);
262  if (!Subtarget->is64Bit())
263    setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
264
265  // Darwin ABI issue.
266  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
267  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
268  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
269  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
270  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
271  if (Subtarget->is64Bit()) {
272    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
273    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
274    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
275    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
276  }
277  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
278  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
279  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
280  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
281  if (Subtarget->is64Bit()) {
282    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
283    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
284    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
285  }
286  // X86 wants to expand memset / memcpy itself.
287  setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
288  setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
289
290  if (!Subtarget->hasSSE1())
291    setOperationAction(ISD::PREFETCH      , MVT::Other, Expand);
292
293  if (!Subtarget->hasSSE2())
294    setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
295
296  setOperationAction(ISD::ATOMIC_LCS     , MVT::i8, Custom);
297  setOperationAction(ISD::ATOMIC_LCS     , MVT::i16, Custom);
298  setOperationAction(ISD::ATOMIC_LCS     , MVT::i32, Custom);
299  setOperationAction(ISD::ATOMIC_LCS     , MVT::i64, Custom);
300
301  // Use the default ISD::LOCATION, ISD::DECLARE expansion.
302  setOperationAction(ISD::LOCATION, MVT::Other, Expand);
303  // FIXME - use subtarget debug flags
304  if (!Subtarget->isTargetDarwin() &&
305      !Subtarget->isTargetELF() &&
306      !Subtarget->isTargetCygMing())
307    setOperationAction(ISD::LABEL, MVT::Other, Expand);
308
309  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
310  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
311  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
312  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
313  if (Subtarget->is64Bit()) {
314    // FIXME: Verify
315    setExceptionPointerRegister(X86::RAX);
316    setExceptionSelectorRegister(X86::RDX);
317  } else {
318    setExceptionPointerRegister(X86::EAX);
319    setExceptionSelectorRegister(X86::EDX);
320  }
321  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
322
323  setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
324
325  setOperationAction(ISD::TRAP, MVT::Other, Legal);
326
327  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
328  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
329  setOperationAction(ISD::VAARG             , MVT::Other, Expand);
330  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
331  if (Subtarget->is64Bit())
332    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
333  else
334    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
335
336  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
337  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
338  if (Subtarget->is64Bit())
339    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
340  if (Subtarget->isTargetCygMing())
341    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
342  else
343    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
344
345  if (X86ScalarSSEf64) {
346    // f32 and f64 use SSE.
347    // Set up the FP register classes.
348    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
349    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
350
351    // Use ANDPD to simulate FABS.
352    setOperationAction(ISD::FABS , MVT::f64, Custom);
353    setOperationAction(ISD::FABS , MVT::f32, Custom);
354
355    // Use XORP to simulate FNEG.
356    setOperationAction(ISD::FNEG , MVT::f64, Custom);
357    setOperationAction(ISD::FNEG , MVT::f32, Custom);
358
359    // Use ANDPD and ORPD to simulate FCOPYSIGN.
360    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
361    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
362
363    // We don't support sin/cos/fmod
364    setOperationAction(ISD::FSIN , MVT::f64, Expand);
365    setOperationAction(ISD::FCOS , MVT::f64, Expand);
366    setOperationAction(ISD::FSIN , MVT::f32, Expand);
367    setOperationAction(ISD::FCOS , MVT::f32, Expand);
368
369    // Expand FP immediates into loads from the stack, except for the special
370    // cases we handle.
371    addLegalFPImmediate(APFloat(+0.0)); // xorpd
372    addLegalFPImmediate(APFloat(+0.0f)); // xorps
373
374    // Floating truncations from f80 and extensions to f80 go through memory.
375    // If optimizing, we lie about this though and handle it in
376    // InstructionSelectPreprocess so that dagcombine2 can hack on these.
377    if (Fast) {
378      setConvertAction(MVT::f32, MVT::f80, Expand);
379      setConvertAction(MVT::f64, MVT::f80, Expand);
380      setConvertAction(MVT::f80, MVT::f32, Expand);
381      setConvertAction(MVT::f80, MVT::f64, Expand);
382    }
383  } else if (X86ScalarSSEf32) {
384    // Use SSE for f32, x87 for f64.
385    // Set up the FP register classes.
386    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
387    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
388
389    // Use ANDPS to simulate FABS.
390    setOperationAction(ISD::FABS , MVT::f32, Custom);
391
392    // Use XORP to simulate FNEG.
393    setOperationAction(ISD::FNEG , MVT::f32, Custom);
394
395    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
396
397    // Use ANDPS and ORPS to simulate FCOPYSIGN.
398    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
399    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
400
401    // We don't support sin/cos/fmod
402    setOperationAction(ISD::FSIN , MVT::f32, Expand);
403    setOperationAction(ISD::FCOS , MVT::f32, Expand);
404
405    // Special cases we handle for FP constants.
406    addLegalFPImmediate(APFloat(+0.0f)); // xorps
407    addLegalFPImmediate(APFloat(+0.0)); // FLD0
408    addLegalFPImmediate(APFloat(+1.0)); // FLD1
409    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
410    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
411
412    // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
413    // this though and handle it in InstructionSelectPreprocess so that
414    // dagcombine2 can hack on these.
415    if (Fast) {
416      setConvertAction(MVT::f32, MVT::f64, Expand);
417      setConvertAction(MVT::f32, MVT::f80, Expand);
418      setConvertAction(MVT::f80, MVT::f32, Expand);
419      setConvertAction(MVT::f64, MVT::f32, Expand);
420      // And x87->x87 truncations also.
421      setConvertAction(MVT::f80, MVT::f64, Expand);
422    }
423
424    if (!UnsafeFPMath) {
425      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
426      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
427    }
428  } else {
429    // f32 and f64 in x87.
430    // Set up the FP register classes.
431    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
432    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
433
434    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
435    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
436    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
437    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
438
439    // Floating truncations go through memory.  If optimizing, we lie about
440    // this though and handle it in InstructionSelectPreprocess so that
441    // dagcombine2 can hack on these.
442    if (Fast) {
443      setConvertAction(MVT::f80, MVT::f32, Expand);
444      setConvertAction(MVT::f64, MVT::f32, Expand);
445      setConvertAction(MVT::f80, MVT::f64, Expand);
446    }
447
448    if (!UnsafeFPMath) {
449      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
450      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
451    }
452    addLegalFPImmediate(APFloat(+0.0)); // FLD0
453    addLegalFPImmediate(APFloat(+1.0)); // FLD1
454    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
455    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
456    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
457    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
458    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
459    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
460  }
461
462  // Long double always uses X87.
463  addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
464  setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
465  setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
466  {
467    APFloat TmpFlt(+0.0);
468    TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
469    addLegalFPImmediate(TmpFlt);  // FLD0
470    TmpFlt.changeSign();
471    addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
472    APFloat TmpFlt2(+1.0);
473    TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
474    addLegalFPImmediate(TmpFlt2);  // FLD1
475    TmpFlt2.changeSign();
476    addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
477  }
478
479  if (!UnsafeFPMath) {
480    setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
481    setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
482  }
483
484  // Always use a library call for pow.
485  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
486  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
487  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
488
489  // First set operation action for all vector types to expand. Then we
490  // will selectively turn on ones that can be effectively codegen'd.
491  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
492       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
493    setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
494    setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
495    setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
496    setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
497    setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
498    setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
499    setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
500    setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
501    setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
502    setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
503    setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
504    setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
505    setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
506    setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
507    setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
508    setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
509    setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
510    setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
511    setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
512    setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
513    setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
514    setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
515    setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
516    setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
517    setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
518    setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
519    setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
520    setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
521    setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
522    setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
523    setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
524    setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
525    setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
526    setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
527    setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
528    setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
529    setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
530  }
531
532  if (Subtarget->hasMMX()) {
533    addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
534    addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
535    addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
536    addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
537
538    // FIXME: add MMX packed arithmetics
539
540    setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
541    setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
542    setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
543    setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
544
545    setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
546    setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
547    setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
548    setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
549
550    setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
551    setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
552
553    setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
554    AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
555    setOperationAction(ISD::AND,                MVT::v4i16, Promote);
556    AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
557    setOperationAction(ISD::AND,                MVT::v2i32, Promote);
558    AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
559    setOperationAction(ISD::AND,                MVT::v1i64, Legal);
560
561    setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
562    AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
563    setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
564    AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
565    setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
566    AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
567    setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
568
569    setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
570    AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
571    setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
572    AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
573    setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
574    AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
575    setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
576
577    setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
578    AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
579    setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
580    AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
581    setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
582    AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
583    setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
584
585    setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
586    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
587    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
588    setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
589
590    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
591    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
592    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
593    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
594
595    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
596    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
597    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
598  }
599
600  if (Subtarget->hasSSE1()) {
601    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
602
603    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
604    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
605    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
606    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
607    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
608    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
609    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
610    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
611    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
612    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
613    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
614  }
615
616  if (Subtarget->hasSSE2()) {
617    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
618    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
619    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
620    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
621    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
622
623    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
624    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
625    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
626    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
627    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
628    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
629    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
630    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
631    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
632    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
633    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
634    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
635    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
636    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
637    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
638
639    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
640    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
641    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
642    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
643    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
644
645    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
646    for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
647      // Do not attempt to custom lower non-power-of-2 vectors
648      if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
649        continue;
650      setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
651      setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
652      setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
653    }
654    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
655    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
656    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
657    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
658    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
659    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
660    if (Subtarget->is64Bit()) {
661      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
662      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
663    }
664
665    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
666    for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
667      setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
668      AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
669      setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
670      AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
671      setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
672      AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
673      setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
674      AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
675      setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
676      AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
677    }
678
679    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
680
681    // Custom lower v2i64 and v2f64 selects.
682    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
683    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
684    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
685    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
686  }
687
688  if (Subtarget->hasSSE41()) {
689    // FIXME: Do we need to handle scalar-to-vector here?
690    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
691
692    // i8 and i16 vectors are custom , because the source register and source
693    // source memory operand types are not the same width.  f32 vectors are
694    // custom since the immediate controlling the insert encodes additional
695    // information.
696    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
697    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
698    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
699    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
700
701    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
702    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
703    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
704    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
705
706    if (Subtarget->is64Bit()) {
707      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
708      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
709    }
710  }
711
712  // We want to custom lower some of our intrinsics.
713  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
714
715  // We have target-specific dag combine patterns for the following nodes:
716  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
717  setTargetDAGCombine(ISD::SELECT);
718  setTargetDAGCombine(ISD::STORE);
719
720  computeRegisterProperties();
721
722  // FIXME: These should be based on subtarget info. Plus, the values should
723  // be smaller when we are in optimizing for size mode.
724  maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
725  maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
726  maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
727  allowUnalignedMemoryAccesses = true; // x86 supports it!
728  setPrefLoopAlignment(16);
729}
730
731/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
732/// the desired ByVal argument alignment.
733static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
734  if (MaxAlign == 16)
735    return;
736  if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
737    if (VTy->getBitWidth() == 128)
738      MaxAlign = 16;
739  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
740    unsigned EltAlign = 0;
741    getMaxByValAlign(ATy->getElementType(), EltAlign);
742    if (EltAlign > MaxAlign)
743      MaxAlign = EltAlign;
744  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
745    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
746      unsigned EltAlign = 0;
747      getMaxByValAlign(STy->getElementType(i), EltAlign);
748      if (EltAlign > MaxAlign)
749        MaxAlign = EltAlign;
750      if (MaxAlign == 16)
751        break;
752    }
753  }
754  return;
755}
756
757/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
758/// function arguments in the caller parameter area. For X86, aggregates
759/// that contain SSE vectors are placed at 16-byte boundaries while the rest
760/// are at 4-byte boundaries.
761unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
762  if (Subtarget->is64Bit())
763    return getTargetData()->getABITypeAlignment(Ty);
764  unsigned Align = 4;
765  if (Subtarget->hasSSE1())
766    getMaxByValAlign(Ty, Align);
767  return Align;
768}
769
770/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
771/// jumptable.
772SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
773                                                      SelectionDAG &DAG) const {
774  if (usesGlobalOffsetTable())
775    return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
776  if (!Subtarget->isPICStyleRIPRel())
777    return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
778  return Table;
779}
780
781//===----------------------------------------------------------------------===//
782//               Return Value Calling Convention Implementation
783//===----------------------------------------------------------------------===//
784
785#include "X86GenCallingConv.inc"
786
787/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
788/// exists skip possible ISD:TokenFactor.
789static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
790  if (Chain.getOpcode() == X86ISD::TAILCALL) {
791    return Chain;
792  } else if (Chain.getOpcode() == ISD::TokenFactor) {
793    if (Chain.getNumOperands() &&
794        Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
795      return Chain.getOperand(0);
796  }
797  return Chain;
798}
799
800/// LowerRET - Lower an ISD::RET node.
801SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
802  assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
803
804  SmallVector<CCValAssign, 16> RVLocs;
805  unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
806  bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
807  CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
808  CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
809
810  // If this is the first return lowered for this function, add the regs to the
811  // liveout set for the function.
812  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
813    for (unsigned i = 0; i != RVLocs.size(); ++i)
814      if (RVLocs[i].isRegLoc())
815        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
816  }
817  SDOperand Chain = Op.getOperand(0);
818
819  // Handle tail call return.
820  Chain = GetPossiblePreceedingTailCall(Chain);
821  if (Chain.getOpcode() == X86ISD::TAILCALL) {
822    SDOperand TailCall = Chain;
823    SDOperand TargetAddress = TailCall.getOperand(1);
824    SDOperand StackAdjustment = TailCall.getOperand(2);
825    assert(((TargetAddress.getOpcode() == ISD::Register &&
826               (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
827                cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
828              TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
829              TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
830             "Expecting an global address, external symbol, or register");
831    assert(StackAdjustment.getOpcode() == ISD::Constant &&
832           "Expecting a const value");
833
834    SmallVector<SDOperand,8> Operands;
835    Operands.push_back(Chain.getOperand(0));
836    Operands.push_back(TargetAddress);
837    Operands.push_back(StackAdjustment);
838    // Copy registers used by the call. Last operand is a flag so it is not
839    // copied.
840    for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
841      Operands.push_back(Chain.getOperand(i));
842    }
843    return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
844                       Operands.size());
845  }
846
847  // Regular return.
848  SDOperand Flag;
849
850  // Copy the result values into the output registers.
851  if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
852      RVLocs[0].getLocReg() != X86::ST0) {
853    for (unsigned i = 0; i != RVLocs.size(); ++i) {
854      CCValAssign &VA = RVLocs[i];
855      assert(VA.isRegLoc() && "Can only return in registers!");
856      Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
857                               Flag);
858      Flag = Chain.getValue(1);
859    }
860  } else {
861    // We need to handle a destination of ST0 specially, because it isn't really
862    // a register.
863    SDOperand Value = Op.getOperand(1);
864
865    // an XMM register onto the fp-stack.  Do this with an FP_EXTEND to f80.
866    // This will get legalized into a load/store if it can't get optimized away.
867    if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
868      Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
869
870    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
871    SDOperand Ops[] = { Chain, Value };
872    Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
873    Flag = Chain.getValue(1);
874  }
875
876  SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
877  if (Flag.Val)
878    return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
879  else
880    return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
881}
882
883
884/// LowerCallResult - Lower the result values of an ISD::CALL into the
885/// appropriate copies out of appropriate physical registers.  This assumes that
886/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
887/// being lowered.  The returns a SDNode with the same number of values as the
888/// ISD::CALL.
889SDNode *X86TargetLowering::
890LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
891                unsigned CallingConv, SelectionDAG &DAG) {
892
893  // Assign locations to each value returned by this call.
894  SmallVector<CCValAssign, 16> RVLocs;
895  bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
896  CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
897  CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
898
899  SmallVector<SDOperand, 8> ResultVals;
900
901  // Copy all of the result registers out of their specified physreg.
902  if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
903    for (unsigned i = 0; i != RVLocs.size(); ++i) {
904      Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
905                                 RVLocs[i].getValVT(), InFlag).getValue(1);
906      InFlag = Chain.getValue(2);
907      ResultVals.push_back(Chain.getValue(0));
908    }
909  } else {
910    // Copies from the FP stack are special, as ST0 isn't a valid register
911    // before the fp stackifier runs.
912
913    // Copy ST0 into an RFP register with FP_GET_RESULT.  If this will end up
914    // in an SSE register, copy it out as F80 and do a truncate, otherwise use
915    // the specified value type.
916    MVT::ValueType GetResultTy = RVLocs[0].getValVT();
917    if (isScalarFPTypeInSSEReg(GetResultTy))
918      GetResultTy = MVT::f80;
919    SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
920    SDOperand GROps[] = { Chain, InFlag };
921    SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_ST0, Tys, GROps, 2);
922    Chain  = RetVal.getValue(1);
923    InFlag = RetVal.getValue(2);
924
925    // If we want the result in an SSE register, use an FP_TRUNCATE to get it
926    // there.
927    if (GetResultTy != RVLocs[0].getValVT())
928      RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
929                           // This truncation won't change the value.
930                           DAG.getIntPtrConstant(1));
931
932    ResultVals.push_back(RetVal);
933  }
934
935  // Merge everything together with a MERGE_VALUES node.
936  ResultVals.push_back(Chain);
937  return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
938                     &ResultVals[0], ResultVals.size()).Val;
939}
940
941/// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
942/// ISD::CALL where the results are known to be in two 64-bit registers,
943/// e.g. XMM0 and XMM1. This simplify store the two values back to the
944/// fixed stack slot allocated for StructRet.
945SDNode *X86TargetLowering::
946LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
947                              SDNode *TheCall, unsigned Reg1, unsigned Reg2,
948                              MVT::ValueType VT, SelectionDAG &DAG) {
949  SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
950  Chain = RetVal1.getValue(1);
951  InFlag = RetVal1.getValue(2);
952  SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
953  Chain = RetVal2.getValue(1);
954  InFlag = RetVal2.getValue(2);
955  SDOperand FIN = TheCall->getOperand(5);
956  Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
957  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
958  Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
959  return Chain.Val;
960}
961
962/// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
963/// where the results are known to be in ST0 and ST1.
964SDNode *X86TargetLowering::
965LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
966                            SDNode *TheCall, SelectionDAG &DAG) {
967  SmallVector<SDOperand, 8> ResultVals;
968  const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
969  SDVTList Tys = DAG.getVTList(VTs, 4);
970  SDOperand Ops[] = { Chain, InFlag };
971  SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_ST0_ST1, Tys, Ops, 2);
972  Chain = RetVal.getValue(2);
973  SDOperand FIN = TheCall->getOperand(5);
974  Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
975  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
976  Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
977  return Chain.Val;
978}
979
980//===----------------------------------------------------------------------===//
981//                C & StdCall & Fast Calling Convention implementation
982//===----------------------------------------------------------------------===//
983//  StdCall calling convention seems to be standard for many Windows' API
984//  routines and around. It differs from C calling convention just a little:
985//  callee should clean up the stack, not caller. Symbols should be also
986//  decorated in some fancy way :) It doesn't support any vector arguments.
987//  For info on fast calling convention see Fast Calling Convention (tail call)
988//  implementation LowerX86_32FastCCCallTo.
989
990/// AddLiveIn - This helper function adds the specified physical register to the
991/// MachineFunction as a live in value.  It also creates a corresponding virtual
992/// register for it.
993static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
994                          const TargetRegisterClass *RC) {
995  assert(RC->contains(PReg) && "Not the correct regclass!");
996  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
997  MF.getRegInfo().addLiveIn(PReg, VReg);
998  return VReg;
999}
1000
1001/// CallIsStructReturn - Determines whether a CALL node uses struct return
1002/// semantics.
1003static bool CallIsStructReturn(SDOperand Op) {
1004  unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1005  if (!NumOps)
1006    return false;
1007
1008  ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
1009  return Flags->getValue() & ISD::ParamFlags::StructReturn;
1010}
1011
1012/// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1013/// return semantics.
1014static bool ArgsAreStructReturn(SDOperand Op) {
1015  unsigned NumArgs = Op.Val->getNumValues() - 1;
1016  if (!NumArgs)
1017    return false;
1018
1019  ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1020  return Flags->getValue() & ISD::ParamFlags::StructReturn;
1021}
1022
1023/// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires the
1024/// callee to pop its own arguments. Callee pop is necessary to support tail
1025/// calls.
1026bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1027  bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1028  if (IsVarArg)
1029    return false;
1030
1031  switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1032  default:
1033    return false;
1034  case CallingConv::X86_StdCall:
1035    return !Subtarget->is64Bit();
1036  case CallingConv::X86_FastCall:
1037    return !Subtarget->is64Bit();
1038  case CallingConv::Fast:
1039    return PerformTailCallOpt;
1040  }
1041}
1042
1043/// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1044/// FORMAL_ARGUMENTS node.
1045CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1046  unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1047
1048  if (Subtarget->is64Bit()) {
1049    if (CC == CallingConv::Fast && PerformTailCallOpt)
1050      return CC_X86_64_TailCall;
1051    else
1052      return CC_X86_64_C;
1053  }
1054
1055  if (CC == CallingConv::X86_FastCall)
1056    return CC_X86_32_FastCall;
1057  else if (CC == CallingConv::Fast && PerformTailCallOpt)
1058    return CC_X86_32_TailCall;
1059  else
1060    return CC_X86_32_C;
1061}
1062
1063/// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1064/// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1065NameDecorationStyle
1066X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1067  unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1068  if (CC == CallingConv::X86_FastCall)
1069    return FastCall;
1070  else if (CC == CallingConv::X86_StdCall)
1071    return StdCall;
1072  return None;
1073}
1074
1075/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
1076/// possibly be overwritten when lowering the outgoing arguments in a tail
1077/// call. Currently the implementation of this call is very conservative and
1078/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
1079/// virtual registers would be overwritten by direct lowering.
1080static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
1081                                                    MachineFrameInfo * MFI) {
1082  RegisterSDNode * OpReg = NULL;
1083  FrameIndexSDNode * FrameIdxNode = NULL;
1084  int FrameIdx = 0;
1085  if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1086      (Op.getOpcode()== ISD::CopyFromReg &&
1087       (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
1088       (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
1089      (Op.getOpcode() == ISD::LOAD &&
1090       (FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op.getOperand(1))) &&
1091       (MFI->isFixedObjectIndex((FrameIdx = FrameIdxNode->getIndex()))) &&
1092       (MFI->getObjectOffset(FrameIdx) >= 0)))
1093    return true;
1094  return false;
1095}
1096
1097/// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1098/// in a register before calling.
1099bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1100  return !IsTailCall && !Is64Bit &&
1101    getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1102    Subtarget->isPICStyleGOT();
1103}
1104
1105
1106/// CallRequiresFnAddressInReg - Check whether the call requires the function
1107/// address to be loaded in a register.
1108bool
1109X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1110  return !Is64Bit && IsTailCall &&
1111    getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1112    Subtarget->isPICStyleGOT();
1113}
1114
1115/// CopyTailCallClobberedArgumentsToVRegs - Create virtual registers for all
1116/// arguments to force loading and guarantee that arguments sourcing from
1117/// incomming parameters are not overwriting each other.
1118static SDOperand
1119CopyTailCallClobberedArgumentsToVRegs(SDOperand Chain,
1120     SmallVector<std::pair<unsigned, SDOperand>, 8> &TailCallClobberedVRegs,
1121                                      SelectionDAG &DAG,
1122                                      MachineFunction &MF,
1123                                      const TargetLowering * TL) {
1124
1125  SDOperand InFlag;
1126  for (unsigned i = 0, e = TailCallClobberedVRegs.size(); i != e; i++) {
1127    SDOperand Arg = TailCallClobberedVRegs[i].second;
1128    unsigned Idx = TailCallClobberedVRegs[i].first;
1129    unsigned VReg =
1130      MF.getRegInfo().
1131      createVirtualRegister(TL->getRegClassFor(Arg.getValueType()));
1132    Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
1133    InFlag = Chain.getValue(1);
1134    Arg = DAG.getCopyFromReg(Chain, VReg, Arg.getValueType(), InFlag);
1135    TailCallClobberedVRegs[i] = std::make_pair(Idx, Arg);
1136    Chain = Arg.getValue(1);
1137    InFlag = Arg.getValue(2);
1138  }
1139  return Chain;
1140}
1141
1142/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1143/// by "Src" to address "Dst" with size and alignment information specified by
1144/// the specific parameter attribute. The copy will be passed as a byval function
1145/// parameter.
1146static SDOperand
1147CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1148                          unsigned Flags, SelectionDAG &DAG) {
1149  unsigned Align = 1 <<
1150    ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1151  unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1152    ISD::ParamFlags::ByValSizeOffs;
1153  SDOperand AlignNode    = DAG.getConstant(Align, MVT::i32);
1154  SDOperand SizeNode     = DAG.getConstant(Size, MVT::i32);
1155  SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1156  return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1157}
1158
1159SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1160                                              const CCValAssign &VA,
1161                                              MachineFrameInfo *MFI,
1162                                              unsigned CC,
1163                                              SDOperand Root, unsigned i) {
1164  // Create the nodes corresponding to a load from this parameter slot.
1165  unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1166  bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1167  bool isByVal = Flags & ISD::ParamFlags::ByVal;
1168  bool isImmutable = !AlwaysUseMutable && !isByVal;
1169
1170  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1171  // changed with more analysis.
1172  // In case of tail call optimization mark all arguments mutable. Since they
1173  // could be overwritten by lowering of arguments in case of a tail call.
1174  int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1175                                  VA.getLocMemOffset(), isImmutable);
1176  SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1177  if (isByVal)
1178    return FIN;
1179  return DAG.getLoad(VA.getValVT(), Root, FIN,
1180                     PseudoSourceValue::getFixedStack(), FI);
1181}
1182
1183SDOperand
1184X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1185  MachineFunction &MF = DAG.getMachineFunction();
1186  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1187
1188  const Function* Fn = MF.getFunction();
1189  if (Fn->hasExternalLinkage() &&
1190      Subtarget->isTargetCygMing() &&
1191      Fn->getName() == "main")
1192    FuncInfo->setForceFramePointer(true);
1193
1194  // Decorate the function name.
1195  FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1196
1197  MachineFrameInfo *MFI = MF.getFrameInfo();
1198  SDOperand Root = Op.getOperand(0);
1199  bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1200  unsigned CC = MF.getFunction()->getCallingConv();
1201  bool Is64Bit = Subtarget->is64Bit();
1202
1203  assert(!(isVarArg && CC == CallingConv::Fast) &&
1204         "Var args not supported with calling convention fastcc");
1205
1206  // Assign locations to all of the incoming arguments.
1207  SmallVector<CCValAssign, 16> ArgLocs;
1208  CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1209  CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1210
1211  SmallVector<SDOperand, 8> ArgValues;
1212  unsigned LastVal = ~0U;
1213  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1214    CCValAssign &VA = ArgLocs[i];
1215    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1216    // places.
1217    assert(VA.getValNo() != LastVal &&
1218           "Don't support value assigned to multiple locs yet");
1219    LastVal = VA.getValNo();
1220
1221    if (VA.isRegLoc()) {
1222      MVT::ValueType RegVT = VA.getLocVT();
1223      TargetRegisterClass *RC;
1224      if (RegVT == MVT::i32)
1225        RC = X86::GR32RegisterClass;
1226      else if (Is64Bit && RegVT == MVT::i64)
1227        RC = X86::GR64RegisterClass;
1228      else if (RegVT == MVT::f32)
1229        RC = X86::FR32RegisterClass;
1230      else if (RegVT == MVT::f64)
1231        RC = X86::FR64RegisterClass;
1232      else {
1233        assert(MVT::isVector(RegVT));
1234        if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1235          RC = X86::GR64RegisterClass;       // MMX values are passed in GPRs.
1236          RegVT = MVT::i64;
1237        } else
1238          RC = X86::VR128RegisterClass;
1239      }
1240
1241      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1242      SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1243
1244      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1245      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1246      // right size.
1247      if (VA.getLocInfo() == CCValAssign::SExt)
1248        ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1249                               DAG.getValueType(VA.getValVT()));
1250      else if (VA.getLocInfo() == CCValAssign::ZExt)
1251        ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1252                               DAG.getValueType(VA.getValVT()));
1253
1254      if (VA.getLocInfo() != CCValAssign::Full)
1255        ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1256
1257      // Handle MMX values passed in GPRs.
1258      if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1259          MVT::getSizeInBits(RegVT) == 64)
1260        ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1261
1262      ArgValues.push_back(ArgValue);
1263    } else {
1264      assert(VA.isMemLoc());
1265      ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1266    }
1267  }
1268
1269  unsigned StackSize = CCInfo.getNextStackOffset();
1270  // align stack specially for tail calls
1271  if (CC == CallingConv::Fast)
1272    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1273
1274  // If the function takes variable number of arguments, make a frame index for
1275  // the start of the first vararg value... for expansion of llvm.va_start.
1276  if (isVarArg) {
1277    if (Is64Bit || CC != CallingConv::X86_FastCall) {
1278      VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1279    }
1280    if (Is64Bit) {
1281      static const unsigned GPR64ArgRegs[] = {
1282        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8,  X86::R9
1283      };
1284      static const unsigned XMMArgRegs[] = {
1285        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1286        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1287      };
1288
1289      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1290      unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1291
1292      // For X86-64, if there are vararg parameters that are passed via
1293      // registers, then we must store them to their spots on the stack so they
1294      // may be loaded by deferencing the result of va_next.
1295      VarArgsGPOffset = NumIntRegs * 8;
1296      VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1297      RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1298
1299      // Store the integer parameter registers.
1300      SmallVector<SDOperand, 8> MemOps;
1301      SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1302      SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1303                                  DAG.getIntPtrConstant(VarArgsGPOffset));
1304      for (; NumIntRegs != 6; ++NumIntRegs) {
1305        unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1306                                  X86::GR64RegisterClass);
1307        SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1308        SDOperand Store =
1309          DAG.getStore(Val.getValue(1), Val, FIN,
1310                       PseudoSourceValue::getFixedStack(),
1311                       RegSaveFrameIndex);
1312        MemOps.push_back(Store);
1313        FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1314                          DAG.getIntPtrConstant(8));
1315      }
1316
1317      // Now store the XMM (fp + vector) parameter registers.
1318      FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1319                        DAG.getIntPtrConstant(VarArgsFPOffset));
1320      for (; NumXMMRegs != 8; ++NumXMMRegs) {
1321        unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1322                                  X86::VR128RegisterClass);
1323        SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1324        SDOperand Store =
1325          DAG.getStore(Val.getValue(1), Val, FIN,
1326                       PseudoSourceValue::getFixedStack(),
1327                       RegSaveFrameIndex);
1328        MemOps.push_back(Store);
1329        FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1330                          DAG.getIntPtrConstant(16));
1331      }
1332      if (!MemOps.empty())
1333          Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1334                             &MemOps[0], MemOps.size());
1335    }
1336  }
1337
1338  // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1339  // arguments and the arguments after the retaddr has been pushed are
1340  // aligned.
1341  if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1342      !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1343      (StackSize & 7) == 0)
1344    StackSize += 4;
1345
1346  ArgValues.push_back(Root);
1347
1348  // Some CCs need callee pop.
1349  if (IsCalleePop(Op)) {
1350    BytesToPopOnReturn  = StackSize; // Callee pops everything.
1351    BytesCallerReserves = 0;
1352  } else {
1353    BytesToPopOnReturn  = 0; // Callee pops nothing.
1354    // If this is an sret function, the return should pop the hidden pointer.
1355    if (!Is64Bit && ArgsAreStructReturn(Op))
1356      BytesToPopOnReturn = 4;
1357    BytesCallerReserves = StackSize;
1358  }
1359
1360  if (!Is64Bit) {
1361    RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1362    if (CC == CallingConv::X86_FastCall)
1363      VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1364  }
1365
1366  FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1367
1368  // Return the new list of results.
1369  return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1370                     &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1371}
1372
1373SDOperand
1374X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1375                                    const SDOperand &StackPtr,
1376                                    const CCValAssign &VA,
1377                                    SDOperand Chain,
1378                                    SDOperand Arg) {
1379  unsigned LocMemOffset = VA.getLocMemOffset();
1380  SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1381  PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1382  SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1383  unsigned Flags    = cast<ConstantSDNode>(FlagsOp)->getValue();
1384  if (Flags & ISD::ParamFlags::ByVal) {
1385    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1386  }
1387  return DAG.getStore(Chain, Arg, PtrOff,
1388                      PseudoSourceValue::getStack(), LocMemOffset);
1389}
1390
1391/// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1392/// struct return call to the specified function. X86-64 ABI specifies
1393/// some SRet calls are actually returned in registers. Since current
1394/// LLVM cannot represent multi-value calls, they are represent as
1395/// calls where the results are passed in a hidden struct provided by
1396/// the caller. This function examines the type of the struct to
1397/// determine the correct way to implement the call.
1398X86::X86_64SRet
1399X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1400  // FIXME: Disabled for now.
1401  return X86::InMemory;
1402
1403  const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1404  const Type *RTy = PTy->getElementType();
1405  unsigned Size = getTargetData()->getABITypeSize(RTy);
1406  if (Size != 16 && Size != 32)
1407    return X86::InMemory;
1408
1409  if (Size == 32) {
1410    const StructType *STy = dyn_cast<StructType>(RTy);
1411    if (!STy) return X86::InMemory;
1412    if (STy->getNumElements() == 2 &&
1413        STy->getElementType(0) == Type::X86_FP80Ty &&
1414        STy->getElementType(1) == Type::X86_FP80Ty)
1415      return X86::InX87;
1416  }
1417
1418  bool AllFP = true;
1419  for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1420       I != E; ++I) {
1421    const Type *STy = I->get();
1422    if (!STy->isFPOrFPVector()) {
1423      AllFP = false;
1424      break;
1425    }
1426  }
1427
1428  if (AllFP)
1429    return X86::InSSE;
1430  return X86::InGPR64;
1431}
1432
1433void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1434                                                      CCAssignFn *Fn,
1435                                                      CCState &CCInfo) {
1436  unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1437  for (unsigned i = 1; i != NumOps; ++i) {
1438    MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1439    SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1440    unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1441    if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1442      cerr << "Call operand #" << i << " has unhandled type "
1443           << MVT::getValueTypeString(ArgVT) << "\n";
1444      abort();
1445    }
1446  }
1447}
1448
1449SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1450  MachineFunction &MF = DAG.getMachineFunction();
1451  MachineFrameInfo * MFI = MF.getFrameInfo();
1452  SDOperand Chain     = Op.getOperand(0);
1453  unsigned CC         = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1454  bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1455  bool IsTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1456                        && CC == CallingConv::Fast && PerformTailCallOpt;
1457  SDOperand Callee    = Op.getOperand(4);
1458  bool Is64Bit        = Subtarget->is64Bit();
1459  bool IsStructRet    = CallIsStructReturn(Op);
1460
1461  assert(!(isVarArg && CC == CallingConv::Fast) &&
1462         "Var args not supported with calling convention fastcc");
1463
1464  // Analyze operands of the call, assigning locations to each operand.
1465  SmallVector<CCValAssign, 16> ArgLocs;
1466  CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1467  CCAssignFn *CCFn = CCAssignFnForNode(Op);
1468
1469  X86::X86_64SRet SRetMethod = X86::InMemory;
1470  if (Is64Bit && IsStructRet)
1471    // FIXME: We can't figure out type of the sret structure for indirect
1472    // calls. We need to copy more information from CallSite to the ISD::CALL
1473    // node.
1474    if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1475      SRetMethod =
1476        ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1477
1478  // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1479  // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1480  // a sret call.
1481  if (SRetMethod != X86::InMemory)
1482    X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1483  else
1484    CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1485
1486  // Get a count of how many bytes are to be pushed on the stack.
1487  unsigned NumBytes = CCInfo.getNextStackOffset();
1488  if (CC == CallingConv::Fast)
1489    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1490
1491  // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1492  // arguments and the arguments after the retaddr has been pushed are aligned.
1493  if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1494      !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1495      (NumBytes & 7) == 0)
1496    NumBytes += 4;
1497
1498  int FPDiff = 0;
1499  if (IsTailCall) {
1500    // Lower arguments at fp - stackoffset + fpdiff.
1501    unsigned NumBytesCallerPushed =
1502      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1503    FPDiff = NumBytesCallerPushed - NumBytes;
1504
1505    // Set the delta of movement of the returnaddr stackslot.
1506    // But only set if delta is greater than previous delta.
1507    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1508      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1509  }
1510
1511  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1512
1513  SDOperand RetAddrFrIdx;
1514  if (IsTailCall) {
1515    // Adjust the Return address stack slot.
1516    if (FPDiff) {
1517      MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1518      RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1519      // Load the "old" Return address.
1520      RetAddrFrIdx =
1521        DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1522      Chain = SDOperand(RetAddrFrIdx.Val, 1);
1523    }
1524  }
1525
1526  SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1527  SmallVector<std::pair<unsigned, SDOperand>, 8> TailCallClobberedVRegs;
1528  SmallVector<SDOperand, 8> MemOpChains;
1529
1530  SDOperand StackPtr;
1531
1532  // Walk the register/memloc assignments, inserting copies/loads.  For tail
1533  // calls, remember all arguments for later special lowering.
1534  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1535    CCValAssign &VA = ArgLocs[i];
1536    SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1537
1538    // Promote the value if needed.
1539    switch (VA.getLocInfo()) {
1540    default: assert(0 && "Unknown loc info!");
1541    case CCValAssign::Full: break;
1542    case CCValAssign::SExt:
1543      Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1544      break;
1545    case CCValAssign::ZExt:
1546      Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1547      break;
1548    case CCValAssign::AExt:
1549      Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1550      break;
1551    }
1552
1553    if (VA.isRegLoc()) {
1554      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1555    } else {
1556      if (!IsTailCall) {
1557        assert(VA.isMemLoc());
1558        if (StackPtr.Val == 0)
1559          StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1560
1561        MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1562                                               Arg));
1563      } else if (IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
1564        TailCallClobberedVRegs.push_back(std::make_pair(i,Arg));
1565      }
1566    }
1567  }
1568
1569  if (!MemOpChains.empty())
1570    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1571                        &MemOpChains[0], MemOpChains.size());
1572
1573  // Build a sequence of copy-to-reg nodes chained together with token chain
1574  // and flag operands which copy the outgoing args into registers.
1575  SDOperand InFlag;
1576  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1577    Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1578                             InFlag);
1579    InFlag = Chain.getValue(1);
1580  }
1581
1582  // ELF / PIC requires GOT in the EBX register before function calls via PLT
1583  // GOT pointer.
1584  if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1585    Chain = DAG.getCopyToReg(Chain, X86::EBX,
1586                             DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1587                             InFlag);
1588    InFlag = Chain.getValue(1);
1589  }
1590  // If we are tail calling and generating PIC/GOT style code load the address
1591  // of the callee into ecx. The value in ecx is used as target of the tail
1592  // jump. This is done to circumvent the ebx/callee-saved problem for tail
1593  // calls on PIC/GOT architectures. Normally we would just put the address of
1594  // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1595  // restored (since ebx is callee saved) before jumping to the target@PLT.
1596  if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1597    // Note: The actual moving to ecx is done further down.
1598    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1599    if (G &&  !G->getGlobal()->hasHiddenVisibility() &&
1600        !G->getGlobal()->hasProtectedVisibility())
1601      Callee =  LowerGlobalAddress(Callee, DAG);
1602    else if (isa<ExternalSymbolSDNode>(Callee))
1603      Callee = LowerExternalSymbol(Callee,DAG);
1604  }
1605
1606  if (Is64Bit && isVarArg) {
1607    // From AMD64 ABI document:
1608    // For calls that may call functions that use varargs or stdargs
1609    // (prototype-less calls or calls to functions containing ellipsis (...) in
1610    // the declaration) %al is used as hidden argument to specify the number
1611    // of SSE registers used. The contents of %al do not need to match exactly
1612    // the number of registers, but must be an ubound on the number of SSE
1613    // registers used and is in the range 0 - 8 inclusive.
1614
1615    // Count the number of XMM registers allocated.
1616    static const unsigned XMMArgRegs[] = {
1617      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1618      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1619    };
1620    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1621
1622    Chain = DAG.getCopyToReg(Chain, X86::AL,
1623                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1624    InFlag = Chain.getValue(1);
1625  }
1626
1627
1628  // For tail calls lower the arguments to the 'real' stack slot.
1629  if (IsTailCall) {
1630    SmallVector<SDOperand, 8> MemOpChains2;
1631    SDOperand FIN;
1632    int FI = 0;
1633    // Do not flag preceeding copytoreg stuff together with the following stuff.
1634    InFlag = SDOperand();
1635
1636    Chain = CopyTailCallClobberedArgumentsToVRegs(Chain, TailCallClobberedVRegs,
1637                                                  DAG, MF, this);
1638
1639    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1640      CCValAssign &VA = ArgLocs[i];
1641      if (!VA.isRegLoc()) {
1642        assert(VA.isMemLoc());
1643        SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1644        SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1645        unsigned Flags    = cast<ConstantSDNode>(FlagsOp)->getValue();
1646        // Create frame index.
1647        int32_t Offset = VA.getLocMemOffset()+FPDiff;
1648        uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1649        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1650        FIN = DAG.getFrameIndex(FI, MVT::i32);
1651
1652        // Find virtual register for this argument.
1653        bool Found=false;
1654        for (unsigned idx=0, e= TailCallClobberedVRegs.size(); idx < e; idx++)
1655          if (TailCallClobberedVRegs[idx].first==i) {
1656            Arg = TailCallClobberedVRegs[idx].second;
1657            Found=true;
1658            break;
1659          }
1660        assert(IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)==false ||
1661          (Found==true && "No corresponding Argument was found"));
1662
1663        if (Flags & ISD::ParamFlags::ByVal) {
1664          // Copy relative to framepointer.
1665          MemOpChains2.push_back(CreateCopyOfByValArgument(Arg, FIN, Chain,
1666                                                           Flags, DAG));
1667        } else {
1668          // Store relative to framepointer.
1669          MemOpChains2.push_back(
1670            DAG.getStore(Chain, Arg, FIN,
1671                         PseudoSourceValue::getFixedStack(), FI));
1672        }
1673      }
1674    }
1675
1676    if (!MemOpChains2.empty())
1677      Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1678                          &MemOpChains2[0], MemOpChains2.size());
1679
1680    // Store the return address to the appropriate stack slot.
1681    if (FPDiff) {
1682      // Calculate the new stack slot for the return address.
1683      int SlotSize = Is64Bit ? 8 : 4;
1684      int NewReturnAddrFI =
1685        MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1686      MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1687      SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1688      Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1689                           PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1690    }
1691  }
1692
1693  // If the callee is a GlobalAddress node (quite common, every direct call is)
1694  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1695  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1696    // We should use extra load for direct calls to dllimported functions in
1697    // non-JIT mode.
1698    if ((IsTailCall || !Is64Bit ||
1699         getTargetMachine().getCodeModel() != CodeModel::Large)
1700        && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1701                                           getTargetMachine(), true))
1702      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1703  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1704    if (IsTailCall || !Is64Bit ||
1705        getTargetMachine().getCodeModel() != CodeModel::Large)
1706      Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1707  } else if (IsTailCall) {
1708    unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1709
1710    Chain = DAG.getCopyToReg(Chain,
1711                             DAG.getRegister(Opc, getPointerTy()),
1712                             Callee,InFlag);
1713    Callee = DAG.getRegister(Opc, getPointerTy());
1714    // Add register as live out.
1715    DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1716  }
1717
1718  // Returns a chain & a flag for retval copy to use.
1719  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1720  SmallVector<SDOperand, 8> Ops;
1721
1722  if (IsTailCall) {
1723    Ops.push_back(Chain);
1724    Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1725    Ops.push_back(DAG.getIntPtrConstant(0));
1726    if (InFlag.Val)
1727      Ops.push_back(InFlag);
1728    Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1729    InFlag = Chain.getValue(1);
1730
1731    // Returns a chain & a flag for retval copy to use.
1732    NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1733    Ops.clear();
1734  }
1735
1736  Ops.push_back(Chain);
1737  Ops.push_back(Callee);
1738
1739  if (IsTailCall)
1740    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1741
1742  // Add an implicit use GOT pointer in EBX.
1743  if (!IsTailCall && !Is64Bit &&
1744      getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1745      Subtarget->isPICStyleGOT())
1746    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1747
1748  // Add argument registers to the end of the list so that they are known live
1749  // into the call.
1750  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1751    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1752                                  RegsToPass[i].second.getValueType()));
1753
1754  if (InFlag.Val)
1755    Ops.push_back(InFlag);
1756
1757  if (IsTailCall) {
1758    assert(InFlag.Val &&
1759           "Flag must be set. Depend on flag being set in LowerRET");
1760    Chain = DAG.getNode(X86ISD::TAILCALL,
1761                        Op.Val->getVTList(), &Ops[0], Ops.size());
1762
1763    return SDOperand(Chain.Val, Op.ResNo);
1764  }
1765
1766  Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1767  InFlag = Chain.getValue(1);
1768
1769  // Create the CALLSEQ_END node.
1770  unsigned NumBytesForCalleeToPush;
1771  if (IsCalleePop(Op))
1772    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1773  else if (!Is64Bit && IsStructRet)
1774    // If this is is a call to a struct-return function, the callee
1775    // pops the hidden struct pointer, so we have to push it back.
1776    // This is common for Darwin/X86, Linux & Mingw32 targets.
1777    NumBytesForCalleeToPush = 4;
1778  else
1779    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1780
1781  // Returns a flag for retval copy to use.
1782  Chain = DAG.getCALLSEQ_END(Chain,
1783                             DAG.getIntPtrConstant(NumBytes),
1784                             DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1785                             InFlag);
1786  InFlag = Chain.getValue(1);
1787
1788  // Handle result values, copying them out of physregs into vregs that we
1789  // return.
1790  switch (SRetMethod) {
1791  default:
1792    return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1793  case X86::InGPR64:
1794    return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1795                                                   X86::RAX, X86::RDX,
1796                                                   MVT::i64, DAG), Op.ResNo);
1797  case X86::InSSE:
1798    return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1799                                                   X86::XMM0, X86::XMM1,
1800                                                   MVT::f64, DAG), Op.ResNo);
1801  case X86::InX87:
1802    return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1803                     Op.ResNo);
1804  }
1805}
1806
1807
1808//===----------------------------------------------------------------------===//
1809//                Fast Calling Convention (tail call) implementation
1810//===----------------------------------------------------------------------===//
1811
1812//  Like std call, callee cleans arguments, convention except that ECX is
1813//  reserved for storing the tail called function address. Only 2 registers are
1814//  free for argument passing (inreg). Tail call optimization is performed
1815//  provided:
1816//                * tailcallopt is enabled
1817//                * caller/callee are fastcc
1818//  On X86_64 architecture with GOT-style position independent code only local
1819//  (within module) calls are supported at the moment.
1820//  To keep the stack aligned according to platform abi the function
1821//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1822//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1823//  If a tail called function callee has more arguments than the caller the
1824//  caller needs to make sure that there is room to move the RETADDR to. This is
1825//  achieved by reserving an area the size of the argument delta right after the
1826//  original REtADDR, but before the saved framepointer or the spilled registers
1827//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1828//  stack layout:
1829//    arg1
1830//    arg2
1831//    RETADDR
1832//    [ new RETADDR
1833//      move area ]
1834//    (possible EBP)
1835//    ESI
1836//    EDI
1837//    local1 ..
1838
1839/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1840/// for a 16 byte align requirement.
1841unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1842                                                        SelectionDAG& DAG) {
1843  if (PerformTailCallOpt) {
1844    MachineFunction &MF = DAG.getMachineFunction();
1845    const TargetMachine &TM = MF.getTarget();
1846    const TargetFrameInfo &TFI = *TM.getFrameInfo();
1847    unsigned StackAlignment = TFI.getStackAlignment();
1848    uint64_t AlignMask = StackAlignment - 1;
1849    int64_t Offset = StackSize;
1850    unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1851    if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1852      // Number smaller than 12 so just add the difference.
1853      Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1854    } else {
1855      // Mask out lower bits, add stackalignment once plus the 12 bytes.
1856      Offset = ((~AlignMask) & Offset) + StackAlignment +
1857        (StackAlignment-SlotSize);
1858    }
1859    StackSize = Offset;
1860  }
1861  return StackSize;
1862}
1863
1864/// IsEligibleForTailCallElimination - Check to see whether the next instruction
1865/// following the call is a return. A function is eligible if caller/callee
1866/// calling conventions match, currently only fastcc supports tail calls, and
1867/// the function CALL is immediatly followed by a RET.
1868bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1869                                                      SDOperand Ret,
1870                                                      SelectionDAG& DAG) const {
1871  if (!PerformTailCallOpt)
1872    return false;
1873
1874  // Check whether CALL node immediatly preceeds the RET node and whether the
1875  // return uses the result of the node or is a void return.
1876  unsigned NumOps = Ret.getNumOperands();
1877  if ((NumOps == 1 &&
1878       (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1879        Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1880      (NumOps > 1 &&
1881       Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1882       Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1883    MachineFunction &MF = DAG.getMachineFunction();
1884    unsigned CallerCC = MF.getFunction()->getCallingConv();
1885    unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1886    if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1887      SDOperand Callee = Call.getOperand(4);
1888      // On x86/32Bit PIC/GOT  tail calls are supported.
1889      if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1890          !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1891        return true;
1892
1893      // Can only do local tail calls (in same module, hidden or protected) on
1894      // x86_64 PIC/GOT at the moment.
1895      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1896        return G->getGlobal()->hasHiddenVisibility()
1897            || G->getGlobal()->hasProtectedVisibility();
1898    }
1899  }
1900
1901  return false;
1902}
1903
1904//===----------------------------------------------------------------------===//
1905//                           Other Lowering Hooks
1906//===----------------------------------------------------------------------===//
1907
1908
1909SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1910  MachineFunction &MF = DAG.getMachineFunction();
1911  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912  int ReturnAddrIndex = FuncInfo->getRAIndex();
1913
1914  if (ReturnAddrIndex == 0) {
1915    // Set up a frame object for the return address.
1916    if (Subtarget->is64Bit())
1917      ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1918    else
1919      ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1920
1921    FuncInfo->setRAIndex(ReturnAddrIndex);
1922  }
1923
1924  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1925}
1926
1927
1928
1929/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1930/// specific condition code. It returns a false if it cannot do a direct
1931/// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1932/// needed.
1933static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1934                           unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1935                           SelectionDAG &DAG) {
1936  X86CC = X86::COND_INVALID;
1937  if (!isFP) {
1938    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1939      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1940        // X > -1   -> X == 0, jump !sign.
1941        RHS = DAG.getConstant(0, RHS.getValueType());
1942        X86CC = X86::COND_NS;
1943        return true;
1944      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1945        // X < 0   -> X == 0, jump on sign.
1946        X86CC = X86::COND_S;
1947        return true;
1948      } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1949        // X < 1   -> X <= 0
1950        RHS = DAG.getConstant(0, RHS.getValueType());
1951        X86CC = X86::COND_LE;
1952        return true;
1953      }
1954    }
1955
1956    switch (SetCCOpcode) {
1957    default: break;
1958    case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1959    case ISD::SETGT:  X86CC = X86::COND_G;  break;
1960    case ISD::SETGE:  X86CC = X86::COND_GE; break;
1961    case ISD::SETLT:  X86CC = X86::COND_L;  break;
1962    case ISD::SETLE:  X86CC = X86::COND_LE; break;
1963    case ISD::SETNE:  X86CC = X86::COND_NE; break;
1964    case ISD::SETULT: X86CC = X86::COND_B;  break;
1965    case ISD::SETUGT: X86CC = X86::COND_A;  break;
1966    case ISD::SETULE: X86CC = X86::COND_BE; break;
1967    case ISD::SETUGE: X86CC = X86::COND_AE; break;
1968    }
1969  } else {
1970    // On a floating point condition, the flags are set as follows:
1971    // ZF  PF  CF   op
1972    //  0 | 0 | 0 | X > Y
1973    //  0 | 0 | 1 | X < Y
1974    //  1 | 0 | 0 | X == Y
1975    //  1 | 1 | 1 | unordered
1976    bool Flip = false;
1977    switch (SetCCOpcode) {
1978    default: break;
1979    case ISD::SETUEQ:
1980    case ISD::SETEQ: X86CC = X86::COND_E;  break;
1981    case ISD::SETOLT: Flip = true; // Fallthrough
1982    case ISD::SETOGT:
1983    case ISD::SETGT: X86CC = X86::COND_A;  break;
1984    case ISD::SETOLE: Flip = true; // Fallthrough
1985    case ISD::SETOGE:
1986    case ISD::SETGE: X86CC = X86::COND_AE; break;
1987    case ISD::SETUGT: Flip = true; // Fallthrough
1988    case ISD::SETULT:
1989    case ISD::SETLT: X86CC = X86::COND_B;  break;
1990    case ISD::SETUGE: Flip = true; // Fallthrough
1991    case ISD::SETULE:
1992    case ISD::SETLE: X86CC = X86::COND_BE; break;
1993    case ISD::SETONE:
1994    case ISD::SETNE: X86CC = X86::COND_NE; break;
1995    case ISD::SETUO: X86CC = X86::COND_P;  break;
1996    case ISD::SETO:  X86CC = X86::COND_NP; break;
1997    }
1998    if (Flip)
1999      std::swap(LHS, RHS);
2000  }
2001
2002  return X86CC != X86::COND_INVALID;
2003}
2004
2005/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2006/// code. Current x86 isa includes the following FP cmov instructions:
2007/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2008static bool hasFPCMov(unsigned X86CC) {
2009  switch (X86CC) {
2010  default:
2011    return false;
2012  case X86::COND_B:
2013  case X86::COND_BE:
2014  case X86::COND_E:
2015  case X86::COND_P:
2016  case X86::COND_A:
2017  case X86::COND_AE:
2018  case X86::COND_NE:
2019  case X86::COND_NP:
2020    return true;
2021  }
2022}
2023
2024/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
2025/// true if Op is undef or if its value falls within the specified range (L, H].
2026static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2027  if (Op.getOpcode() == ISD::UNDEF)
2028    return true;
2029
2030  unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2031  return (Val >= Low && Val < Hi);
2032}
2033
2034/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2035/// true if Op is undef or if its value equal to the specified value.
2036static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2037  if (Op.getOpcode() == ISD::UNDEF)
2038    return true;
2039  return cast<ConstantSDNode>(Op)->getValue() == Val;
2040}
2041
2042/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2043/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2044bool X86::isPSHUFDMask(SDNode *N) {
2045  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2046
2047  if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2048    return false;
2049
2050  // Check if the value doesn't reference the second vector.
2051  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2052    SDOperand Arg = N->getOperand(i);
2053    if (Arg.getOpcode() == ISD::UNDEF) continue;
2054    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2055    if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2056      return false;
2057  }
2058
2059  return true;
2060}
2061
2062/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2063/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2064bool X86::isPSHUFHWMask(SDNode *N) {
2065  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2066
2067  if (N->getNumOperands() != 8)
2068    return false;
2069
2070  // Lower quadword copied in order.
2071  for (unsigned i = 0; i != 4; ++i) {
2072    SDOperand Arg = N->getOperand(i);
2073    if (Arg.getOpcode() == ISD::UNDEF) continue;
2074    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2075    if (cast<ConstantSDNode>(Arg)->getValue() != i)
2076      return false;
2077  }
2078
2079  // Upper quadword shuffled.
2080  for (unsigned i = 4; i != 8; ++i) {
2081    SDOperand Arg = N->getOperand(i);
2082    if (Arg.getOpcode() == ISD::UNDEF) continue;
2083    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2084    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2085    if (Val < 4 || Val > 7)
2086      return false;
2087  }
2088
2089  return true;
2090}
2091
2092/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2093/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2094bool X86::isPSHUFLWMask(SDNode *N) {
2095  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2096
2097  if (N->getNumOperands() != 8)
2098    return false;
2099
2100  // Upper quadword copied in order.
2101  for (unsigned i = 4; i != 8; ++i)
2102    if (!isUndefOrEqual(N->getOperand(i), i))
2103      return false;
2104
2105  // Lower quadword shuffled.
2106  for (unsigned i = 0; i != 4; ++i)
2107    if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2108      return false;
2109
2110  return true;
2111}
2112
2113/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2114/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2115static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2116  if (NumElems != 2 && NumElems != 4) return false;
2117
2118  unsigned Half = NumElems / 2;
2119  for (unsigned i = 0; i < Half; ++i)
2120    if (!isUndefOrInRange(Elems[i], 0, NumElems))
2121      return false;
2122  for (unsigned i = Half; i < NumElems; ++i)
2123    if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2124      return false;
2125
2126  return true;
2127}
2128
2129bool X86::isSHUFPMask(SDNode *N) {
2130  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2131  return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2132}
2133
2134/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2135/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2136/// half elements to come from vector 1 (which would equal the dest.) and
2137/// the upper half to come from vector 2.
2138static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2139  if (NumOps != 2 && NumOps != 4) return false;
2140
2141  unsigned Half = NumOps / 2;
2142  for (unsigned i = 0; i < Half; ++i)
2143    if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2144      return false;
2145  for (unsigned i = Half; i < NumOps; ++i)
2146    if (!isUndefOrInRange(Ops[i], 0, NumOps))
2147      return false;
2148  return true;
2149}
2150
2151static bool isCommutedSHUFP(SDNode *N) {
2152  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2153  return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2154}
2155
2156/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2157/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2158bool X86::isMOVHLPSMask(SDNode *N) {
2159  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2160
2161  if (N->getNumOperands() != 4)
2162    return false;
2163
2164  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2165  return isUndefOrEqual(N->getOperand(0), 6) &&
2166         isUndefOrEqual(N->getOperand(1), 7) &&
2167         isUndefOrEqual(N->getOperand(2), 2) &&
2168         isUndefOrEqual(N->getOperand(3), 3);
2169}
2170
2171/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2172/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2173/// <2, 3, 2, 3>
2174bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2175  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2176
2177  if (N->getNumOperands() != 4)
2178    return false;
2179
2180  // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2181  return isUndefOrEqual(N->getOperand(0), 2) &&
2182         isUndefOrEqual(N->getOperand(1), 3) &&
2183         isUndefOrEqual(N->getOperand(2), 2) &&
2184         isUndefOrEqual(N->getOperand(3), 3);
2185}
2186
2187/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2188/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2189bool X86::isMOVLPMask(SDNode *N) {
2190  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2191
2192  unsigned NumElems = N->getNumOperands();
2193  if (NumElems != 2 && NumElems != 4)
2194    return false;
2195
2196  for (unsigned i = 0; i < NumElems/2; ++i)
2197    if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2198      return false;
2199
2200  for (unsigned i = NumElems/2; i < NumElems; ++i)
2201    if (!isUndefOrEqual(N->getOperand(i), i))
2202      return false;
2203
2204  return true;
2205}
2206
2207/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2208/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2209/// and MOVLHPS.
2210bool X86::isMOVHPMask(SDNode *N) {
2211  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2212
2213  unsigned NumElems = N->getNumOperands();
2214  if (NumElems != 2 && NumElems != 4)
2215    return false;
2216
2217  for (unsigned i = 0; i < NumElems/2; ++i)
2218    if (!isUndefOrEqual(N->getOperand(i), i))
2219      return false;
2220
2221  for (unsigned i = 0; i < NumElems/2; ++i) {
2222    SDOperand Arg = N->getOperand(i + NumElems/2);
2223    if (!isUndefOrEqual(Arg, i + NumElems))
2224      return false;
2225  }
2226
2227  return true;
2228}
2229
2230/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2231/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2232bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2233                         bool V2IsSplat = false) {
2234  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2235    return false;
2236
2237  for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2238    SDOperand BitI  = Elts[i];
2239    SDOperand BitI1 = Elts[i+1];
2240    if (!isUndefOrEqual(BitI, j))
2241      return false;
2242    if (V2IsSplat) {
2243      if (isUndefOrEqual(BitI1, NumElts))
2244        return false;
2245    } else {
2246      if (!isUndefOrEqual(BitI1, j + NumElts))
2247        return false;
2248    }
2249  }
2250
2251  return true;
2252}
2253
2254bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2255  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2256  return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2257}
2258
2259/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2260/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2261bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2262                         bool V2IsSplat = false) {
2263  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2264    return false;
2265
2266  for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2267    SDOperand BitI  = Elts[i];
2268    SDOperand BitI1 = Elts[i+1];
2269    if (!isUndefOrEqual(BitI, j + NumElts/2))
2270      return false;
2271    if (V2IsSplat) {
2272      if (isUndefOrEqual(BitI1, NumElts))
2273        return false;
2274    } else {
2275      if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2276        return false;
2277    }
2278  }
2279
2280  return true;
2281}
2282
2283bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2284  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285  return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2286}
2287
2288/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2289/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2290/// <0, 0, 1, 1>
2291bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2292  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2293
2294  unsigned NumElems = N->getNumOperands();
2295  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2296    return false;
2297
2298  for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2299    SDOperand BitI  = N->getOperand(i);
2300    SDOperand BitI1 = N->getOperand(i+1);
2301
2302    if (!isUndefOrEqual(BitI, j))
2303      return false;
2304    if (!isUndefOrEqual(BitI1, j))
2305      return false;
2306  }
2307
2308  return true;
2309}
2310
2311/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2312/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2313/// <2, 2, 3, 3>
2314bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2315  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2316
2317  unsigned NumElems = N->getNumOperands();
2318  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2319    return false;
2320
2321  for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2322    SDOperand BitI  = N->getOperand(i);
2323    SDOperand BitI1 = N->getOperand(i + 1);
2324
2325    if (!isUndefOrEqual(BitI, j))
2326      return false;
2327    if (!isUndefOrEqual(BitI1, j))
2328      return false;
2329  }
2330
2331  return true;
2332}
2333
2334/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2335/// specifies a shuffle of elements that is suitable for input to MOVSS,
2336/// MOVSD, and MOVD, i.e. setting the lowest element.
2337static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2338  if (NumElts != 2 && NumElts != 4)
2339    return false;
2340
2341  if (!isUndefOrEqual(Elts[0], NumElts))
2342    return false;
2343
2344  for (unsigned i = 1; i < NumElts; ++i) {
2345    if (!isUndefOrEqual(Elts[i], i))
2346      return false;
2347  }
2348
2349  return true;
2350}
2351
2352bool X86::isMOVLMask(SDNode *N) {
2353  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2354  return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2355}
2356
2357/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2358/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2359/// element of vector 2 and the other elements to come from vector 1 in order.
2360static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2361                           bool V2IsSplat = false,
2362                           bool V2IsUndef = false) {
2363  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2364    return false;
2365
2366  if (!isUndefOrEqual(Ops[0], 0))
2367    return false;
2368
2369  for (unsigned i = 1; i < NumOps; ++i) {
2370    SDOperand Arg = Ops[i];
2371    if (!(isUndefOrEqual(Arg, i+NumOps) ||
2372          (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2373          (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2374      return false;
2375  }
2376
2377  return true;
2378}
2379
2380static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2381                           bool V2IsUndef = false) {
2382  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2383  return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2384                        V2IsSplat, V2IsUndef);
2385}
2386
2387/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2388/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2389bool X86::isMOVSHDUPMask(SDNode *N) {
2390  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2391
2392  if (N->getNumOperands() != 4)
2393    return false;
2394
2395  // Expect 1, 1, 3, 3
2396  for (unsigned i = 0; i < 2; ++i) {
2397    SDOperand Arg = N->getOperand(i);
2398    if (Arg.getOpcode() == ISD::UNDEF) continue;
2399    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2400    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2401    if (Val != 1) return false;
2402  }
2403
2404  bool HasHi = false;
2405  for (unsigned i = 2; i < 4; ++i) {
2406    SDOperand Arg = N->getOperand(i);
2407    if (Arg.getOpcode() == ISD::UNDEF) continue;
2408    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2409    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2410    if (Val != 3) return false;
2411    HasHi = true;
2412  }
2413
2414  // Don't use movshdup if it can be done with a shufps.
2415  return HasHi;
2416}
2417
2418/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2419/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2420bool X86::isMOVSLDUPMask(SDNode *N) {
2421  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2422
2423  if (N->getNumOperands() != 4)
2424    return false;
2425
2426  // Expect 0, 0, 2, 2
2427  for (unsigned i = 0; i < 2; ++i) {
2428    SDOperand Arg = N->getOperand(i);
2429    if (Arg.getOpcode() == ISD::UNDEF) continue;
2430    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2431    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2432    if (Val != 0) return false;
2433  }
2434
2435  bool HasHi = false;
2436  for (unsigned i = 2; i < 4; ++i) {
2437    SDOperand Arg = N->getOperand(i);
2438    if (Arg.getOpcode() == ISD::UNDEF) continue;
2439    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2440    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2441    if (Val != 2) return false;
2442    HasHi = true;
2443  }
2444
2445  // Don't use movshdup if it can be done with a shufps.
2446  return HasHi;
2447}
2448
2449/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2450/// specifies a identity operation on the LHS or RHS.
2451static bool isIdentityMask(SDNode *N, bool RHS = false) {
2452  unsigned NumElems = N->getNumOperands();
2453  for (unsigned i = 0; i < NumElems; ++i)
2454    if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2455      return false;
2456  return true;
2457}
2458
2459/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2460/// a splat of a single element.
2461static bool isSplatMask(SDNode *N) {
2462  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2463
2464  // This is a splat operation if each element of the permute is the same, and
2465  // if the value doesn't reference the second vector.
2466  unsigned NumElems = N->getNumOperands();
2467  SDOperand ElementBase;
2468  unsigned i = 0;
2469  for (; i != NumElems; ++i) {
2470    SDOperand Elt = N->getOperand(i);
2471    if (isa<ConstantSDNode>(Elt)) {
2472      ElementBase = Elt;
2473      break;
2474    }
2475  }
2476
2477  if (!ElementBase.Val)
2478    return false;
2479
2480  for (; i != NumElems; ++i) {
2481    SDOperand Arg = N->getOperand(i);
2482    if (Arg.getOpcode() == ISD::UNDEF) continue;
2483    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2484    if (Arg != ElementBase) return false;
2485  }
2486
2487  // Make sure it is a splat of the first vector operand.
2488  return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2489}
2490
2491/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2492/// a splat of a single element and it's a 2 or 4 element mask.
2493bool X86::isSplatMask(SDNode *N) {
2494  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2495
2496  // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2497  if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2498    return false;
2499  return ::isSplatMask(N);
2500}
2501
2502/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2503/// specifies a splat of zero element.
2504bool X86::isSplatLoMask(SDNode *N) {
2505  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2506
2507  for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2508    if (!isUndefOrEqual(N->getOperand(i), 0))
2509      return false;
2510  return true;
2511}
2512
2513/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2514/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2515/// instructions.
2516unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2517  unsigned NumOperands = N->getNumOperands();
2518  unsigned Shift = (NumOperands == 4) ? 2 : 1;
2519  unsigned Mask = 0;
2520  for (unsigned i = 0; i < NumOperands; ++i) {
2521    unsigned Val = 0;
2522    SDOperand Arg = N->getOperand(NumOperands-i-1);
2523    if (Arg.getOpcode() != ISD::UNDEF)
2524      Val = cast<ConstantSDNode>(Arg)->getValue();
2525    if (Val >= NumOperands) Val -= NumOperands;
2526    Mask |= Val;
2527    if (i != NumOperands - 1)
2528      Mask <<= Shift;
2529  }
2530
2531  return Mask;
2532}
2533
2534/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2535/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2536/// instructions.
2537unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2538  unsigned Mask = 0;
2539  // 8 nodes, but we only care about the last 4.
2540  for (unsigned i = 7; i >= 4; --i) {
2541    unsigned Val = 0;
2542    SDOperand Arg = N->getOperand(i);
2543    if (Arg.getOpcode() != ISD::UNDEF)
2544      Val = cast<ConstantSDNode>(Arg)->getValue();
2545    Mask |= (Val - 4);
2546    if (i != 4)
2547      Mask <<= 2;
2548  }
2549
2550  return Mask;
2551}
2552
2553/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2554/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2555/// instructions.
2556unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2557  unsigned Mask = 0;
2558  // 8 nodes, but we only care about the first 4.
2559  for (int i = 3; i >= 0; --i) {
2560    unsigned Val = 0;
2561    SDOperand Arg = N->getOperand(i);
2562    if (Arg.getOpcode() != ISD::UNDEF)
2563      Val = cast<ConstantSDNode>(Arg)->getValue();
2564    Mask |= Val;
2565    if (i != 0)
2566      Mask <<= 2;
2567  }
2568
2569  return Mask;
2570}
2571
2572/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2573/// specifies a 8 element shuffle that can be broken into a pair of
2574/// PSHUFHW and PSHUFLW.
2575static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2576  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2577
2578  if (N->getNumOperands() != 8)
2579    return false;
2580
2581  // Lower quadword shuffled.
2582  for (unsigned i = 0; i != 4; ++i) {
2583    SDOperand Arg = N->getOperand(i);
2584    if (Arg.getOpcode() == ISD::UNDEF) continue;
2585    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2586    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2587    if (Val >= 4)
2588      return false;
2589  }
2590
2591  // Upper quadword shuffled.
2592  for (unsigned i = 4; i != 8; ++i) {
2593    SDOperand Arg = N->getOperand(i);
2594    if (Arg.getOpcode() == ISD::UNDEF) continue;
2595    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2596    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2597    if (Val < 4 || Val > 7)
2598      return false;
2599  }
2600
2601  return true;
2602}
2603
2604/// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2605/// values in ther permute mask.
2606static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2607                                      SDOperand &V2, SDOperand &Mask,
2608                                      SelectionDAG &DAG) {
2609  MVT::ValueType VT = Op.getValueType();
2610  MVT::ValueType MaskVT = Mask.getValueType();
2611  MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2612  unsigned NumElems = Mask.getNumOperands();
2613  SmallVector<SDOperand, 8> MaskVec;
2614
2615  for (unsigned i = 0; i != NumElems; ++i) {
2616    SDOperand Arg = Mask.getOperand(i);
2617    if (Arg.getOpcode() == ISD::UNDEF) {
2618      MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2619      continue;
2620    }
2621    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2622    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2623    if (Val < NumElems)
2624      MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2625    else
2626      MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2627  }
2628
2629  std::swap(V1, V2);
2630  Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2631  return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2632}
2633
2634/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2635/// the two vector operands have swapped position.
2636static
2637SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2638  MVT::ValueType MaskVT = Mask.getValueType();
2639  MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2640  unsigned NumElems = Mask.getNumOperands();
2641  SmallVector<SDOperand, 8> MaskVec;
2642  for (unsigned i = 0; i != NumElems; ++i) {
2643    SDOperand Arg = Mask.getOperand(i);
2644    if (Arg.getOpcode() == ISD::UNDEF) {
2645      MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2646      continue;
2647    }
2648    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2649    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2650    if (Val < NumElems)
2651      MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2652    else
2653      MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2654  }
2655  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2656}
2657
2658
2659/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2660/// match movhlps. The lower half elements should come from upper half of
2661/// V1 (and in order), and the upper half elements should come from the upper
2662/// half of V2 (and in order).
2663static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2664  unsigned NumElems = Mask->getNumOperands();
2665  if (NumElems != 4)
2666    return false;
2667  for (unsigned i = 0, e = 2; i != e; ++i)
2668    if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2669      return false;
2670  for (unsigned i = 2; i != 4; ++i)
2671    if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2672      return false;
2673  return true;
2674}
2675
2676/// isScalarLoadToVector - Returns true if the node is a scalar load that
2677/// is promoted to a vector.
2678static inline bool isScalarLoadToVector(SDNode *N) {
2679  if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2680    N = N->getOperand(0).Val;
2681    return ISD::isNON_EXTLoad(N);
2682  }
2683  return false;
2684}
2685
2686/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2687/// match movlp{s|d}. The lower half elements should come from lower half of
2688/// V1 (and in order), and the upper half elements should come from the upper
2689/// half of V2 (and in order). And since V1 will become the source of the
2690/// MOVLP, it must be either a vector load or a scalar load to vector.
2691static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2692  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2693    return false;
2694  // Is V2 is a vector load, don't do this transformation. We will try to use
2695  // load folding shufps op.
2696  if (ISD::isNON_EXTLoad(V2))
2697    return false;
2698
2699  unsigned NumElems = Mask->getNumOperands();
2700  if (NumElems != 2 && NumElems != 4)
2701    return false;
2702  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2703    if (!isUndefOrEqual(Mask->getOperand(i), i))
2704      return false;
2705  for (unsigned i = NumElems/2; i != NumElems; ++i)
2706    if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2707      return false;
2708  return true;
2709}
2710
2711/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2712/// all the same.
2713static bool isSplatVector(SDNode *N) {
2714  if (N->getOpcode() != ISD::BUILD_VECTOR)
2715    return false;
2716
2717  SDOperand SplatValue = N->getOperand(0);
2718  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2719    if (N->getOperand(i) != SplatValue)
2720      return false;
2721  return true;
2722}
2723
2724/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2725/// to an undef.
2726static bool isUndefShuffle(SDNode *N) {
2727  if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2728    return false;
2729
2730  SDOperand V1 = N->getOperand(0);
2731  SDOperand V2 = N->getOperand(1);
2732  SDOperand Mask = N->getOperand(2);
2733  unsigned NumElems = Mask.getNumOperands();
2734  for (unsigned i = 0; i != NumElems; ++i) {
2735    SDOperand Arg = Mask.getOperand(i);
2736    if (Arg.getOpcode() != ISD::UNDEF) {
2737      unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2738      if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2739        return false;
2740      else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2741        return false;
2742    }
2743  }
2744  return true;
2745}
2746
2747/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2748/// constant +0.0.
2749static inline bool isZeroNode(SDOperand Elt) {
2750  return ((isa<ConstantSDNode>(Elt) &&
2751           cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2752          (isa<ConstantFPSDNode>(Elt) &&
2753           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2754}
2755
2756/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2757/// to an zero vector.
2758static bool isZeroShuffle(SDNode *N) {
2759  if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2760    return false;
2761
2762  SDOperand V1 = N->getOperand(0);
2763  SDOperand V2 = N->getOperand(1);
2764  SDOperand Mask = N->getOperand(2);
2765  unsigned NumElems = Mask.getNumOperands();
2766  for (unsigned i = 0; i != NumElems; ++i) {
2767    SDOperand Arg = Mask.getOperand(i);
2768    if (Arg.getOpcode() == ISD::UNDEF)
2769      continue;
2770
2771    unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2772    if (Idx < NumElems) {
2773      unsigned Opc = V1.Val->getOpcode();
2774      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2775        continue;
2776      if (Opc != ISD::BUILD_VECTOR ||
2777          !isZeroNode(V1.Val->getOperand(Idx)))
2778        return false;
2779    } else if (Idx >= NumElems) {
2780      unsigned Opc = V2.Val->getOpcode();
2781      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2782        continue;
2783      if (Opc != ISD::BUILD_VECTOR ||
2784          !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2785        return false;
2786    }
2787  }
2788  return true;
2789}
2790
2791/// getZeroVector - Returns a vector of specified type with all zero elements.
2792///
2793static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2794  assert(MVT::isVector(VT) && "Expected a vector type");
2795
2796  // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2797  // type.  This ensures they get CSE'd.
2798  SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2799  SDOperand Vec;
2800  if (MVT::getSizeInBits(VT) == 64)  // MMX
2801    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2802  else                                              // SSE
2803    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2804  return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2805}
2806
2807/// getOnesVector - Returns a vector of specified type with all bits set.
2808///
2809static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2810  assert(MVT::isVector(VT) && "Expected a vector type");
2811
2812  // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2813  // type.  This ensures they get CSE'd.
2814  SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2815  SDOperand Vec;
2816  if (MVT::getSizeInBits(VT) == 64)  // MMX
2817    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2818  else                                              // SSE
2819    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2820  return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2821}
2822
2823
2824/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2825/// that point to V2 points to its first element.
2826static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2827  assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2828
2829  bool Changed = false;
2830  SmallVector<SDOperand, 8> MaskVec;
2831  unsigned NumElems = Mask.getNumOperands();
2832  for (unsigned i = 0; i != NumElems; ++i) {
2833    SDOperand Arg = Mask.getOperand(i);
2834    if (Arg.getOpcode() != ISD::UNDEF) {
2835      unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2836      if (Val > NumElems) {
2837        Arg = DAG.getConstant(NumElems, Arg.getValueType());
2838        Changed = true;
2839      }
2840    }
2841    MaskVec.push_back(Arg);
2842  }
2843
2844  if (Changed)
2845    Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2846                       &MaskVec[0], MaskVec.size());
2847  return Mask;
2848}
2849
2850/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2851/// operation of specified width.
2852static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2853  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2854  MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2855
2856  SmallVector<SDOperand, 8> MaskVec;
2857  MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2858  for (unsigned i = 1; i != NumElems; ++i)
2859    MaskVec.push_back(DAG.getConstant(i, BaseVT));
2860  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2861}
2862
2863/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2864/// of specified width.
2865static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2866  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2867  MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2868  SmallVector<SDOperand, 8> MaskVec;
2869  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2870    MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2871    MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2872  }
2873  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2874}
2875
2876/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2877/// of specified width.
2878static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2879  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2880  MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2881  unsigned Half = NumElems/2;
2882  SmallVector<SDOperand, 8> MaskVec;
2883  for (unsigned i = 0; i != Half; ++i) {
2884    MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2885    MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2886  }
2887  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2888}
2889
2890/// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2891/// element #0 of a vector with the specified index, leaving the rest of the
2892/// elements in place.
2893static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2894                                   SelectionDAG &DAG) {
2895  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2896  MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2897  SmallVector<SDOperand, 8> MaskVec;
2898  // Element #0 of the result gets the elt we are replacing.
2899  MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2900  for (unsigned i = 1; i != NumElems; ++i)
2901    MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2902  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2903}
2904
2905/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2906///
2907static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2908  SDOperand V1 = Op.getOperand(0);
2909  SDOperand Mask = Op.getOperand(2);
2910  MVT::ValueType VT = Op.getValueType();
2911  unsigned NumElems = Mask.getNumOperands();
2912  Mask = getUnpacklMask(NumElems, DAG);
2913  while (NumElems != 4) {
2914    V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2915    NumElems >>= 1;
2916  }
2917  V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2918
2919  Mask = getZeroVector(MVT::v4i32, DAG);
2920  SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2921                                  DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2922  return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2923}
2924
2925/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2926/// vector of zero or undef vector.  This produces a shuffle where the low
2927/// element of V2 is swizzled into the zero/undef vector, landing at element
2928/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2929static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2930                                             bool isZero, SelectionDAG &DAG) {
2931  MVT::ValueType VT = V2.getValueType();
2932  SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2933  unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2934  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2935  MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2936  SmallVector<SDOperand, 16> MaskVec;
2937  for (unsigned i = 0; i != NumElems; ++i)
2938    if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2939      MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2940    else
2941      MaskVec.push_back(DAG.getConstant(i, EVT));
2942  SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2943                               &MaskVec[0], MaskVec.size());
2944  return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2945}
2946
2947/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2948///
2949static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2950                                       unsigned NumNonZero, unsigned NumZero,
2951                                       SelectionDAG &DAG, TargetLowering &TLI) {
2952  if (NumNonZero > 8)
2953    return SDOperand();
2954
2955  SDOperand V(0, 0);
2956  bool First = true;
2957  for (unsigned i = 0; i < 16; ++i) {
2958    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2959    if (ThisIsNonZero && First) {
2960      if (NumZero)
2961        V = getZeroVector(MVT::v8i16, DAG);
2962      else
2963        V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2964      First = false;
2965    }
2966
2967    if ((i & 1) != 0) {
2968      SDOperand ThisElt(0, 0), LastElt(0, 0);
2969      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2970      if (LastIsNonZero) {
2971        LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2972      }
2973      if (ThisIsNonZero) {
2974        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2975        ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2976                              ThisElt, DAG.getConstant(8, MVT::i8));
2977        if (LastIsNonZero)
2978          ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2979      } else
2980        ThisElt = LastElt;
2981
2982      if (ThisElt.Val)
2983        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2984                        DAG.getIntPtrConstant(i/2));
2985    }
2986  }
2987
2988  return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2989}
2990
2991/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2992///
2993static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2994                                       unsigned NumNonZero, unsigned NumZero,
2995                                       SelectionDAG &DAG, TargetLowering &TLI) {
2996  if (NumNonZero > 4)
2997    return SDOperand();
2998
2999  SDOperand V(0, 0);
3000  bool First = true;
3001  for (unsigned i = 0; i < 8; ++i) {
3002    bool isNonZero = (NonZeros & (1 << i)) != 0;
3003    if (isNonZero) {
3004      if (First) {
3005        if (NumZero)
3006          V = getZeroVector(MVT::v8i16, DAG);
3007        else
3008          V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3009        First = false;
3010      }
3011      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3012                      DAG.getIntPtrConstant(i));
3013    }
3014  }
3015
3016  return V;
3017}
3018
3019SDOperand
3020X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3021  // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3022  if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3023    // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3024    // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3025    // eliminated on x86-32 hosts.
3026    if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3027      return Op;
3028
3029    if (ISD::isBuildVectorAllOnes(Op.Val))
3030      return getOnesVector(Op.getValueType(), DAG);
3031    return getZeroVector(Op.getValueType(), DAG);
3032  }
3033
3034  MVT::ValueType VT = Op.getValueType();
3035  MVT::ValueType EVT = MVT::getVectorElementType(VT);
3036  unsigned EVTBits = MVT::getSizeInBits(EVT);
3037
3038  unsigned NumElems = Op.getNumOperands();
3039  unsigned NumZero  = 0;
3040  unsigned NumNonZero = 0;
3041  unsigned NonZeros = 0;
3042  bool IsAllConstants = true;
3043  SmallSet<SDOperand, 8> Values;
3044  for (unsigned i = 0; i < NumElems; ++i) {
3045    SDOperand Elt = Op.getOperand(i);
3046    if (Elt.getOpcode() == ISD::UNDEF)
3047      continue;
3048    Values.insert(Elt);
3049    if (Elt.getOpcode() != ISD::Constant &&
3050        Elt.getOpcode() != ISD::ConstantFP)
3051      IsAllConstants = false;
3052    if (isZeroNode(Elt))
3053      NumZero++;
3054    else {
3055      NonZeros |= (1 << i);
3056      NumNonZero++;
3057    }
3058  }
3059
3060  if (NumNonZero == 0) {
3061    // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3062    return DAG.getNode(ISD::UNDEF, VT);
3063  }
3064
3065  // Special case for single non-zero, non-undef, element.
3066  if (NumNonZero == 1 && NumElems <= 4) {
3067    unsigned Idx = CountTrailingZeros_32(NonZeros);
3068    SDOperand Item = Op.getOperand(Idx);
3069
3070    // If this is an insertion of an i64 value on x86-32, and if the top bits of
3071    // the value are obviously zero, truncate the value to i32 and do the
3072    // insertion that way.  Only do this if the value is non-constant or if the
3073    // value is a constant being inserted into element 0.  It is cheaper to do
3074    // a constant pool load than it is to do a movd + shuffle.
3075    if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3076        (!IsAllConstants || Idx == 0)) {
3077      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3078        // Handle MMX and SSE both.
3079        MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3080        MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3081
3082        // Truncate the value (which may itself be a constant) to i32, and
3083        // convert it to a vector with movd (S2V+shuffle to zero extend).
3084        Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3085        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3086        Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3087
3088        // Now we have our 32-bit value zero extended in the low element of
3089        // a vector.  If Idx != 0, swizzle it into place.
3090        if (Idx != 0) {
3091          SDOperand Ops[] = {
3092            Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3093            getSwapEltZeroMask(VecElts, Idx, DAG)
3094          };
3095          Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3096        }
3097        return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3098      }
3099    }
3100
3101    // If we have a constant or non-constant insertion into the low element of
3102    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3103    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3104    // depending on what the source datatype is.  Because we can only get here
3105    // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3106    if (Idx == 0 &&
3107        // Don't do this for i64 values on x86-32.
3108        (EVT != MVT::i64 || Subtarget->is64Bit())) {
3109      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3110      // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3111      return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3112    }
3113
3114    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3115      return SDOperand();
3116
3117    // Otherwise, if this is a vector with i32 or f32 elements, and the element
3118    // is a non-constant being inserted into an element other than the low one,
3119    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3120    // movd/movss) to move this into the low element, then shuffle it into
3121    // place.
3122    if (EVTBits == 32) {
3123      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3124
3125      // Turn it into a shuffle of zero and zero-extended scalar to vector.
3126      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3127      MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3128      MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3129      SmallVector<SDOperand, 8> MaskVec;
3130      for (unsigned i = 0; i < NumElems; i++)
3131        MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3132      SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3133                                   &MaskVec[0], MaskVec.size());
3134      return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3135                         DAG.getNode(ISD::UNDEF, VT), Mask);
3136    }
3137  }
3138
3139  // Splat is obviously ok. Let legalizer expand it to a shuffle.
3140  if (Values.size() == 1)
3141    return SDOperand();
3142
3143  // A vector full of immediates; various special cases are already
3144  // handled, so this is best done with a single constant-pool load.
3145  if (IsAllConstants)
3146    return SDOperand();
3147
3148  // Let legalizer expand 2-wide build_vectors.
3149  if (EVTBits == 64)
3150    return SDOperand();
3151
3152  // If element VT is < 32 bits, convert it to inserts into a zero vector.
3153  if (EVTBits == 8 && NumElems == 16) {
3154    SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3155                                        *this);
3156    if (V.Val) return V;
3157  }
3158
3159  if (EVTBits == 16 && NumElems == 8) {
3160    SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3161                                        *this);
3162    if (V.Val) return V;
3163  }
3164
3165  // If element VT is == 32 bits, turn it into a number of shuffles.
3166  SmallVector<SDOperand, 8> V;
3167  V.resize(NumElems);
3168  if (NumElems == 4 && NumZero > 0) {
3169    for (unsigned i = 0; i < 4; ++i) {
3170      bool isZero = !(NonZeros & (1 << i));
3171      if (isZero)
3172        V[i] = getZeroVector(VT, DAG);
3173      else
3174        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3175    }
3176
3177    for (unsigned i = 0; i < 2; ++i) {
3178      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3179        default: break;
3180        case 0:
3181          V[i] = V[i*2];  // Must be a zero vector.
3182          break;
3183        case 1:
3184          V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3185                             getMOVLMask(NumElems, DAG));
3186          break;
3187        case 2:
3188          V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3189                             getMOVLMask(NumElems, DAG));
3190          break;
3191        case 3:
3192          V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3193                             getUnpacklMask(NumElems, DAG));
3194          break;
3195      }
3196    }
3197
3198    // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3199    // clears the upper bits.
3200    // FIXME: we can do the same for v4f32 case when we know both parts of
3201    // the lower half come from scalar_to_vector (loadf32). We should do
3202    // that in post legalizer dag combiner with target specific hooks.
3203    if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3204      return V[0];
3205    MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3206    MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3207    SmallVector<SDOperand, 8> MaskVec;
3208    bool Reverse = (NonZeros & 0x3) == 2;
3209    for (unsigned i = 0; i < 2; ++i)
3210      if (Reverse)
3211        MaskVec.push_back(DAG.getConstant(1-i, EVT));
3212      else
3213        MaskVec.push_back(DAG.getConstant(i, EVT));
3214    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3215    for (unsigned i = 0; i < 2; ++i)
3216      if (Reverse)
3217        MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3218      else
3219        MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3220    SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3221                                     &MaskVec[0], MaskVec.size());
3222    return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3223  }
3224
3225  if (Values.size() > 2) {
3226    // Expand into a number of unpckl*.
3227    // e.g. for v4f32
3228    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3229    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3230    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3231    SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3232    for (unsigned i = 0; i < NumElems; ++i)
3233      V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3234    NumElems >>= 1;
3235    while (NumElems != 0) {
3236      for (unsigned i = 0; i < NumElems; ++i)
3237        V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3238                           UnpckMask);
3239      NumElems >>= 1;
3240    }
3241    return V[0];
3242  }
3243
3244  return SDOperand();
3245}
3246
3247static
3248SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3249                                   SDOperand PermMask, SelectionDAG &DAG,
3250                                   TargetLowering &TLI) {
3251  SDOperand NewV;
3252  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3253  MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3254  MVT::ValueType PtrVT = TLI.getPointerTy();
3255  SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3256                                     PermMask.Val->op_end());
3257
3258  // First record which half of which vector the low elements come from.
3259  SmallVector<unsigned, 4> LowQuad(4);
3260  for (unsigned i = 0; i < 4; ++i) {
3261    SDOperand Elt = MaskElts[i];
3262    if (Elt.getOpcode() == ISD::UNDEF)
3263      continue;
3264    unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3265    int QuadIdx = EltIdx / 4;
3266    ++LowQuad[QuadIdx];
3267  }
3268  int BestLowQuad = -1;
3269  unsigned MaxQuad = 1;
3270  for (unsigned i = 0; i < 4; ++i) {
3271    if (LowQuad[i] > MaxQuad) {
3272      BestLowQuad = i;
3273      MaxQuad = LowQuad[i];
3274    }
3275  }
3276
3277  // Record which half of which vector the high elements come from.
3278  SmallVector<unsigned, 4> HighQuad(4);
3279  for (unsigned i = 4; i < 8; ++i) {
3280    SDOperand Elt = MaskElts[i];
3281    if (Elt.getOpcode() == ISD::UNDEF)
3282      continue;
3283    unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3284    int QuadIdx = EltIdx / 4;
3285    ++HighQuad[QuadIdx];
3286  }
3287  int BestHighQuad = -1;
3288  MaxQuad = 1;
3289  for (unsigned i = 0; i < 4; ++i) {
3290    if (HighQuad[i] > MaxQuad) {
3291      BestHighQuad = i;
3292      MaxQuad = HighQuad[i];
3293    }
3294  }
3295
3296  // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3297  if (BestLowQuad != -1 || BestHighQuad != -1) {
3298    // First sort the 4 chunks in order using shufpd.
3299    SmallVector<SDOperand, 8> MaskVec;
3300    if (BestLowQuad != -1)
3301      MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3302    else
3303      MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3304    if (BestHighQuad != -1)
3305      MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3306    else
3307      MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3308    SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3309    NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3310                       DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3311                       DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3312    NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3313
3314    // Now sort high and low parts separately.
3315    BitVector InOrder(8);
3316    if (BestLowQuad != -1) {
3317      // Sort lower half in order using PSHUFLW.
3318      MaskVec.clear();
3319      bool AnyOutOrder = false;
3320      for (unsigned i = 0; i != 4; ++i) {
3321        SDOperand Elt = MaskElts[i];
3322        if (Elt.getOpcode() == ISD::UNDEF) {
3323          MaskVec.push_back(Elt);
3324          InOrder.set(i);
3325        } else {
3326          unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3327          if (EltIdx != i)
3328            AnyOutOrder = true;
3329          MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3330          // If this element is in the right place after this shuffle, then
3331          // remember it.
3332          if ((int)(EltIdx / 4) == BestLowQuad)
3333            InOrder.set(i);
3334        }
3335      }
3336      if (AnyOutOrder) {
3337        for (unsigned i = 4; i != 8; ++i)
3338          MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3339        SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3340        NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3341      }
3342    }
3343
3344    if (BestHighQuad != -1) {
3345      // Sort high half in order using PSHUFHW if possible.
3346      MaskVec.clear();
3347      for (unsigned i = 0; i != 4; ++i)
3348        MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3349      bool AnyOutOrder = false;
3350      for (unsigned i = 4; i != 8; ++i) {
3351        SDOperand Elt = MaskElts[i];
3352        if (Elt.getOpcode() == ISD::UNDEF) {
3353          MaskVec.push_back(Elt);
3354          InOrder.set(i);
3355        } else {
3356          unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3357          if (EltIdx != i)
3358            AnyOutOrder = true;
3359          MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3360          // If this element is in the right place after this shuffle, then
3361          // remember it.
3362          if ((int)(EltIdx / 4) == BestHighQuad)
3363            InOrder.set(i);
3364        }
3365      }
3366      if (AnyOutOrder) {
3367        SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3368        NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3369      }
3370    }
3371
3372    // The other elements are put in the right place using pextrw and pinsrw.
3373    for (unsigned i = 0; i != 8; ++i) {
3374      if (InOrder[i])
3375        continue;
3376      SDOperand Elt = MaskElts[i];
3377      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3378      if (EltIdx == i)
3379        continue;
3380      SDOperand ExtOp = (EltIdx < 8)
3381        ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3382                      DAG.getConstant(EltIdx, PtrVT))
3383        : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3384                      DAG.getConstant(EltIdx - 8, PtrVT));
3385      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3386                         DAG.getConstant(i, PtrVT));
3387    }
3388    return NewV;
3389  }
3390
3391  // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3392  ///as few as possible.
3393  // First, let's find out how many elements are already in the right order.
3394  unsigned V1InOrder = 0;
3395  unsigned V1FromV1 = 0;
3396  unsigned V2InOrder = 0;
3397  unsigned V2FromV2 = 0;
3398  SmallVector<SDOperand, 8> V1Elts;
3399  SmallVector<SDOperand, 8> V2Elts;
3400  for (unsigned i = 0; i < 8; ++i) {
3401    SDOperand Elt = MaskElts[i];
3402    if (Elt.getOpcode() == ISD::UNDEF) {
3403      V1Elts.push_back(Elt);
3404      V2Elts.push_back(Elt);
3405      ++V1InOrder;
3406      ++V2InOrder;
3407      continue;
3408    }
3409    unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3410    if (EltIdx == i) {
3411      V1Elts.push_back(Elt);
3412      V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3413      ++V1InOrder;
3414    } else if (EltIdx == i+8) {
3415      V1Elts.push_back(Elt);
3416      V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3417      ++V2InOrder;
3418    } else if (EltIdx < 8) {
3419      V1Elts.push_back(Elt);
3420      ++V1FromV1;
3421    } else {
3422      V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3423      ++V2FromV2;
3424    }
3425  }
3426
3427  if (V2InOrder > V1InOrder) {
3428    PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3429    std::swap(V1, V2);
3430    std::swap(V1Elts, V2Elts);
3431    std::swap(V1FromV1, V2FromV2);
3432  }
3433
3434  if ((V1FromV1 + V1InOrder) != 8) {
3435    // Some elements are from V2.
3436    if (V1FromV1) {
3437      // If there are elements that are from V1 but out of place,
3438      // then first sort them in place
3439      SmallVector<SDOperand, 8> MaskVec;
3440      for (unsigned i = 0; i < 8; ++i) {
3441        SDOperand Elt = V1Elts[i];
3442        if (Elt.getOpcode() == ISD::UNDEF) {
3443          MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3444          continue;
3445        }
3446        unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3447        if (EltIdx >= 8)
3448          MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3449        else
3450          MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3451      }
3452      SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3453      V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3454    }
3455
3456    NewV = V1;
3457    for (unsigned i = 0; i < 8; ++i) {
3458      SDOperand Elt = V1Elts[i];
3459      if (Elt.getOpcode() == ISD::UNDEF)
3460        continue;
3461      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3462      if (EltIdx < 8)
3463        continue;
3464      SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3465                                    DAG.getConstant(EltIdx - 8, PtrVT));
3466      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3467                         DAG.getConstant(i, PtrVT));
3468    }
3469    return NewV;
3470  } else {
3471    // All elements are from V1.
3472    NewV = V1;
3473    for (unsigned i = 0; i < 8; ++i) {
3474      SDOperand Elt = V1Elts[i];
3475      if (Elt.getOpcode() == ISD::UNDEF)
3476        continue;
3477      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3478      SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3479                                    DAG.getConstant(EltIdx, PtrVT));
3480      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3481                         DAG.getConstant(i, PtrVT));
3482    }
3483    return NewV;
3484  }
3485}
3486
3487/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3488/// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3489/// done when every pair / quad of shuffle mask elements point to elements in
3490/// the right sequence. e.g.
3491/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3492static
3493SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3494                                MVT::ValueType VT,
3495                                SDOperand PermMask, SelectionDAG &DAG,
3496                                TargetLowering &TLI) {
3497  unsigned NumElems = PermMask.getNumOperands();
3498  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3499  MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3500  MVT::ValueType NewVT = MaskVT;
3501  switch (VT) {
3502  case MVT::v4f32: NewVT = MVT::v2f64; break;
3503  case MVT::v4i32: NewVT = MVT::v2i64; break;
3504  case MVT::v8i16: NewVT = MVT::v4i32; break;
3505  case MVT::v16i8: NewVT = MVT::v4i32; break;
3506  default: assert(false && "Unexpected!");
3507  }
3508
3509  if (NewWidth == 2) {
3510    if (MVT::isInteger(VT))
3511      NewVT = MVT::v2i64;
3512    else
3513      NewVT = MVT::v2f64;
3514  }
3515  unsigned Scale = NumElems / NewWidth;
3516  SmallVector<SDOperand, 8> MaskVec;
3517  for (unsigned i = 0; i < NumElems; i += Scale) {
3518    unsigned StartIdx = ~0U;
3519    for (unsigned j = 0; j < Scale; ++j) {
3520      SDOperand Elt = PermMask.getOperand(i+j);
3521      if (Elt.getOpcode() == ISD::UNDEF)
3522        continue;
3523      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3524      if (StartIdx == ~0U)
3525        StartIdx = EltIdx - (EltIdx % Scale);
3526      if (EltIdx != StartIdx + j)
3527        return SDOperand();
3528    }
3529    if (StartIdx == ~0U)
3530      MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3531    else
3532      MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3533  }
3534
3535  V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3536  V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3537  return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3538                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3539                                 &MaskVec[0], MaskVec.size()));
3540}
3541
3542SDOperand
3543X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3544  SDOperand V1 = Op.getOperand(0);
3545  SDOperand V2 = Op.getOperand(1);
3546  SDOperand PermMask = Op.getOperand(2);
3547  MVT::ValueType VT = Op.getValueType();
3548  unsigned NumElems = PermMask.getNumOperands();
3549  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3550  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3551  bool V1IsSplat = false;
3552  bool V2IsSplat = false;
3553
3554  if (isUndefShuffle(Op.Val))
3555    return DAG.getNode(ISD::UNDEF, VT);
3556
3557  if (isZeroShuffle(Op.Val))
3558    return getZeroVector(VT, DAG);
3559
3560  if (isIdentityMask(PermMask.Val))
3561    return V1;
3562  else if (isIdentityMask(PermMask.Val, true))
3563    return V2;
3564
3565  if (isSplatMask(PermMask.Val)) {
3566    if (NumElems <= 4) return Op;
3567    // Promote it to a v4i32 splat.
3568    return PromoteSplat(Op, DAG);
3569  }
3570
3571  // If the shuffle can be profitably rewritten as a narrower shuffle, then
3572  // do it!
3573  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3574    SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3575    if (NewOp.Val)
3576      return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3577  } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3578    // FIXME: Figure out a cleaner way to do this.
3579    // Try to make use of movq to zero out the top part.
3580    if (ISD::isBuildVectorAllZeros(V2.Val)) {
3581      SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3582      if (NewOp.Val) {
3583        SDOperand NewV1 = NewOp.getOperand(0);
3584        SDOperand NewV2 = NewOp.getOperand(1);
3585        SDOperand NewMask = NewOp.getOperand(2);
3586        if (isCommutedMOVL(NewMask.Val, true, false)) {
3587          NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3588          NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3589                              NewV1, NewV2, getMOVLMask(2, DAG));
3590          return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3591        }
3592      }
3593    } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3594      SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3595      if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3596        return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3597    }
3598  }
3599
3600  if (X86::isMOVLMask(PermMask.Val))
3601    return (V1IsUndef) ? V2 : Op;
3602
3603  if (X86::isMOVSHDUPMask(PermMask.Val) ||
3604      X86::isMOVSLDUPMask(PermMask.Val) ||
3605      X86::isMOVHLPSMask(PermMask.Val) ||
3606      X86::isMOVHPMask(PermMask.Val) ||
3607      X86::isMOVLPMask(PermMask.Val))
3608    return Op;
3609
3610  if (ShouldXformToMOVHLPS(PermMask.Val) ||
3611      ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3612    return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3613
3614  bool Commuted = false;
3615  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3616  // 1,1,1,1 -> v8i16 though.
3617  V1IsSplat = isSplatVector(V1.Val);
3618  V2IsSplat = isSplatVector(V2.Val);
3619
3620  // Canonicalize the splat or undef, if present, to be on the RHS.
3621  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3622    Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3623    std::swap(V1IsSplat, V2IsSplat);
3624    std::swap(V1IsUndef, V2IsUndef);
3625    Commuted = true;
3626  }
3627
3628  // FIXME: Figure out a cleaner way to do this.
3629  if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3630    if (V2IsUndef) return V1;
3631    Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3632    if (V2IsSplat) {
3633      // V2 is a splat, so the mask may be malformed. That is, it may point
3634      // to any V2 element. The instruction selectior won't like this. Get
3635      // a corrected mask and commute to form a proper MOVS{S|D}.
3636      SDOperand NewMask = getMOVLMask(NumElems, DAG);
3637      if (NewMask.Val != PermMask.Val)
3638        Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3639    }
3640    return Op;
3641  }
3642
3643  if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3644      X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3645      X86::isUNPCKLMask(PermMask.Val) ||
3646      X86::isUNPCKHMask(PermMask.Val))
3647    return Op;
3648
3649  if (V2IsSplat) {
3650    // Normalize mask so all entries that point to V2 points to its first
3651    // element then try to match unpck{h|l} again. If match, return a
3652    // new vector_shuffle with the corrected mask.
3653    SDOperand NewMask = NormalizeMask(PermMask, DAG);
3654    if (NewMask.Val != PermMask.Val) {
3655      if (X86::isUNPCKLMask(PermMask.Val, true)) {
3656        SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3657        return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3658      } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3659        SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3660        return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3661      }
3662    }
3663  }
3664
3665  // Normalize the node to match x86 shuffle ops if needed
3666  if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3667      Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3668
3669  if (Commuted) {
3670    // Commute is back and try unpck* again.
3671    Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3672    if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3673        X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3674        X86::isUNPCKLMask(PermMask.Val) ||
3675        X86::isUNPCKHMask(PermMask.Val))
3676      return Op;
3677  }
3678
3679  // If VT is integer, try PSHUF* first, then SHUFP*.
3680  if (MVT::isInteger(VT)) {
3681    // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3682    // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3683    if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3684         X86::isPSHUFDMask(PermMask.Val)) ||
3685        X86::isPSHUFHWMask(PermMask.Val) ||
3686        X86::isPSHUFLWMask(PermMask.Val)) {
3687      if (V2.getOpcode() != ISD::UNDEF)
3688        return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3689                           DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3690      return Op;
3691    }
3692
3693    if (X86::isSHUFPMask(PermMask.Val) &&
3694        MVT::getSizeInBits(VT) != 64)    // Don't do this for MMX.
3695      return Op;
3696  } else {
3697    // Floating point cases in the other order.
3698    if (X86::isSHUFPMask(PermMask.Val))
3699      return Op;
3700    if (X86::isPSHUFDMask(PermMask.Val) ||
3701        X86::isPSHUFHWMask(PermMask.Val) ||
3702        X86::isPSHUFLWMask(PermMask.Val)) {
3703      if (V2.getOpcode() != ISD::UNDEF)
3704        return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3705                           DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3706      return Op;
3707    }
3708  }
3709
3710  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3711  if (VT == MVT::v8i16) {
3712    SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3713    if (NewOp.Val)
3714      return NewOp;
3715  }
3716
3717  // Handle all 4 wide cases with a number of shuffles.
3718  if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3719    // Don't do this for MMX.
3720    MVT::ValueType MaskVT = PermMask.getValueType();
3721    MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3722    SmallVector<std::pair<int, int>, 8> Locs;
3723    Locs.reserve(NumElems);
3724    SmallVector<SDOperand, 8> Mask1(NumElems,
3725                                    DAG.getNode(ISD::UNDEF, MaskEVT));
3726    SmallVector<SDOperand, 8> Mask2(NumElems,
3727                                    DAG.getNode(ISD::UNDEF, MaskEVT));
3728    unsigned NumHi = 0;
3729    unsigned NumLo = 0;
3730    // If no more than two elements come from either vector. This can be
3731    // implemented with two shuffles. First shuffle gather the elements.
3732    // The second shuffle, which takes the first shuffle as both of its
3733    // vector operands, put the elements into the right order.
3734    for (unsigned i = 0; i != NumElems; ++i) {
3735      SDOperand Elt = PermMask.getOperand(i);
3736      if (Elt.getOpcode() == ISD::UNDEF) {
3737        Locs[i] = std::make_pair(-1, -1);
3738      } else {
3739        unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3740        if (Val < NumElems) {
3741          Locs[i] = std::make_pair(0, NumLo);
3742          Mask1[NumLo] = Elt;
3743          NumLo++;
3744        } else {
3745          Locs[i] = std::make_pair(1, NumHi);
3746          if (2+NumHi < NumElems)
3747            Mask1[2+NumHi] = Elt;
3748          NumHi++;
3749        }
3750      }
3751    }
3752    if (NumLo <= 2 && NumHi <= 2) {
3753      V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3754                       DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3755                                   &Mask1[0], Mask1.size()));
3756      for (unsigned i = 0; i != NumElems; ++i) {
3757        if (Locs[i].first == -1)
3758          continue;
3759        else {
3760          unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3761          Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3762          Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3763        }
3764      }
3765
3766      return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3767                         DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3768                                     &Mask2[0], Mask2.size()));
3769    }
3770
3771    // Break it into (shuffle shuffle_hi, shuffle_lo).
3772    Locs.clear();
3773    SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3774    SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3775    SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3776    unsigned MaskIdx = 0;
3777    unsigned LoIdx = 0;
3778    unsigned HiIdx = NumElems/2;
3779    for (unsigned i = 0; i != NumElems; ++i) {
3780      if (i == NumElems/2) {
3781        MaskPtr = &HiMask;
3782        MaskIdx = 1;
3783        LoIdx = 0;
3784        HiIdx = NumElems/2;
3785      }
3786      SDOperand Elt = PermMask.getOperand(i);
3787      if (Elt.getOpcode() == ISD::UNDEF) {
3788        Locs[i] = std::make_pair(-1, -1);
3789      } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3790        Locs[i] = std::make_pair(MaskIdx, LoIdx);
3791        (*MaskPtr)[LoIdx] = Elt;
3792        LoIdx++;
3793      } else {
3794        Locs[i] = std::make_pair(MaskIdx, HiIdx);
3795        (*MaskPtr)[HiIdx] = Elt;
3796        HiIdx++;
3797      }
3798    }
3799
3800    SDOperand LoShuffle =
3801      DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3802                  DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3803                              &LoMask[0], LoMask.size()));
3804    SDOperand HiShuffle =
3805      DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3806                  DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3807                              &HiMask[0], HiMask.size()));
3808    SmallVector<SDOperand, 8> MaskOps;
3809    for (unsigned i = 0; i != NumElems; ++i) {
3810      if (Locs[i].first == -1) {
3811        MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3812      } else {
3813        unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3814        MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3815      }
3816    }
3817    return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3818                       DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3819                                   &MaskOps[0], MaskOps.size()));
3820  }
3821
3822  return SDOperand();
3823}
3824
3825SDOperand
3826X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3827                                                SelectionDAG &DAG) {
3828  MVT::ValueType VT = Op.getValueType();
3829  if (MVT::getSizeInBits(VT) == 8) {
3830    SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3831                                    Op.getOperand(0), Op.getOperand(1));
3832    SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3833                                    DAG.getValueType(VT));
3834    return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3835  } else if (MVT::getSizeInBits(VT) == 16) {
3836    SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3837                                    Op.getOperand(0), Op.getOperand(1));
3838    SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3839                                    DAG.getValueType(VT));
3840    return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3841  }
3842  return SDOperand();
3843}
3844
3845
3846SDOperand
3847X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3848  if (!isa<ConstantSDNode>(Op.getOperand(1)))
3849    return SDOperand();
3850
3851  if (Subtarget->hasSSE41())
3852    return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3853
3854  MVT::ValueType VT = Op.getValueType();
3855  // TODO: handle v16i8.
3856  if (MVT::getSizeInBits(VT) == 16) {
3857    SDOperand Vec = Op.getOperand(0);
3858    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3859    if (Idx == 0)
3860      return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3861                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3862                                 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3863                                     Op.getOperand(1)));
3864    // Transform it so it match pextrw which produces a 32-bit result.
3865    MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3866    SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3867                                    Op.getOperand(0), Op.getOperand(1));
3868    SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
3869                                    DAG.getValueType(VT));
3870    return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3871  } else if (MVT::getSizeInBits(VT) == 32) {
3872    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3873    if (Idx == 0)
3874      return Op;
3875    // SHUFPS the element to the lowest double word, then movss.
3876    MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3877    SmallVector<SDOperand, 8> IdxVec;
3878    IdxVec.
3879      push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3880    IdxVec.
3881      push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3882    IdxVec.
3883      push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3884    IdxVec.
3885      push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3886    SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3887                                 &IdxVec[0], IdxVec.size());
3888    SDOperand Vec = Op.getOperand(0);
3889    Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3890                      Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3891    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3892                       DAG.getIntPtrConstant(0));
3893  } else if (MVT::getSizeInBits(VT) == 64) {
3894    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3895    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3896    //        to match extract_elt for f64.
3897    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3898    if (Idx == 0)
3899      return Op;
3900
3901    // UNPCKHPD the element to the lowest double word, then movsd.
3902    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3903    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3904    MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3905    SmallVector<SDOperand, 8> IdxVec;
3906    IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3907    IdxVec.
3908      push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3909    SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3910                                 &IdxVec[0], IdxVec.size());
3911    SDOperand Vec = Op.getOperand(0);
3912    Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3913                      Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3914    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3915                       DAG.getIntPtrConstant(0));
3916  }
3917
3918  return SDOperand();
3919}
3920
3921SDOperand
3922X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3923  MVT::ValueType VT = Op.getValueType();
3924  MVT::ValueType EVT = MVT::getVectorElementType(VT);
3925
3926  SDOperand N0 = Op.getOperand(0);
3927  SDOperand N1 = Op.getOperand(1);
3928  SDOperand N2 = Op.getOperand(2);
3929
3930  if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3931    unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3932                                                  : X86ISD::PINSRW;
3933    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3934    // argument.
3935    if (N1.getValueType() != MVT::i32)
3936      N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3937    if (N2.getValueType() != MVT::i32)
3938      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3939    return DAG.getNode(Opc, VT, N0, N1, N2);
3940  } else if (EVT == MVT::f32) {
3941    // Bits [7:6] of the constant are the source select.  This will always be
3942    //  zero here.  The DAG Combiner may combine an extract_elt index into these
3943    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
3944    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
3945    // Bits [5:4] of the constant are the destination select.  This is the
3946    //  value of the incoming immediate.
3947    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
3948    //   combine either bitwise AND or insert of float 0.0 to set these bits.
3949    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3950    return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3951  }
3952  return SDOperand();
3953}
3954
3955SDOperand
3956X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3957  MVT::ValueType VT = Op.getValueType();
3958  MVT::ValueType EVT = MVT::getVectorElementType(VT);
3959
3960  if (Subtarget->hasSSE41())
3961    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3962
3963  if (EVT == MVT::i8)
3964    return SDOperand();
3965
3966  SDOperand N0 = Op.getOperand(0);
3967  SDOperand N1 = Op.getOperand(1);
3968  SDOperand N2 = Op.getOperand(2);
3969
3970  if (MVT::getSizeInBits(EVT) == 16) {
3971    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3972    // as its second argument.
3973    if (N1.getValueType() != MVT::i32)
3974      N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3975    if (N2.getValueType() != MVT::i32)
3976      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3977    return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3978  }
3979  return SDOperand();
3980}
3981
3982SDOperand
3983X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3984  SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3985  MVT::ValueType VT = MVT::v2i32;
3986  switch (Op.getValueType()) {
3987  default: break;
3988  case MVT::v16i8:
3989  case MVT::v8i16:
3990    VT = MVT::v4i32;
3991    break;
3992  }
3993  return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3994                     DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3995}
3996
3997// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3998// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3999// one of the above mentioned nodes. It has to be wrapped because otherwise
4000// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4001// be used to form addressing mode. These wrapped nodes will be selected
4002// into MOV32ri.
4003SDOperand
4004X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4005  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4006  SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4007                                               getPointerTy(),
4008                                               CP->getAlignment());
4009  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4010  // With PIC, the address is actually $g + Offset.
4011  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4012      !Subtarget->isPICStyleRIPRel()) {
4013    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4014                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4015                         Result);
4016  }
4017
4018  return Result;
4019}
4020
4021SDOperand
4022X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4023  GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4024  SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4025  // If it's a debug information descriptor, don't mess with it.
4026  if (DAG.isVerifiedDebugInfoDesc(Op))
4027    return Result;
4028  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4029  // With PIC, the address is actually $g + Offset.
4030  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4031      !Subtarget->isPICStyleRIPRel()) {
4032    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4033                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4034                         Result);
4035  }
4036
4037  // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4038  // load the value at address GV, not the value of GV itself. This means that
4039  // the GlobalAddress must be in the base or index register of the address, not
4040  // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4041  // The same applies for external symbols during PIC codegen
4042  if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4043    Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4044                         PseudoSourceValue::getGOT(), 0);
4045
4046  return Result;
4047}
4048
4049// Lower ISD::GlobalTLSAddress using the "general dynamic" model
4050static SDOperand
4051LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4052                              const MVT::ValueType PtrVT) {
4053  SDOperand InFlag;
4054  SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4055                                     DAG.getNode(X86ISD::GlobalBaseReg,
4056                                                 PtrVT), InFlag);
4057  InFlag = Chain.getValue(1);
4058
4059  // emit leal symbol@TLSGD(,%ebx,1), %eax
4060  SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4061  SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4062                                             GA->getValueType(0),
4063                                             GA->getOffset());
4064  SDOperand Ops[] = { Chain,  TGA, InFlag };
4065  SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4066  InFlag = Result.getValue(2);
4067  Chain = Result.getValue(1);
4068
4069  // call ___tls_get_addr. This function receives its argument in
4070  // the register EAX.
4071  Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4072  InFlag = Chain.getValue(1);
4073
4074  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4075  SDOperand Ops1[] = { Chain,
4076                      DAG.getTargetExternalSymbol("___tls_get_addr",
4077                                                  PtrVT),
4078                      DAG.getRegister(X86::EAX, PtrVT),
4079                      DAG.getRegister(X86::EBX, PtrVT),
4080                      InFlag };
4081  Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4082  InFlag = Chain.getValue(1);
4083
4084  return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4085}
4086
4087// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4088// "local exec" model.
4089static SDOperand
4090LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4091                         const MVT::ValueType PtrVT) {
4092  // Get the Thread Pointer
4093  SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4094  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4095  // exec)
4096  SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4097                                             GA->getValueType(0),
4098                                             GA->getOffset());
4099  SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4100
4101  if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4102    Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4103                         PseudoSourceValue::getGOT(), 0);
4104
4105  // The address of the thread local variable is the add of the thread
4106  // pointer with the offset of the variable.
4107  return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4108}
4109
4110SDOperand
4111X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4112  // TODO: implement the "local dynamic" model
4113  // TODO: implement the "initial exec"model for pic executables
4114  assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4115         "TLS not implemented for non-ELF and 64-bit targets");
4116  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4117  // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4118  // otherwise use the "Local Exec"TLS Model
4119  if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4120    return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4121  else
4122    return LowerToTLSExecModel(GA, DAG, getPointerTy());
4123}
4124
4125SDOperand
4126X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4127  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4128  SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4129  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4130  // With PIC, the address is actually $g + Offset.
4131  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4132      !Subtarget->isPICStyleRIPRel()) {
4133    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4134                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4135                         Result);
4136  }
4137
4138  return Result;
4139}
4140
4141SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4142  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4143  SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4144  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4145  // With PIC, the address is actually $g + Offset.
4146  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4147      !Subtarget->isPICStyleRIPRel()) {
4148    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4149                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4150                         Result);
4151  }
4152
4153  return Result;
4154}
4155
4156/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4157/// take a 2 x i32 value to shift plus a shift amount.
4158SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4159  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4160  MVT::ValueType VT = Op.getValueType();
4161  unsigned VTBits = MVT::getSizeInBits(VT);
4162  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4163  SDOperand ShOpLo = Op.getOperand(0);
4164  SDOperand ShOpHi = Op.getOperand(1);
4165  SDOperand ShAmt  = Op.getOperand(2);
4166  SDOperand Tmp1 = isSRA ?
4167    DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4168    DAG.getConstant(0, VT);
4169
4170  SDOperand Tmp2, Tmp3;
4171  if (Op.getOpcode() == ISD::SHL_PARTS) {
4172    Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4173    Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4174  } else {
4175    Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4176    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4177  }
4178
4179  const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4180  SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4181                                  DAG.getConstant(VTBits, MVT::i8));
4182  SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4183                               AndNode, DAG.getConstant(0, MVT::i8));
4184
4185  SDOperand Hi, Lo;
4186  SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4187  VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4188  SmallVector<SDOperand, 4> Ops;
4189  if (Op.getOpcode() == ISD::SHL_PARTS) {
4190    Ops.push_back(Tmp2);
4191    Ops.push_back(Tmp3);
4192    Ops.push_back(CC);
4193    Ops.push_back(Cond);
4194    Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4195
4196    Ops.clear();
4197    Ops.push_back(Tmp3);
4198    Ops.push_back(Tmp1);
4199    Ops.push_back(CC);
4200    Ops.push_back(Cond);
4201    Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4202  } else {
4203    Ops.push_back(Tmp2);
4204    Ops.push_back(Tmp3);
4205    Ops.push_back(CC);
4206    Ops.push_back(Cond);
4207    Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4208
4209    Ops.clear();
4210    Ops.push_back(Tmp3);
4211    Ops.push_back(Tmp1);
4212    Ops.push_back(CC);
4213    Ops.push_back(Cond);
4214    Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4215  }
4216
4217  VTs = DAG.getNodeValueTypes(VT, VT);
4218  Ops.clear();
4219  Ops.push_back(Lo);
4220  Ops.push_back(Hi);
4221  return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4222}
4223
4224SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4225  MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4226  assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4227         "Unknown SINT_TO_FP to lower!");
4228
4229  // These are really Legal; caller falls through into that case.
4230  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4231    return SDOperand();
4232  if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4233      Subtarget->is64Bit())
4234    return SDOperand();
4235
4236  unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4237  MachineFunction &MF = DAG.getMachineFunction();
4238  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4239  SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4240  SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4241                                 StackSlot,
4242                                 PseudoSourceValue::getFixedStack(),
4243                                 SSFI);
4244
4245  // Build the FILD
4246  SDVTList Tys;
4247  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4248  if (useSSE)
4249    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4250  else
4251    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4252  SmallVector<SDOperand, 8> Ops;
4253  Ops.push_back(Chain);
4254  Ops.push_back(StackSlot);
4255  Ops.push_back(DAG.getValueType(SrcVT));
4256  SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4257                                 Tys, &Ops[0], Ops.size());
4258
4259  if (useSSE) {
4260    Chain = Result.getValue(1);
4261    SDOperand InFlag = Result.getValue(2);
4262
4263    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4264    // shouldn't be necessary except that RFP cannot be live across
4265    // multiple blocks. When stackifier is fixed, they can be uncoupled.
4266    MachineFunction &MF = DAG.getMachineFunction();
4267    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4268    SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4269    Tys = DAG.getVTList(MVT::Other);
4270    SmallVector<SDOperand, 8> Ops;
4271    Ops.push_back(Chain);
4272    Ops.push_back(Result);
4273    Ops.push_back(StackSlot);
4274    Ops.push_back(DAG.getValueType(Op.getValueType()));
4275    Ops.push_back(InFlag);
4276    Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4277    Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4278                         PseudoSourceValue::getFixedStack(), SSFI);
4279  }
4280
4281  return Result;
4282}
4283
4284std::pair<SDOperand,SDOperand> X86TargetLowering::
4285FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4286  assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4287         "Unknown FP_TO_SINT to lower!");
4288
4289  // These are really Legal.
4290  if (Op.getValueType() == MVT::i32 &&
4291      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4292    return std::make_pair(SDOperand(), SDOperand());
4293  if (Subtarget->is64Bit() &&
4294      Op.getValueType() == MVT::i64 &&
4295      Op.getOperand(0).getValueType() != MVT::f80)
4296    return std::make_pair(SDOperand(), SDOperand());
4297
4298  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4299  // stack slot.
4300  MachineFunction &MF = DAG.getMachineFunction();
4301  unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4302  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4303  SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4304  unsigned Opc;
4305  switch (Op.getValueType()) {
4306  default: assert(0 && "Invalid FP_TO_SINT to lower!");
4307  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4308  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4309  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4310  }
4311
4312  SDOperand Chain = DAG.getEntryNode();
4313  SDOperand Value = Op.getOperand(0);
4314  if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4315    assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4316    Chain = DAG.getStore(Chain, Value, StackSlot,
4317                         PseudoSourceValue::getFixedStack(), SSFI);
4318    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4319    SDOperand Ops[] = {
4320      Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4321    };
4322    Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4323    Chain = Value.getValue(1);
4324    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4325    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4326  }
4327
4328  // Build the FP_TO_INT*_IN_MEM
4329  SDOperand Ops[] = { Chain, Value, StackSlot };
4330  SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4331
4332  return std::make_pair(FIST, StackSlot);
4333}
4334
4335SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4336  std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4337  SDOperand FIST = Vals.first, StackSlot = Vals.second;
4338  if (FIST.Val == 0) return SDOperand();
4339
4340  // Load the result.
4341  return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4342}
4343
4344SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4345  std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4346  SDOperand FIST = Vals.first, StackSlot = Vals.second;
4347  if (FIST.Val == 0) return 0;
4348
4349  // Return an i64 load from the stack slot.
4350  SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4351
4352  // Use a MERGE_VALUES node to drop the chain result value.
4353  return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4354}
4355
4356SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4357  MVT::ValueType VT = Op.getValueType();
4358  MVT::ValueType EltVT = VT;
4359  if (MVT::isVector(VT))
4360    EltVT = MVT::getVectorElementType(VT);
4361  const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4362  std::vector<Constant*> CV;
4363  if (EltVT == MVT::f64) {
4364    Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4365    CV.push_back(C);
4366    CV.push_back(C);
4367  } else {
4368    Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4369    CV.push_back(C);
4370    CV.push_back(C);
4371    CV.push_back(C);
4372    CV.push_back(C);
4373  }
4374  Constant *C = ConstantVector::get(CV);
4375  SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4376  SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4377                               PseudoSourceValue::getConstantPool(), 0,
4378                               false, 16);
4379  return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4380}
4381
4382SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4383  MVT::ValueType VT = Op.getValueType();
4384  MVT::ValueType EltVT = VT;
4385  unsigned EltNum = 1;
4386  if (MVT::isVector(VT)) {
4387    EltVT = MVT::getVectorElementType(VT);
4388    EltNum = MVT::getVectorNumElements(VT);
4389  }
4390  const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4391  std::vector<Constant*> CV;
4392  if (EltVT == MVT::f64) {
4393    Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4394    CV.push_back(C);
4395    CV.push_back(C);
4396  } else {
4397    Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4398    CV.push_back(C);
4399    CV.push_back(C);
4400    CV.push_back(C);
4401    CV.push_back(C);
4402  }
4403  Constant *C = ConstantVector::get(CV);
4404  SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4405  SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4406                               PseudoSourceValue::getConstantPool(), 0,
4407                               false, 16);
4408  if (MVT::isVector(VT)) {
4409    return DAG.getNode(ISD::BIT_CONVERT, VT,
4410                       DAG.getNode(ISD::XOR, MVT::v2i64,
4411                    DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4412                    DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4413  } else {
4414    return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4415  }
4416}
4417
4418SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4419  SDOperand Op0 = Op.getOperand(0);
4420  SDOperand Op1 = Op.getOperand(1);
4421  MVT::ValueType VT = Op.getValueType();
4422  MVT::ValueType SrcVT = Op1.getValueType();
4423  const Type *SrcTy =  MVT::getTypeForValueType(SrcVT);
4424
4425  // If second operand is smaller, extend it first.
4426  if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4427    Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4428    SrcVT = VT;
4429    SrcTy = MVT::getTypeForValueType(SrcVT);
4430  }
4431  // And if it is bigger, shrink it first.
4432  if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4433    Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4434    SrcVT = VT;
4435    SrcTy = MVT::getTypeForValueType(SrcVT);
4436  }
4437
4438  // At this point the operands and the result should have the same
4439  // type, and that won't be f80 since that is not custom lowered.
4440
4441  // First get the sign bit of second operand.
4442  std::vector<Constant*> CV;
4443  if (SrcVT == MVT::f64) {
4444    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4445    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4446  } else {
4447    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4448    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4449    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4450    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4451  }
4452  Constant *C = ConstantVector::get(CV);
4453  SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4454  SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4455                                PseudoSourceValue::getConstantPool(), 0,
4456                                false, 16);
4457  SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4458
4459  // Shift sign bit right or left if the two operands have different types.
4460  if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4461    // Op0 is MVT::f32, Op1 is MVT::f64.
4462    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4463    SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4464                          DAG.getConstant(32, MVT::i32));
4465    SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4466    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4467                          DAG.getIntPtrConstant(0));
4468  }
4469
4470  // Clear first operand sign bit.
4471  CV.clear();
4472  if (VT == MVT::f64) {
4473    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4474    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4475  } else {
4476    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4477    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4478    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4479    CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4480  }
4481  C = ConstantVector::get(CV);
4482  CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4483  SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4484                                PseudoSourceValue::getConstantPool(), 0,
4485                                false, 16);
4486  SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4487
4488  // Or the value with the sign bit.
4489  return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4490}
4491
4492SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4493  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4494  SDOperand Cond;
4495  SDOperand Op0 = Op.getOperand(0);
4496  SDOperand Op1 = Op.getOperand(1);
4497  SDOperand CC = Op.getOperand(2);
4498  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4499  bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4500  unsigned X86CC;
4501
4502  if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4503                     Op0, Op1, DAG)) {
4504    Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4505    return DAG.getNode(X86ISD::SETCC, MVT::i8,
4506                       DAG.getConstant(X86CC, MVT::i8), Cond);
4507  }
4508
4509  assert(isFP && "Illegal integer SetCC!");
4510
4511  Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4512  switch (SetCCOpcode) {
4513  default: assert(false && "Illegal floating point SetCC!");
4514  case ISD::SETOEQ: {  // !PF & ZF
4515    SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4516                                 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4517    SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4518                                 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4519    return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4520  }
4521  case ISD::SETUNE: {  // PF | !ZF
4522    SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4523                                 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4524    SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4525                                 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4526    return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4527  }
4528  }
4529}
4530
4531
4532SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4533  bool addTest = true;
4534  SDOperand Cond  = Op.getOperand(0);
4535  SDOperand CC;
4536
4537  if (Cond.getOpcode() == ISD::SETCC)
4538    Cond = LowerSETCC(Cond, DAG);
4539
4540  // If condition flag is set by a X86ISD::CMP, then use it as the condition
4541  // setting operand in place of the X86ISD::SETCC.
4542  if (Cond.getOpcode() == X86ISD::SETCC) {
4543    CC = Cond.getOperand(0);
4544
4545    SDOperand Cmp = Cond.getOperand(1);
4546    unsigned Opc = Cmp.getOpcode();
4547    MVT::ValueType VT = Op.getValueType();
4548
4549    bool IllegalFPCMov = false;
4550    if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4551        !isScalarFPTypeInSSEReg(VT))  // FPStack?
4552      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4553
4554    if ((Opc == X86ISD::CMP ||
4555         Opc == X86ISD::COMI ||
4556         Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4557      Cond = Cmp;
4558      addTest = false;
4559    }
4560  }
4561
4562  if (addTest) {
4563    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4564    Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4565  }
4566
4567  const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4568                                                    MVT::Flag);
4569  SmallVector<SDOperand, 4> Ops;
4570  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4571  // condition is true.
4572  Ops.push_back(Op.getOperand(2));
4573  Ops.push_back(Op.getOperand(1));
4574  Ops.push_back(CC);
4575  Ops.push_back(Cond);
4576  return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4577}
4578
4579SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4580  bool addTest = true;
4581  SDOperand Chain = Op.getOperand(0);
4582  SDOperand Cond  = Op.getOperand(1);
4583  SDOperand Dest  = Op.getOperand(2);
4584  SDOperand CC;
4585
4586  if (Cond.getOpcode() == ISD::SETCC)
4587    Cond = LowerSETCC(Cond, DAG);
4588
4589  // If condition flag is set by a X86ISD::CMP, then use it as the condition
4590  // setting operand in place of the X86ISD::SETCC.
4591  if (Cond.getOpcode() == X86ISD::SETCC) {
4592    CC = Cond.getOperand(0);
4593
4594    SDOperand Cmp = Cond.getOperand(1);
4595    unsigned Opc = Cmp.getOpcode();
4596    if (Opc == X86ISD::CMP ||
4597        Opc == X86ISD::COMI ||
4598        Opc == X86ISD::UCOMI) {
4599      Cond = Cmp;
4600      addTest = false;
4601    }
4602  }
4603
4604  if (addTest) {
4605    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4606    Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4607  }
4608  return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4609                     Chain, Op.getOperand(2), CC, Cond);
4610}
4611
4612
4613// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4614// Calls to _alloca is needed to probe the stack when allocating more than 4k
4615// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4616// that the guard pages used by the OS virtual memory manager are allocated in
4617// correct sequence.
4618SDOperand
4619X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4620                                           SelectionDAG &DAG) {
4621  assert(Subtarget->isTargetCygMing() &&
4622         "This should be used only on Cygwin/Mingw targets");
4623
4624  // Get the inputs.
4625  SDOperand Chain = Op.getOperand(0);
4626  SDOperand Size  = Op.getOperand(1);
4627  // FIXME: Ensure alignment here
4628
4629  SDOperand Flag;
4630
4631  MVT::ValueType IntPtr = getPointerTy();
4632  MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4633
4634  Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4635  Flag = Chain.getValue(1);
4636
4637  SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4638  SDOperand Ops[] = { Chain,
4639                      DAG.getTargetExternalSymbol("_alloca", IntPtr),
4640                      DAG.getRegister(X86::EAX, IntPtr),
4641                      Flag };
4642  Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4643  Flag = Chain.getValue(1);
4644
4645  Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4646
4647  std::vector<MVT::ValueType> Tys;
4648  Tys.push_back(SPTy);
4649  Tys.push_back(MVT::Other);
4650  SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4651  return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4652}
4653
4654SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4655  SDOperand InFlag(0, 0);
4656  SDOperand Chain = Op.getOperand(0);
4657  unsigned Align =
4658    (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4659  if (Align == 0) Align = 1;
4660
4661  ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4662  // If not DWORD aligned or size is more than the threshold, call memset.
4663  // The libc version is likely to be faster for these cases. It can use the
4664  // address value and run time information about the CPU.
4665  if ((Align & 3) != 0 ||
4666      (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4667    MVT::ValueType IntPtr = getPointerTy();
4668    const Type *IntPtrTy = getTargetData()->getIntPtrType();
4669    TargetLowering::ArgListTy Args;
4670    TargetLowering::ArgListEntry Entry;
4671    Entry.Node = Op.getOperand(1);
4672    Entry.Ty = IntPtrTy;
4673    Args.push_back(Entry);
4674    // Extend the unsigned i8 argument to be an int value for the call.
4675    Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4676    Entry.Ty = IntPtrTy;
4677    Args.push_back(Entry);
4678    Entry.Node = Op.getOperand(3);
4679    Args.push_back(Entry);
4680    std::pair<SDOperand,SDOperand> CallResult =
4681      LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4682                  false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4683    return CallResult.second;
4684  }
4685
4686  MVT::ValueType AVT;
4687  SDOperand Count;
4688  ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4689  unsigned BytesLeft = 0;
4690  bool TwoRepStos = false;
4691  if (ValC) {
4692    unsigned ValReg;
4693    uint64_t Val = ValC->getValue() & 255;
4694
4695    // If the value is a constant, then we can potentially use larger sets.
4696    switch (Align & 3) {
4697      case 2:   // WORD aligned
4698        AVT = MVT::i16;
4699        ValReg = X86::AX;
4700        Val = (Val << 8) | Val;
4701        break;
4702      case 0:  // DWORD aligned
4703        AVT = MVT::i32;
4704        ValReg = X86::EAX;
4705        Val = (Val << 8)  | Val;
4706        Val = (Val << 16) | Val;
4707        if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) {  // QWORD aligned
4708          AVT = MVT::i64;
4709          ValReg = X86::RAX;
4710          Val = (Val << 32) | Val;
4711        }
4712        break;
4713      default:  // Byte aligned
4714        AVT = MVT::i8;
4715        ValReg = X86::AL;
4716        Count = Op.getOperand(3);
4717        break;
4718    }
4719
4720    if (AVT > MVT::i8) {
4721      if (I) {
4722        unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4723        Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4724        BytesLeft = I->getValue() % UBytes;
4725      } else {
4726        assert(AVT >= MVT::i32 &&
4727               "Do not use rep;stos if not at least DWORD aligned");
4728        Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4729                            Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4730        TwoRepStos = true;
4731      }
4732    }
4733
4734    Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4735                              InFlag);
4736    InFlag = Chain.getValue(1);
4737  } else {
4738    AVT = MVT::i8;
4739    Count  = Op.getOperand(3);
4740    Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4741    InFlag = Chain.getValue(1);
4742  }
4743
4744  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4745                            Count, InFlag);
4746  InFlag = Chain.getValue(1);
4747  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4748                            Op.getOperand(1), InFlag);
4749  InFlag = Chain.getValue(1);
4750
4751  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4752  SmallVector<SDOperand, 8> Ops;
4753  Ops.push_back(Chain);
4754  Ops.push_back(DAG.getValueType(AVT));
4755  Ops.push_back(InFlag);
4756  Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4757
4758  if (TwoRepStos) {
4759    InFlag = Chain.getValue(1);
4760    Count = Op.getOperand(3);
4761    MVT::ValueType CVT = Count.getValueType();
4762    SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4763                               DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4764    Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4765                              Left, InFlag);
4766    InFlag = Chain.getValue(1);
4767    Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4768    Ops.clear();
4769    Ops.push_back(Chain);
4770    Ops.push_back(DAG.getValueType(MVT::i8));
4771    Ops.push_back(InFlag);
4772    Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4773  } else if (BytesLeft) {
4774    // Issue stores for the last 1 - 7 bytes.
4775    SDOperand Value;
4776    unsigned Val = ValC->getValue() & 255;
4777    unsigned Offset = I->getValue() - BytesLeft;
4778    SDOperand DstAddr = Op.getOperand(1);
4779    MVT::ValueType AddrVT = DstAddr.getValueType();
4780    if (BytesLeft >= 4) {
4781      Val = (Val << 8)  | Val;
4782      Val = (Val << 16) | Val;
4783      Value = DAG.getConstant(Val, MVT::i32);
4784      Chain = DAG.getStore(Chain, Value,
4785                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4786                                       DAG.getConstant(Offset, AddrVT)),
4787                           NULL, 0);
4788      BytesLeft -= 4;
4789      Offset += 4;
4790    }
4791    if (BytesLeft >= 2) {
4792      Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4793      Chain = DAG.getStore(Chain, Value,
4794                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4795                                       DAG.getConstant(Offset, AddrVT)),
4796                           NULL, 0);
4797      BytesLeft -= 2;
4798      Offset += 2;
4799    }
4800    if (BytesLeft == 1) {
4801      Value = DAG.getConstant(Val, MVT::i8);
4802      Chain = DAG.getStore(Chain, Value,
4803                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4804                                       DAG.getConstant(Offset, AddrVT)),
4805                           NULL, 0);
4806    }
4807  }
4808
4809  return Chain;
4810}
4811
4812SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4813                                               SDOperand Dest,
4814                                               SDOperand Source,
4815                                               unsigned Size,
4816                                               unsigned Align,
4817                                               SelectionDAG &DAG) {
4818  MVT::ValueType AVT;
4819  unsigned BytesLeft = 0;
4820  switch (Align & 3) {
4821    case 2:   // WORD aligned
4822      AVT = MVT::i16;
4823      break;
4824    case 0:  // DWORD aligned
4825      AVT = MVT::i32;
4826      if (Subtarget->is64Bit() && ((Align & 0xF) == 0))  // QWORD aligned
4827        AVT = MVT::i64;
4828      break;
4829    default:  // Byte aligned
4830      AVT = MVT::i8;
4831      break;
4832  }
4833
4834  unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4835  SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4836  BytesLeft = Size % UBytes;
4837
4838  SDOperand InFlag(0, 0);
4839  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4840                            Count, InFlag);
4841  InFlag = Chain.getValue(1);
4842  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4843                            Dest, InFlag);
4844  InFlag = Chain.getValue(1);
4845  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4846                            Source, InFlag);
4847  InFlag = Chain.getValue(1);
4848
4849  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4850  SmallVector<SDOperand, 8> Ops;
4851  Ops.push_back(Chain);
4852  Ops.push_back(DAG.getValueType(AVT));
4853  Ops.push_back(InFlag);
4854  Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4855
4856  if (BytesLeft) {
4857    // Issue loads and stores for the last 1 - 7 bytes.
4858    unsigned Offset = Size - BytesLeft;
4859    SDOperand DstAddr = Dest;
4860    MVT::ValueType DstVT = DstAddr.getValueType();
4861    SDOperand SrcAddr = Source;
4862    MVT::ValueType SrcVT = SrcAddr.getValueType();
4863    SDOperand Value;
4864    if (BytesLeft >= 4) {
4865      Value = DAG.getLoad(MVT::i32, Chain,
4866                          DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4867                                      DAG.getConstant(Offset, SrcVT)),
4868                          NULL, 0);
4869      Chain = Value.getValue(1);
4870      Chain = DAG.getStore(Chain, Value,
4871                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
4872                                       DAG.getConstant(Offset, DstVT)),
4873                           NULL, 0);
4874      BytesLeft -= 4;
4875      Offset += 4;
4876    }
4877    if (BytesLeft >= 2) {
4878      Value = DAG.getLoad(MVT::i16, Chain,
4879                          DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4880                                      DAG.getConstant(Offset, SrcVT)),
4881                          NULL, 0);
4882      Chain = Value.getValue(1);
4883      Chain = DAG.getStore(Chain, Value,
4884                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
4885                                       DAG.getConstant(Offset, DstVT)),
4886                           NULL, 0);
4887      BytesLeft -= 2;
4888      Offset += 2;
4889    }
4890
4891    if (BytesLeft == 1) {
4892      Value = DAG.getLoad(MVT::i8, Chain,
4893                          DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4894                                      DAG.getConstant(Offset, SrcVT)),
4895                          NULL, 0);
4896      Chain = Value.getValue(1);
4897      Chain = DAG.getStore(Chain, Value,
4898                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
4899                                       DAG.getConstant(Offset, DstVT)),
4900                           NULL, 0);
4901    }
4902  }
4903
4904  return Chain;
4905}
4906
4907/// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4908SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4909  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4910  SDOperand TheChain = N->getOperand(0);
4911  SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4912  if (Subtarget->is64Bit()) {
4913    SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4914    SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4915                                       MVT::i64, rax.getValue(2));
4916    SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4917                                DAG.getConstant(32, MVT::i8));
4918    SDOperand Ops[] = {
4919      DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4920    };
4921
4922    Tys = DAG.getVTList(MVT::i64, MVT::Other);
4923    return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4924  }
4925
4926  SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4927  SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4928                                       MVT::i32, eax.getValue(2));
4929  // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4930  SDOperand Ops[] = { eax, edx };
4931  Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4932
4933  // Use a MERGE_VALUES to return the value and chain.
4934  Ops[1] = edx.getValue(1);
4935  Tys = DAG.getVTList(MVT::i64, MVT::Other);
4936  return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4937}
4938
4939SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4940  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4941
4942  if (!Subtarget->is64Bit()) {
4943    // vastart just stores the address of the VarArgsFrameIndex slot into the
4944    // memory location argument.
4945    SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4946    return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4947  }
4948
4949  // __va_list_tag:
4950  //   gp_offset         (0 - 6 * 8)
4951  //   fp_offset         (48 - 48 + 8 * 16)
4952  //   overflow_arg_area (point to parameters coming in memory).
4953  //   reg_save_area
4954  SmallVector<SDOperand, 8> MemOps;
4955  SDOperand FIN = Op.getOperand(1);
4956  // Store gp_offset
4957  SDOperand Store = DAG.getStore(Op.getOperand(0),
4958                                 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4959                                 FIN, SV, 0);
4960  MemOps.push_back(Store);
4961
4962  // Store fp_offset
4963  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4964  Store = DAG.getStore(Op.getOperand(0),
4965                       DAG.getConstant(VarArgsFPOffset, MVT::i32),
4966                       FIN, SV, 0);
4967  MemOps.push_back(Store);
4968
4969  // Store ptr to overflow_arg_area
4970  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4971  SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4972  Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4973  MemOps.push_back(Store);
4974
4975  // Store ptr to reg_save_area.
4976  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4977  SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4978  Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4979  MemOps.push_back(Store);
4980  return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4981}
4982
4983SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4984  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4985  SDOperand Chain = Op.getOperand(0);
4986  SDOperand DstPtr = Op.getOperand(1);
4987  SDOperand SrcPtr = Op.getOperand(2);
4988  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4989  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4990
4991  SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4992  Chain = SrcPtr.getValue(1);
4993  for (unsigned i = 0; i < 3; ++i) {
4994    SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4995    Chain = Val.getValue(1);
4996    Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4997    if (i == 2)
4998      break;
4999    SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5000                         DAG.getIntPtrConstant(8));
5001    DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5002                         DAG.getIntPtrConstant(8));
5003  }
5004  return Chain;
5005}
5006
5007SDOperand
5008X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5009  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5010  switch (IntNo) {
5011  default: return SDOperand();    // Don't custom lower most intrinsics.
5012    // Comparison intrinsics.
5013  case Intrinsic::x86_sse_comieq_ss:
5014  case Intrinsic::x86_sse_comilt_ss:
5015  case Intrinsic::x86_sse_comile_ss:
5016  case Intrinsic::x86_sse_comigt_ss:
5017  case Intrinsic::x86_sse_comige_ss:
5018  case Intrinsic::x86_sse_comineq_ss:
5019  case Intrinsic::x86_sse_ucomieq_ss:
5020  case Intrinsic::x86_sse_ucomilt_ss:
5021  case Intrinsic::x86_sse_ucomile_ss:
5022  case Intrinsic::x86_sse_ucomigt_ss:
5023  case Intrinsic::x86_sse_ucomige_ss:
5024  case Intrinsic::x86_sse_ucomineq_ss:
5025  case Intrinsic::x86_sse2_comieq_sd:
5026  case Intrinsic::x86_sse2_comilt_sd:
5027  case Intrinsic::x86_sse2_comile_sd:
5028  case Intrinsic::x86_sse2_comigt_sd:
5029  case Intrinsic::x86_sse2_comige_sd:
5030  case Intrinsic::x86_sse2_comineq_sd:
5031  case Intrinsic::x86_sse2_ucomieq_sd:
5032  case Intrinsic::x86_sse2_ucomilt_sd:
5033  case Intrinsic::x86_sse2_ucomile_sd:
5034  case Intrinsic::x86_sse2_ucomigt_sd:
5035  case Intrinsic::x86_sse2_ucomige_sd:
5036  case Intrinsic::x86_sse2_ucomineq_sd: {
5037    unsigned Opc = 0;
5038    ISD::CondCode CC = ISD::SETCC_INVALID;
5039    switch (IntNo) {
5040    default: break;
5041    case Intrinsic::x86_sse_comieq_ss:
5042    case Intrinsic::x86_sse2_comieq_sd:
5043      Opc = X86ISD::COMI;
5044      CC = ISD::SETEQ;
5045      break;
5046    case Intrinsic::x86_sse_comilt_ss:
5047    case Intrinsic::x86_sse2_comilt_sd:
5048      Opc = X86ISD::COMI;
5049      CC = ISD::SETLT;
5050      break;
5051    case Intrinsic::x86_sse_comile_ss:
5052    case Intrinsic::x86_sse2_comile_sd:
5053      Opc = X86ISD::COMI;
5054      CC = ISD::SETLE;
5055      break;
5056    case Intrinsic::x86_sse_comigt_ss:
5057    case Intrinsic::x86_sse2_comigt_sd:
5058      Opc = X86ISD::COMI;
5059      CC = ISD::SETGT;
5060      break;
5061    case Intrinsic::x86_sse_comige_ss:
5062    case Intrinsic::x86_sse2_comige_sd:
5063      Opc = X86ISD::COMI;
5064      CC = ISD::SETGE;
5065      break;
5066    case Intrinsic::x86_sse_comineq_ss:
5067    case Intrinsic::x86_sse2_comineq_sd:
5068      Opc = X86ISD::COMI;
5069      CC = ISD::SETNE;
5070      break;
5071    case Intrinsic::x86_sse_ucomieq_ss:
5072    case Intrinsic::x86_sse2_ucomieq_sd:
5073      Opc = X86ISD::UCOMI;
5074      CC = ISD::SETEQ;
5075      break;
5076    case Intrinsic::x86_sse_ucomilt_ss:
5077    case Intrinsic::x86_sse2_ucomilt_sd:
5078      Opc = X86ISD::UCOMI;
5079      CC = ISD::SETLT;
5080      break;
5081    case Intrinsic::x86_sse_ucomile_ss:
5082    case Intrinsic::x86_sse2_ucomile_sd:
5083      Opc = X86ISD::UCOMI;
5084      CC = ISD::SETLE;
5085      break;
5086    case Intrinsic::x86_sse_ucomigt_ss:
5087    case Intrinsic::x86_sse2_ucomigt_sd:
5088      Opc = X86ISD::UCOMI;
5089      CC = ISD::SETGT;
5090      break;
5091    case Intrinsic::x86_sse_ucomige_ss:
5092    case Intrinsic::x86_sse2_ucomige_sd:
5093      Opc = X86ISD::UCOMI;
5094      CC = ISD::SETGE;
5095      break;
5096    case Intrinsic::x86_sse_ucomineq_ss:
5097    case Intrinsic::x86_sse2_ucomineq_sd:
5098      Opc = X86ISD::UCOMI;
5099      CC = ISD::SETNE;
5100      break;
5101    }
5102
5103    unsigned X86CC;
5104    SDOperand LHS = Op.getOperand(1);
5105    SDOperand RHS = Op.getOperand(2);
5106    translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5107
5108    SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5109    SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5110                                  DAG.getConstant(X86CC, MVT::i8), Cond);
5111    return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5112  }
5113  }
5114}
5115
5116SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5117  // Depths > 0 not supported yet!
5118  if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5119    return SDOperand();
5120
5121  // Just load the return address
5122  SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5123  return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5124}
5125
5126SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5127  // Depths > 0 not supported yet!
5128  if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5129    return SDOperand();
5130
5131  SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5132  return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5133                     DAG.getIntPtrConstant(4));
5134}
5135
5136SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5137                                                       SelectionDAG &DAG) {
5138  // Is not yet supported on x86-64
5139  if (Subtarget->is64Bit())
5140    return SDOperand();
5141
5142  return DAG.getIntPtrConstant(8);
5143}
5144
5145SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5146{
5147  assert(!Subtarget->is64Bit() &&
5148         "Lowering of eh_return builtin is not supported yet on x86-64");
5149
5150  MachineFunction &MF = DAG.getMachineFunction();
5151  SDOperand Chain     = Op.getOperand(0);
5152  SDOperand Offset    = Op.getOperand(1);
5153  SDOperand Handler   = Op.getOperand(2);
5154
5155  SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5156                                    getPointerTy());
5157
5158  SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5159                                    DAG.getIntPtrConstant(-4UL));
5160  StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5161  Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5162  Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5163  MF.getRegInfo().addLiveOut(X86::ECX);
5164
5165  return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5166                     Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5167}
5168
5169SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5170                                             SelectionDAG &DAG) {
5171  SDOperand Root = Op.getOperand(0);
5172  SDOperand Trmp = Op.getOperand(1); // trampoline
5173  SDOperand FPtr = Op.getOperand(2); // nested function
5174  SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5175
5176  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5177
5178  const X86InstrInfo *TII =
5179    ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5180
5181  if (Subtarget->is64Bit()) {
5182    SDOperand OutChains[6];
5183
5184    // Large code-model.
5185
5186    const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5187    const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5188
5189    const unsigned char N86R10 =
5190      ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5191    const unsigned char N86R11 =
5192      ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5193
5194    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5195
5196    // Load the pointer to the nested function into R11.
5197    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5198    SDOperand Addr = Trmp;
5199    OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5200                                TrmpAddr, 0);
5201
5202    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5203    OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5204
5205    // Load the 'nest' parameter value into R10.
5206    // R10 is specified in X86CallingConv.td
5207    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5208    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5209    OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5210                                TrmpAddr, 10);
5211
5212    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5213    OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5214
5215    // Jump to the nested function.
5216    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5217    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5218    OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5219                                TrmpAddr, 20);
5220
5221    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5222    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5223    OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5224                                TrmpAddr, 22);
5225
5226    SDOperand Ops[] =
5227      { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5228    return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5229  } else {
5230    const Function *Func =
5231      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5232    unsigned CC = Func->getCallingConv();
5233    unsigned NestReg;
5234
5235    switch (CC) {
5236    default:
5237      assert(0 && "Unsupported calling convention");
5238    case CallingConv::C:
5239    case CallingConv::X86_StdCall: {
5240      // Pass 'nest' parameter in ECX.
5241      // Must be kept in sync with X86CallingConv.td
5242      NestReg = X86::ECX;
5243
5244      // Check that ECX wasn't needed by an 'inreg' parameter.
5245      const FunctionType *FTy = Func->getFunctionType();
5246      const ParamAttrsList *Attrs = Func->getParamAttrs();
5247
5248      if (Attrs && !Func->isVarArg()) {
5249        unsigned InRegCount = 0;
5250        unsigned Idx = 1;
5251
5252        for (FunctionType::param_iterator I = FTy->param_begin(),
5253             E = FTy->param_end(); I != E; ++I, ++Idx)
5254          if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5255            // FIXME: should only count parameters that are lowered to integers.
5256            InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5257
5258        if (InRegCount > 2) {
5259          cerr << "Nest register in use - reduce number of inreg parameters!\n";
5260          abort();
5261        }
5262      }
5263      break;
5264    }
5265    case CallingConv::X86_FastCall:
5266      // Pass 'nest' parameter in EAX.
5267      // Must be kept in sync with X86CallingConv.td
5268      NestReg = X86::EAX;
5269      break;
5270    }
5271
5272    SDOperand OutChains[4];
5273    SDOperand Addr, Disp;
5274
5275    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5276    Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5277
5278    const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5279    const unsigned char N86Reg =
5280      ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5281    OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5282                                Trmp, TrmpAddr, 0);
5283
5284    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5285    OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5286
5287    const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5288    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5289    OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5290                                TrmpAddr, 5, false, 1);
5291
5292    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5293    OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5294
5295    SDOperand Ops[] =
5296      { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5297    return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5298  }
5299}
5300
5301SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5302  /*
5303   The rounding mode is in bits 11:10 of FPSR, and has the following
5304   settings:
5305     00 Round to nearest
5306     01 Round to -inf
5307     10 Round to +inf
5308     11 Round to 0
5309
5310  FLT_ROUNDS, on the other hand, expects the following:
5311    -1 Undefined
5312     0 Round to 0
5313     1 Round to nearest
5314     2 Round to +inf
5315     3 Round to -inf
5316
5317  To perform the conversion, we do:
5318    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5319  */
5320
5321  MachineFunction &MF = DAG.getMachineFunction();
5322  const TargetMachine &TM = MF.getTarget();
5323  const TargetFrameInfo &TFI = *TM.getFrameInfo();
5324  unsigned StackAlignment = TFI.getStackAlignment();
5325  MVT::ValueType VT = Op.getValueType();
5326
5327  // Save FP Control Word to stack slot
5328  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5329  SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5330
5331  SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5332                                DAG.getEntryNode(), StackSlot);
5333
5334  // Load FP Control Word from stack slot
5335  SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5336
5337  // Transform as necessary
5338  SDOperand CWD1 =
5339    DAG.getNode(ISD::SRL, MVT::i16,
5340                DAG.getNode(ISD::AND, MVT::i16,
5341                            CWD, DAG.getConstant(0x800, MVT::i16)),
5342                DAG.getConstant(11, MVT::i8));
5343  SDOperand CWD2 =
5344    DAG.getNode(ISD::SRL, MVT::i16,
5345                DAG.getNode(ISD::AND, MVT::i16,
5346                            CWD, DAG.getConstant(0x400, MVT::i16)),
5347                DAG.getConstant(9, MVT::i8));
5348
5349  SDOperand RetVal =
5350    DAG.getNode(ISD::AND, MVT::i16,
5351                DAG.getNode(ISD::ADD, MVT::i16,
5352                            DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5353                            DAG.getConstant(1, MVT::i16)),
5354                DAG.getConstant(3, MVT::i16));
5355
5356
5357  return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5358                      ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5359}
5360
5361SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5362  MVT::ValueType VT = Op.getValueType();
5363  MVT::ValueType OpVT = VT;
5364  unsigned NumBits = MVT::getSizeInBits(VT);
5365
5366  Op = Op.getOperand(0);
5367  if (VT == MVT::i8) {
5368    // Zero extend to i32 since there is not an i8 bsr.
5369    OpVT = MVT::i32;
5370    Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5371  }
5372
5373  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5374  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5375  Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5376
5377  // If src is zero (i.e. bsr sets ZF), returns NumBits.
5378  SmallVector<SDOperand, 4> Ops;
5379  Ops.push_back(Op);
5380  Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5381  Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5382  Ops.push_back(Op.getValue(1));
5383  Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5384
5385  // Finally xor with NumBits-1.
5386  Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5387
5388  if (VT == MVT::i8)
5389    Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5390  return Op;
5391}
5392
5393SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5394  MVT::ValueType VT = Op.getValueType();
5395  MVT::ValueType OpVT = VT;
5396  unsigned NumBits = MVT::getSizeInBits(VT);
5397
5398  Op = Op.getOperand(0);
5399  if (VT == MVT::i8) {
5400    OpVT = MVT::i32;
5401    Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5402  }
5403
5404  // Issue a bsf (scan bits forward) which also sets EFLAGS.
5405  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5406  Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5407
5408  // If src is zero (i.e. bsf sets ZF), returns NumBits.
5409  SmallVector<SDOperand, 4> Ops;
5410  Ops.push_back(Op);
5411  Ops.push_back(DAG.getConstant(NumBits, OpVT));
5412  Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5413  Ops.push_back(Op.getValue(1));
5414  Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5415
5416  if (VT == MVT::i8)
5417    Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5418  return Op;
5419}
5420
5421SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5422  MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5423  unsigned Reg = 0;
5424  unsigned size = 0;
5425  switch(T) {
5426  case MVT::i8:  Reg = X86::AL;  size = 1; break;
5427  case MVT::i16: Reg = X86::AX;  size = 2; break;
5428  case MVT::i32: Reg = X86::EAX; size = 4; break;
5429  case MVT::i64:
5430    if (Subtarget->is64Bit()) {
5431      Reg = X86::RAX; size = 8;
5432    } else //Should go away when LowerType stuff lands
5433      return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5434    break;
5435  };
5436  SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5437                                    Op.getOperand(3), SDOperand());
5438  SDOperand Ops[] = { cpIn.getValue(0),
5439                      Op.getOperand(1),
5440                      Op.getOperand(2),
5441                      DAG.getTargetConstant(size, MVT::i8),
5442                      cpIn.getValue(1) };
5443  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5444  SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5445  SDOperand cpOut =
5446    DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5447  return cpOut;
5448}
5449
5450SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5451  MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5452  assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5453  SDOperand cpInL, cpInH;
5454  cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5455                      DAG.getConstant(0, MVT::i32));
5456  cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5457                      DAG.getConstant(1, MVT::i32));
5458  cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5459                           cpInL, SDOperand());
5460  cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5461                           cpInH, cpInL.getValue(1));
5462  SDOperand swapInL, swapInH;
5463  swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5464                        DAG.getConstant(0, MVT::i32));
5465  swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5466                        DAG.getConstant(1, MVT::i32));
5467  swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5468                             swapInL, cpInH.getValue(1));
5469  swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5470                             swapInH, swapInL.getValue(1));
5471  SDOperand Ops[] = { swapInH.getValue(0),
5472                      Op->getOperand(1),
5473                      swapInH.getValue(1)};
5474  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5475  SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5476  SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5477                                        Result.getValue(1));
5478  SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5479                                        cpOutL.getValue(2));
5480  SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5481  SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5482  Tys = DAG.getVTList(MVT::i64, MVT::Other);
5483  return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5484}
5485
5486/// LowerOperation - Provide custom lowering hooks for some operations.
5487///
5488SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5489  switch (Op.getOpcode()) {
5490  default: assert(0 && "Should not custom lower this!");
5491  case ISD::ATOMIC_LCS:         return LowerLCS(Op,DAG);
5492  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5493  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5494  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5495  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5496  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5497  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5498  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5499  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5500  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5501  case ISD::SHL_PARTS:
5502  case ISD::SRA_PARTS:
5503  case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5504  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5505  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5506  case ISD::FABS:               return LowerFABS(Op, DAG);
5507  case ISD::FNEG:               return LowerFNEG(Op, DAG);
5508  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5509  case ISD::SETCC:              return LowerSETCC(Op, DAG);
5510  case ISD::SELECT:             return LowerSELECT(Op, DAG);
5511  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5512  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5513  case ISD::CALL:               return LowerCALL(Op, DAG);
5514  case ISD::RET:                return LowerRET(Op, DAG);
5515  case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5516  case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
5517  case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
5518  case ISD::VASTART:            return LowerVASTART(Op, DAG);
5519  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5520  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5521  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5522  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5523  case ISD::FRAME_TO_ARGS_OFFSET:
5524                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5525  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5526  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5527  case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5528  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5529  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
5530  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
5531
5532  // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5533  case ISD::READCYCLECOUNTER:
5534    return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5535  }
5536}
5537
5538/// ExpandOperation - Provide custom lowering hooks for expanding operations.
5539SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5540  switch (N->getOpcode()) {
5541  default: assert(0 && "Should not custom lower this!");
5542  case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5543  case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5544  case ISD::ATOMIC_LCS:         return ExpandATOMIC_LCS(N, DAG);
5545  }
5546}
5547
5548const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5549  switch (Opcode) {
5550  default: return NULL;
5551  case X86ISD::BSF:                return "X86ISD::BSF";
5552  case X86ISD::BSR:                return "X86ISD::BSR";
5553  case X86ISD::SHLD:               return "X86ISD::SHLD";
5554  case X86ISD::SHRD:               return "X86ISD::SHRD";
5555  case X86ISD::FAND:               return "X86ISD::FAND";
5556  case X86ISD::FOR:                return "X86ISD::FOR";
5557  case X86ISD::FXOR:               return "X86ISD::FXOR";
5558  case X86ISD::FSRL:               return "X86ISD::FSRL";
5559  case X86ISD::FILD:               return "X86ISD::FILD";
5560  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5561  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5562  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5563  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5564  case X86ISD::FLD:                return "X86ISD::FLD";
5565  case X86ISD::FST:                return "X86ISD::FST";
5566  case X86ISD::FP_GET_ST0:         return "X86ISD::FP_GET_ST0";
5567  case X86ISD::FP_GET_ST0_ST1:     return "X86ISD::FP_GET_ST0_ST1";
5568  case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
5569  case X86ISD::CALL:               return "X86ISD::CALL";
5570  case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5571  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5572  case X86ISD::CMP:                return "X86ISD::CMP";
5573  case X86ISD::COMI:               return "X86ISD::COMI";
5574  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5575  case X86ISD::SETCC:              return "X86ISD::SETCC";
5576  case X86ISD::CMOV:               return "X86ISD::CMOV";
5577  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5578  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5579  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5580  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5581  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5582  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5583  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
5584  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5585  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
5586  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
5587  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5588  case X86ISD::FMAX:               return "X86ISD::FMAX";
5589  case X86ISD::FMIN:               return "X86ISD::FMIN";
5590  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
5591  case X86ISD::FRCP:               return "X86ISD::FRCP";
5592  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
5593  case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
5594  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
5595  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
5596  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
5597  case X86ISD::LCMPXCHG_DAG:       return "x86ISD::LCMPXCHG_DAG";
5598  case X86ISD::LCMPXCHG8_DAG:      return "x86ISD::LCMPXCHG8_DAG";
5599  }
5600}
5601
5602// isLegalAddressingMode - Return true if the addressing mode represented
5603// by AM is legal for this target, for a load/store of the specified type.
5604bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5605                                              const Type *Ty) const {
5606  // X86 supports extremely general addressing modes.
5607
5608  // X86 allows a sign-extended 32-bit immediate field as a displacement.
5609  if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5610    return false;
5611
5612  if (AM.BaseGV) {
5613    // We can only fold this if we don't need an extra load.
5614    if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5615      return false;
5616
5617    // X86-64 only supports addr of globals in small code model.
5618    if (Subtarget->is64Bit()) {
5619      if (getTargetMachine().getCodeModel() != CodeModel::Small)
5620        return false;
5621      // If lower 4G is not available, then we must use rip-relative addressing.
5622      if (AM.BaseOffs || AM.Scale > 1)
5623        return false;
5624    }
5625  }
5626
5627  switch (AM.Scale) {
5628  case 0:
5629  case 1:
5630  case 2:
5631  case 4:
5632  case 8:
5633    // These scales always work.
5634    break;
5635  case 3:
5636  case 5:
5637  case 9:
5638    // These scales are formed with basereg+scalereg.  Only accept if there is
5639    // no basereg yet.
5640    if (AM.HasBaseReg)
5641      return false;
5642    break;
5643  default:  // Other stuff never works.
5644    return false;
5645  }
5646
5647  return true;
5648}
5649
5650
5651bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5652  if (!Ty1->isInteger() || !Ty2->isInteger())
5653    return false;
5654  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5655  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5656  if (NumBits1 <= NumBits2)
5657    return false;
5658  return Subtarget->is64Bit() || NumBits1 < 64;
5659}
5660
5661bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5662                                       MVT::ValueType VT2) const {
5663  if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5664    return false;
5665  unsigned NumBits1 = MVT::getSizeInBits(VT1);
5666  unsigned NumBits2 = MVT::getSizeInBits(VT2);
5667  if (NumBits1 <= NumBits2)
5668    return false;
5669  return Subtarget->is64Bit() || NumBits1 < 64;
5670}
5671
5672/// isShuffleMaskLegal - Targets can use this to indicate that they only
5673/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5674/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5675/// are assumed to be legal.
5676bool
5677X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5678  // Only do shuffles on 128-bit vector types for now.
5679  if (MVT::getSizeInBits(VT) == 64) return false;
5680  return (Mask.Val->getNumOperands() <= 4 ||
5681          isIdentityMask(Mask.Val) ||
5682          isIdentityMask(Mask.Val, true) ||
5683          isSplatMask(Mask.Val)  ||
5684          isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5685          X86::isUNPCKLMask(Mask.Val) ||
5686          X86::isUNPCKHMask(Mask.Val) ||
5687          X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5688          X86::isUNPCKH_v_undef_Mask(Mask.Val));
5689}
5690
5691bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5692                                               MVT::ValueType EVT,
5693                                               SelectionDAG &DAG) const {
5694  unsigned NumElts = BVOps.size();
5695  // Only do shuffles on 128-bit vector types for now.
5696  if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5697  if (NumElts == 2) return true;
5698  if (NumElts == 4) {
5699    return (isMOVLMask(&BVOps[0], 4)  ||
5700            isCommutedMOVL(&BVOps[0], 4, true) ||
5701            isSHUFPMask(&BVOps[0], 4) ||
5702            isCommutedSHUFP(&BVOps[0], 4));
5703  }
5704  return false;
5705}
5706
5707//===----------------------------------------------------------------------===//
5708//                           X86 Scheduler Hooks
5709//===----------------------------------------------------------------------===//
5710
5711MachineBasicBlock *
5712X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5713                                               MachineBasicBlock *BB) {
5714  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5715  switch (MI->getOpcode()) {
5716  default: assert(false && "Unexpected instr type to insert");
5717  case X86::CMOV_FR32:
5718  case X86::CMOV_FR64:
5719  case X86::CMOV_V4F32:
5720  case X86::CMOV_V2F64:
5721  case X86::CMOV_V2I64: {
5722    // To "insert" a SELECT_CC instruction, we actually have to insert the
5723    // diamond control-flow pattern.  The incoming instruction knows the
5724    // destination vreg to set, the condition code register to branch on, the
5725    // true/false values to select between, and a branch opcode to use.
5726    const BasicBlock *LLVM_BB = BB->getBasicBlock();
5727    ilist<MachineBasicBlock>::iterator It = BB;
5728    ++It;
5729
5730    //  thisMBB:
5731    //  ...
5732    //   TrueVal = ...
5733    //   cmpTY ccX, r1, r2
5734    //   bCC copy1MBB
5735    //   fallthrough --> copy0MBB
5736    MachineBasicBlock *thisMBB = BB;
5737    MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5738    MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5739    unsigned Opc =
5740      X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5741    BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5742    MachineFunction *F = BB->getParent();
5743    F->getBasicBlockList().insert(It, copy0MBB);
5744    F->getBasicBlockList().insert(It, sinkMBB);
5745    // Update machine-CFG edges by first adding all successors of the current
5746    // block to the new block which will contain the Phi node for the select.
5747    for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5748        e = BB->succ_end(); i != e; ++i)
5749      sinkMBB->addSuccessor(*i);
5750    // Next, remove all successors of the current block, and add the true
5751    // and fallthrough blocks as its successors.
5752    while(!BB->succ_empty())
5753      BB->removeSuccessor(BB->succ_begin());
5754    BB->addSuccessor(copy0MBB);
5755    BB->addSuccessor(sinkMBB);
5756
5757    //  copy0MBB:
5758    //   %FalseValue = ...
5759    //   # fallthrough to sinkMBB
5760    BB = copy0MBB;
5761
5762    // Update machine-CFG edges
5763    BB->addSuccessor(sinkMBB);
5764
5765    //  sinkMBB:
5766    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5767    //  ...
5768    BB = sinkMBB;
5769    BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5770      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5771      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5772
5773    delete MI;   // The pseudo instruction is gone now.
5774    return BB;
5775  }
5776
5777  case X86::FP32_TO_INT16_IN_MEM:
5778  case X86::FP32_TO_INT32_IN_MEM:
5779  case X86::FP32_TO_INT64_IN_MEM:
5780  case X86::FP64_TO_INT16_IN_MEM:
5781  case X86::FP64_TO_INT32_IN_MEM:
5782  case X86::FP64_TO_INT64_IN_MEM:
5783  case X86::FP80_TO_INT16_IN_MEM:
5784  case X86::FP80_TO_INT32_IN_MEM:
5785  case X86::FP80_TO_INT64_IN_MEM: {
5786    // Change the floating point control register to use "round towards zero"
5787    // mode when truncating to an integer value.
5788    MachineFunction *F = BB->getParent();
5789    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5790    addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5791
5792    // Load the old value of the high byte of the control word...
5793    unsigned OldCW =
5794      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5795    addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5796
5797    // Set the high part to be round to zero...
5798    addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5799      .addImm(0xC7F);
5800
5801    // Reload the modified control word now...
5802    addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5803
5804    // Restore the memory image of control word to original value
5805    addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5806      .addReg(OldCW);
5807
5808    // Get the X86 opcode to use.
5809    unsigned Opc;
5810    switch (MI->getOpcode()) {
5811    default: assert(0 && "illegal opcode!");
5812    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5813    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5814    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5815    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5816    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5817    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5818    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5819    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5820    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5821    }
5822
5823    X86AddressMode AM;
5824    MachineOperand &Op = MI->getOperand(0);
5825    if (Op.isRegister()) {
5826      AM.BaseType = X86AddressMode::RegBase;
5827      AM.Base.Reg = Op.getReg();
5828    } else {
5829      AM.BaseType = X86AddressMode::FrameIndexBase;
5830      AM.Base.FrameIndex = Op.getIndex();
5831    }
5832    Op = MI->getOperand(1);
5833    if (Op.isImmediate())
5834      AM.Scale = Op.getImm();
5835    Op = MI->getOperand(2);
5836    if (Op.isImmediate())
5837      AM.IndexReg = Op.getImm();
5838    Op = MI->getOperand(3);
5839    if (Op.isGlobalAddress()) {
5840      AM.GV = Op.getGlobal();
5841    } else {
5842      AM.Disp = Op.getImm();
5843    }
5844    addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5845                      .addReg(MI->getOperand(4).getReg());
5846
5847    // Reload the original control word now.
5848    addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5849
5850    delete MI;   // The pseudo instruction is gone now.
5851    return BB;
5852  }
5853  }
5854}
5855
5856//===----------------------------------------------------------------------===//
5857//                           X86 Optimization Hooks
5858//===----------------------------------------------------------------------===//
5859
5860void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5861                                                       const APInt &Mask,
5862                                                       APInt &KnownZero,
5863                                                       APInt &KnownOne,
5864                                                       const SelectionDAG &DAG,
5865                                                       unsigned Depth) const {
5866  unsigned Opc = Op.getOpcode();
5867  assert((Opc >= ISD::BUILTIN_OP_END ||
5868          Opc == ISD::INTRINSIC_WO_CHAIN ||
5869          Opc == ISD::INTRINSIC_W_CHAIN ||
5870          Opc == ISD::INTRINSIC_VOID) &&
5871         "Should use MaskedValueIsZero if you don't know whether Op"
5872         " is a target node!");
5873
5874  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
5875  switch (Opc) {
5876  default: break;
5877  case X86ISD::SETCC:
5878    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5879                                       Mask.getBitWidth() - 1);
5880    break;
5881  }
5882}
5883
5884/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5885/// element of the result of the vector shuffle.
5886static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5887  MVT::ValueType VT = N->getValueType(0);
5888  SDOperand PermMask = N->getOperand(2);
5889  unsigned NumElems = PermMask.getNumOperands();
5890  SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5891  i %= NumElems;
5892  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5893    return (i == 0)
5894     ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5895  } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5896    SDOperand Idx = PermMask.getOperand(i);
5897    if (Idx.getOpcode() == ISD::UNDEF)
5898      return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5899    return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5900  }
5901  return SDOperand();
5902}
5903
5904/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5905/// node is a GlobalAddress + an offset.
5906static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5907  unsigned Opc = N->getOpcode();
5908  if (Opc == X86ISD::Wrapper) {
5909    if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5910      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5911      return true;
5912    }
5913  } else if (Opc == ISD::ADD) {
5914    SDOperand N1 = N->getOperand(0);
5915    SDOperand N2 = N->getOperand(1);
5916    if (isGAPlusOffset(N1.Val, GA, Offset)) {
5917      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5918      if (V) {
5919        Offset += V->getSignExtended();
5920        return true;
5921      }
5922    } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5923      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5924      if (V) {
5925        Offset += V->getSignExtended();
5926        return true;
5927      }
5928    }
5929  }
5930  return false;
5931}
5932
5933/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5934/// + Dist * Size.
5935static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5936                              MachineFrameInfo *MFI) {
5937  if (N->getOperand(0).Val != Base->getOperand(0).Val)
5938    return false;
5939
5940  SDOperand Loc = N->getOperand(1);
5941  SDOperand BaseLoc = Base->getOperand(1);
5942  if (Loc.getOpcode() == ISD::FrameIndex) {
5943    if (BaseLoc.getOpcode() != ISD::FrameIndex)
5944      return false;
5945    int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
5946    int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5947    int FS  = MFI->getObjectSize(FI);
5948    int BFS = MFI->getObjectSize(BFI);
5949    if (FS != BFS || FS != Size) return false;
5950    return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5951  } else {
5952    GlobalValue *GV1 = NULL;
5953    GlobalValue *GV2 = NULL;
5954    int64_t Offset1 = 0;
5955    int64_t Offset2 = 0;
5956    bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5957    bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5958    if (isGA1 && isGA2 && GV1 == GV2)
5959      return Offset1 == (Offset2 + Dist*Size);
5960  }
5961
5962  return false;
5963}
5964
5965static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5966                              const X86Subtarget *Subtarget) {
5967  GlobalValue *GV;
5968  int64_t Offset = 0;
5969  if (isGAPlusOffset(Base, GV, Offset))
5970    return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5971  // DAG combine handles the stack object case.
5972  return false;
5973}
5974
5975
5976/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5977/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5978/// if the load addresses are consecutive, non-overlapping, and in the right
5979/// order.
5980static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5981                                       const X86Subtarget *Subtarget) {
5982  MachineFunction &MF = DAG.getMachineFunction();
5983  MachineFrameInfo *MFI = MF.getFrameInfo();
5984  MVT::ValueType VT = N->getValueType(0);
5985  MVT::ValueType EVT = MVT::getVectorElementType(VT);
5986  SDOperand PermMask = N->getOperand(2);
5987  int NumElems = (int)PermMask.getNumOperands();
5988  SDNode *Base = NULL;
5989  for (int i = 0; i < NumElems; ++i) {
5990    SDOperand Idx = PermMask.getOperand(i);
5991    if (Idx.getOpcode() == ISD::UNDEF) {
5992      if (!Base) return SDOperand();
5993    } else {
5994      SDOperand Arg =
5995        getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5996      if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5997        return SDOperand();
5998      if (!Base)
5999        Base = Arg.Val;
6000      else if (!isConsecutiveLoad(Arg.Val, Base,
6001                                  i, MVT::getSizeInBits(EVT)/8,MFI))
6002        return SDOperand();
6003    }
6004  }
6005
6006  bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
6007  LoadSDNode *LD = cast<LoadSDNode>(Base);
6008  if (isAlign16) {
6009    return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6010                       LD->getSrcValueOffset(), LD->isVolatile());
6011  } else {
6012    return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6013                       LD->getSrcValueOffset(), LD->isVolatile(),
6014                       LD->getAlignment());
6015  }
6016}
6017
6018/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6019static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6020                                      const X86Subtarget *Subtarget) {
6021  SDOperand Cond = N->getOperand(0);
6022
6023  // If we have SSE[12] support, try to form min/max nodes.
6024  if (Subtarget->hasSSE2() &&
6025      (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6026    if (Cond.getOpcode() == ISD::SETCC) {
6027      // Get the LHS/RHS of the select.
6028      SDOperand LHS = N->getOperand(1);
6029      SDOperand RHS = N->getOperand(2);
6030      ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6031
6032      unsigned Opcode = 0;
6033      if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6034        switch (CC) {
6035        default: break;
6036        case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6037        case ISD::SETULE:
6038        case ISD::SETLE:
6039          if (!UnsafeFPMath) break;
6040          // FALL THROUGH.
6041        case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
6042        case ISD::SETLT:
6043          Opcode = X86ISD::FMIN;
6044          break;
6045
6046        case ISD::SETOGT: // (X > Y) ? X : Y -> max
6047        case ISD::SETUGT:
6048        case ISD::SETGT:
6049          if (!UnsafeFPMath) break;
6050          // FALL THROUGH.
6051        case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
6052        case ISD::SETGE:
6053          Opcode = X86ISD::FMAX;
6054          break;
6055        }
6056      } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6057        switch (CC) {
6058        default: break;
6059        case ISD::SETOGT: // (X > Y) ? Y : X -> min
6060        case ISD::SETUGT:
6061        case ISD::SETGT:
6062          if (!UnsafeFPMath) break;
6063          // FALL THROUGH.
6064        case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
6065        case ISD::SETGE:
6066          Opcode = X86ISD::FMIN;
6067          break;
6068
6069        case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
6070        case ISD::SETULE:
6071        case ISD::SETLE:
6072          if (!UnsafeFPMath) break;
6073          // FALL THROUGH.
6074        case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
6075        case ISD::SETLT:
6076          Opcode = X86ISD::FMAX;
6077          break;
6078        }
6079      }
6080
6081      if (Opcode)
6082        return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6083    }
6084
6085  }
6086
6087  return SDOperand();
6088}
6089
6090/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6091static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6092                                     const X86Subtarget *Subtarget) {
6093  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
6094  // the FP state in cases where an emms may be missing.
6095  // A preferable solution to the general problem is to figure out the right
6096  // places to insert EMMS.  This qualifies as a quick hack.
6097  if (MVT::isVector(St->getValue().getValueType()) &&
6098      MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6099      isa<LoadSDNode>(St->getValue()) &&
6100      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6101      St->getChain().hasOneUse() && !St->isVolatile()) {
6102    SDNode* LdVal = St->getValue().Val;
6103    LoadSDNode *Ld = 0;
6104    int TokenFactorIndex = -1;
6105    SmallVector<SDOperand, 8> Ops;
6106    SDNode* ChainVal = St->getChain().Val;
6107    // Must be a store of a load.  We currently handle two cases:  the load
6108    // is a direct child, and it's under an intervening TokenFactor.  It is
6109    // possible to dig deeper under nested TokenFactors.
6110    if (ChainVal == LdVal)
6111      Ld = cast<LoadSDNode>(St->getChain());
6112    else if (St->getValue().hasOneUse() &&
6113             ChainVal->getOpcode() == ISD::TokenFactor) {
6114      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6115        if (ChainVal->getOperand(i).Val == LdVal) {
6116          TokenFactorIndex = i;
6117          Ld = cast<LoadSDNode>(St->getValue());
6118        } else
6119          Ops.push_back(ChainVal->getOperand(i));
6120      }
6121    }
6122    if (Ld) {
6123      // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6124      if (Subtarget->is64Bit()) {
6125        SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6126                                      Ld->getBasePtr(), Ld->getSrcValue(),
6127                                      Ld->getSrcValueOffset(), Ld->isVolatile(),
6128                                      Ld->getAlignment());
6129        SDOperand NewChain = NewLd.getValue(1);
6130        if (TokenFactorIndex != -1) {
6131          Ops.push_back(NewLd);
6132          NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6133                                 Ops.size());
6134        }
6135        return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6136                            St->getSrcValue(), St->getSrcValueOffset(),
6137                            St->isVolatile(), St->getAlignment());
6138      }
6139
6140      // Otherwise, lower to two 32-bit copies.
6141      SDOperand LoAddr = Ld->getBasePtr();
6142      SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6143                                     DAG.getConstant(MVT::i32, 4));
6144
6145      SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6146                                   Ld->getSrcValue(), Ld->getSrcValueOffset(),
6147                                   Ld->isVolatile(), Ld->getAlignment());
6148      SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6149                                   Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6150                                   Ld->isVolatile(),
6151                                   MinAlign(Ld->getAlignment(), 4));
6152
6153      SDOperand NewChain = LoLd.getValue(1);
6154      if (TokenFactorIndex != -1) {
6155        Ops.push_back(LoLd);
6156        Ops.push_back(HiLd);
6157        NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6158                               Ops.size());
6159      }
6160
6161      LoAddr = St->getBasePtr();
6162      HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6163                           DAG.getConstant(MVT::i32, 4));
6164
6165      SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6166                          St->getSrcValue(), St->getSrcValueOffset(),
6167                          St->isVolatile(), St->getAlignment());
6168      SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6169                                    St->getSrcValue(), St->getSrcValueOffset()+4,
6170                                    St->isVolatile(),
6171                                    MinAlign(St->getAlignment(), 4));
6172      return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6173    }
6174  }
6175  return SDOperand();
6176}
6177
6178/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6179/// X86ISD::FXOR nodes.
6180static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6181  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6182  // F[X]OR(0.0, x) -> x
6183  // F[X]OR(x, 0.0) -> x
6184  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6185    if (C->getValueAPF().isPosZero())
6186      return N->getOperand(1);
6187  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6188    if (C->getValueAPF().isPosZero())
6189      return N->getOperand(0);
6190  return SDOperand();
6191}
6192
6193/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6194static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6195  // FAND(0.0, x) -> 0.0
6196  // FAND(x, 0.0) -> 0.0
6197  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6198    if (C->getValueAPF().isPosZero())
6199      return N->getOperand(0);
6200  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6201    if (C->getValueAPF().isPosZero())
6202      return N->getOperand(1);
6203  return SDOperand();
6204}
6205
6206
6207SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6208                                               DAGCombinerInfo &DCI) const {
6209  SelectionDAG &DAG = DCI.DAG;
6210  switch (N->getOpcode()) {
6211  default: break;
6212  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6213  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
6214  case ISD::STORE:
6215      return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6216  case X86ISD::FXOR:
6217  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
6218  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
6219  }
6220
6221  return SDOperand();
6222}
6223
6224//===----------------------------------------------------------------------===//
6225//                           X86 Inline Assembly Support
6226//===----------------------------------------------------------------------===//
6227
6228/// getConstraintType - Given a constraint letter, return the type of
6229/// constraint it is for this target.
6230X86TargetLowering::ConstraintType
6231X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6232  if (Constraint.size() == 1) {
6233    switch (Constraint[0]) {
6234    case 'A':
6235    case 'r':
6236    case 'R':
6237    case 'l':
6238    case 'q':
6239    case 'Q':
6240    case 'x':
6241    case 'Y':
6242      return C_RegisterClass;
6243    default:
6244      break;
6245    }
6246  }
6247  return TargetLowering::getConstraintType(Constraint);
6248}
6249
6250/// LowerXConstraint - try to replace an X constraint, which matches anything,
6251/// with another that has more specific requirements based on the type of the
6252/// corresponding operand.
6253void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6254                                         std::string& s) const {
6255  if (MVT::isFloatingPoint(ConstraintVT)) {
6256    if (Subtarget->hasSSE2())
6257      s = "Y";
6258    else if (Subtarget->hasSSE1())
6259      s = "x";
6260    else
6261      s = "f";
6262  } else
6263    return TargetLowering::lowerXConstraint(ConstraintVT, s);
6264}
6265
6266/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6267/// vector.  If it is invalid, don't add anything to Ops.
6268void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6269                                                     char Constraint,
6270                                                     std::vector<SDOperand>&Ops,
6271                                                     SelectionDAG &DAG) {
6272  SDOperand Result(0, 0);
6273
6274  switch (Constraint) {
6275  default: break;
6276  case 'I':
6277    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6278      if (C->getValue() <= 31) {
6279        Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6280        break;
6281      }
6282    }
6283    return;
6284  case 'N':
6285    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6286      if (C->getValue() <= 255) {
6287        Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6288        break;
6289      }
6290    }
6291    return;
6292  case 'i': {
6293    // Literal immediates are always ok.
6294    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6295      Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6296      break;
6297    }
6298
6299    // If we are in non-pic codegen mode, we allow the address of a global (with
6300    // an optional displacement) to be used with 'i'.
6301    GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6302    int64_t Offset = 0;
6303
6304    // Match either (GA) or (GA+C)
6305    if (GA) {
6306      Offset = GA->getOffset();
6307    } else if (Op.getOpcode() == ISD::ADD) {
6308      ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6309      GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6310      if (C && GA) {
6311        Offset = GA->getOffset()+C->getValue();
6312      } else {
6313        C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6314        GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6315        if (C && GA)
6316          Offset = GA->getOffset()+C->getValue();
6317        else
6318          C = 0, GA = 0;
6319      }
6320    }
6321
6322    if (GA) {
6323      // If addressing this global requires a load (e.g. in PIC mode), we can't
6324      // match.
6325      if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6326                                         false))
6327        return;
6328
6329      Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6330                                      Offset);
6331      Result = Op;
6332      break;
6333    }
6334
6335    // Otherwise, not valid for this mode.
6336    return;
6337  }
6338  }
6339
6340  if (Result.Val) {
6341    Ops.push_back(Result);
6342    return;
6343  }
6344  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6345}
6346
6347std::vector<unsigned> X86TargetLowering::
6348getRegClassForInlineAsmConstraint(const std::string &Constraint,
6349                                  MVT::ValueType VT) const {
6350  if (Constraint.size() == 1) {
6351    // FIXME: not handling fp-stack yet!
6352    switch (Constraint[0]) {      // GCC X86 Constraint Letters
6353    default: break;  // Unknown constraint letter
6354    case 'A':   // EAX/EDX
6355      if (VT == MVT::i32 || VT == MVT::i64)
6356        return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6357      break;
6358    case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
6359    case 'Q':   // Q_REGS
6360      if (VT == MVT::i32)
6361        return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6362      else if (VT == MVT::i16)
6363        return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6364      else if (VT == MVT::i8)
6365        return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6366      else if (VT == MVT::i64)
6367        return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6368      break;
6369    }
6370  }
6371
6372  return std::vector<unsigned>();
6373}
6374
6375std::pair<unsigned, const TargetRegisterClass*>
6376X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6377                                                MVT::ValueType VT) const {
6378  // First, see if this is a constraint that directly corresponds to an LLVM
6379  // register class.
6380  if (Constraint.size() == 1) {
6381    // GCC Constraint Letters
6382    switch (Constraint[0]) {
6383    default: break;
6384    case 'r':   // GENERAL_REGS
6385    case 'R':   // LEGACY_REGS
6386    case 'l':   // INDEX_REGS
6387      if (VT == MVT::i64 && Subtarget->is64Bit())
6388        return std::make_pair(0U, X86::GR64RegisterClass);
6389      if (VT == MVT::i32)
6390        return std::make_pair(0U, X86::GR32RegisterClass);
6391      else if (VT == MVT::i16)
6392        return std::make_pair(0U, X86::GR16RegisterClass);
6393      else if (VT == MVT::i8)
6394        return std::make_pair(0U, X86::GR8RegisterClass);
6395      break;
6396    case 'y':   // MMX_REGS if MMX allowed.
6397      if (!Subtarget->hasMMX()) break;
6398      return std::make_pair(0U, X86::VR64RegisterClass);
6399      break;
6400    case 'Y':   // SSE_REGS if SSE2 allowed
6401      if (!Subtarget->hasSSE2()) break;
6402      // FALL THROUGH.
6403    case 'x':   // SSE_REGS if SSE1 allowed
6404      if (!Subtarget->hasSSE1()) break;
6405
6406      switch (VT) {
6407      default: break;
6408      // Scalar SSE types.
6409      case MVT::f32:
6410      case MVT::i32:
6411        return std::make_pair(0U, X86::FR32RegisterClass);
6412      case MVT::f64:
6413      case MVT::i64:
6414        return std::make_pair(0U, X86::FR64RegisterClass);
6415      // Vector types.
6416      case MVT::v16i8:
6417      case MVT::v8i16:
6418      case MVT::v4i32:
6419      case MVT::v2i64:
6420      case MVT::v4f32:
6421      case MVT::v2f64:
6422        return std::make_pair(0U, X86::VR128RegisterClass);
6423      }
6424      break;
6425    }
6426  }
6427
6428  // Use the default implementation in TargetLowering to convert the register
6429  // constraint into a member of a register class.
6430  std::pair<unsigned, const TargetRegisterClass*> Res;
6431  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6432
6433  // Not found as a standard register?
6434  if (Res.second == 0) {
6435    // GCC calls "st(0)" just plain "st".
6436    if (StringsEqualNoCase("{st}", Constraint)) {
6437      Res.first = X86::ST0;
6438      Res.second = X86::RFP80RegisterClass;
6439    }
6440
6441    return Res;
6442  }
6443
6444  // Otherwise, check to see if this is a register class of the wrong value
6445  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6446  // turn into {ax},{dx}.
6447  if (Res.second->hasType(VT))
6448    return Res;   // Correct type already, nothing to do.
6449
6450  // All of the single-register GCC register classes map their values onto
6451  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
6452  // really want an 8-bit or 32-bit register, map to the appropriate register
6453  // class and return the appropriate register.
6454  if (Res.second != X86::GR16RegisterClass)
6455    return Res;
6456
6457  if (VT == MVT::i8) {
6458    unsigned DestReg = 0;
6459    switch (Res.first) {
6460    default: break;
6461    case X86::AX: DestReg = X86::AL; break;
6462    case X86::DX: DestReg = X86::DL; break;
6463    case X86::CX: DestReg = X86::CL; break;
6464    case X86::BX: DestReg = X86::BL; break;
6465    }
6466    if (DestReg) {
6467      Res.first = DestReg;
6468      Res.second = Res.second = X86::GR8RegisterClass;
6469    }
6470  } else if (VT == MVT::i32) {
6471    unsigned DestReg = 0;
6472    switch (Res.first) {
6473    default: break;
6474    case X86::AX: DestReg = X86::EAX; break;
6475    case X86::DX: DestReg = X86::EDX; break;
6476    case X86::CX: DestReg = X86::ECX; break;
6477    case X86::BX: DestReg = X86::EBX; break;
6478    case X86::SI: DestReg = X86::ESI; break;
6479    case X86::DI: DestReg = X86::EDI; break;
6480    case X86::BP: DestReg = X86::EBP; break;
6481    case X86::SP: DestReg = X86::ESP; break;
6482    }
6483    if (DestReg) {
6484      Res.first = DestReg;
6485      Res.second = Res.second = X86::GR32RegisterClass;
6486    }
6487  } else if (VT == MVT::i64) {
6488    unsigned DestReg = 0;
6489    switch (Res.first) {
6490    default: break;
6491    case X86::AX: DestReg = X86::RAX; break;
6492    case X86::DX: DestReg = X86::RDX; break;
6493    case X86::CX: DestReg = X86::RCX; break;
6494    case X86::BX: DestReg = X86::RBX; break;
6495    case X86::SI: DestReg = X86::RSI; break;
6496    case X86::DI: DestReg = X86::RDI; break;
6497    case X86::BP: DestReg = X86::RBP; break;
6498    case X86::SP: DestReg = X86::RSP; break;
6499    }
6500    if (DestReg) {
6501      Res.first = DestReg;
6502      Res.second = Res.second = X86::GR64RegisterClass;
6503    }
6504  }
6505
6506  return Res;
6507}
6508