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