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