X86ISelLowering.cpp revision a6b20ced765b67a85d9219d0c8547fc9c133e14f
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#define DEBUG_TYPE "x86-isel"
16#include "X86ISelLowering.h"
17#include "Utils/X86ShuffleDecode.h"
18#include "X86.h"
19#include "X86InstrBuilder.h"
20#include "X86TargetMachine.h"
21#include "X86TargetObjectFile.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/VariadicFunction.h"
26#include "llvm/CodeGen/IntrinsicLowering.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineJumpTableInfo.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/IR/CallingConv.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/MC/MCAsmInfo.h"
43#include "llvm/MC/MCContext.h"
44#include "llvm/MC/MCExpr.h"
45#include "llvm/MC/MCSymbol.h"
46#include "llvm/Support/CallSite.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/Target/TargetOptions.h"
51#include <bitset>
52#include <cctype>
53using namespace llvm;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56
57// Forward declarations.
58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                       SDValue V2);
60
61/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62/// sets things up to match to an AVX VEXTRACTF128 instruction or a
63/// simple subregister reference.  Idx is an index in the 128 bits we
64/// want.  It need not be aligned to a 128-bit bounday.  That makes
65/// lowering EXTRACT_VECTOR_ELT operations easier.
66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                   SelectionDAG &DAG, DebugLoc dl) {
68  EVT VT = Vec.getValueType();
69  assert(VT.is256BitVector() && "Unexpected vector size!");
70  EVT ElVT = VT.getVectorElementType();
71  unsigned Factor = VT.getSizeInBits()/128;
72  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                  VT.getVectorNumElements()/Factor);
74
75  // Extract from UNDEF is UNDEF.
76  if (Vec.getOpcode() == ISD::UNDEF)
77    return DAG.getUNDEF(ResultVT);
78
79  // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80  // we can match to VEXTRACTF128.
81  unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83  // This is the index of the first element of the 128-bit chunk
84  // we want.
85  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                               * ElemsPerChunk);
87
88  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89  SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                               VecIdx);
91
92  return Result;
93}
94
95/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96/// sets things up to match to an AVX VINSERTF128 instruction or a
97/// simple superregister reference.  Idx is an index in the 128 bits
98/// we want.  It need not be aligned to a 128-bit bounday.  That makes
99/// lowering INSERT_VECTOR_ELT operations easier.
100static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                  unsigned IdxVal, SelectionDAG &DAG,
102                                  DebugLoc dl) {
103  // Inserting UNDEF is Result
104  if (Vec.getOpcode() == ISD::UNDEF)
105    return Result;
106
107  EVT VT = Vec.getValueType();
108  assert(VT.is128BitVector() && "Unexpected vector size!");
109
110  EVT ElVT = VT.getVectorElementType();
111  EVT ResultVT = Result.getValueType();
112
113  // Insert the relevant 128 bits.
114  unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116  // This is the index of the first element of the 128-bit chunk
117  // we want.
118  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                               * ElemsPerChunk);
120
121  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122  return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                     VecIdx);
124}
125
126/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127/// instructions. This is used because creating CONCAT_VECTOR nodes of
128/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129/// large BUILD_VECTORS.
130static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                   unsigned NumElems, SelectionDAG &DAG,
132                                   DebugLoc dl) {
133  SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134  return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135}
136
137static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139  bool is64Bit = Subtarget->is64Bit();
140
141  if (Subtarget->isTargetEnvMacho()) {
142    if (is64Bit)
143      return new X86_64MachoTargetObjectFile();
144    return new TargetLoweringObjectFileMachO();
145  }
146
147  if (Subtarget->isTargetLinux())
148    return new X86LinuxTargetObjectFile();
149  if (Subtarget->isTargetELF())
150    return new TargetLoweringObjectFileELF();
151  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152    return new TargetLoweringObjectFileCOFF();
153  llvm_unreachable("unknown subtarget type");
154}
155
156X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157  : TargetLowering(TM, createTLOF(TM)) {
158  Subtarget = &TM.getSubtarget<X86Subtarget>();
159  X86ScalarSSEf64 = Subtarget->hasSSE2();
160  X86ScalarSSEf32 = Subtarget->hasSSE1();
161
162  RegInfo = TM.getRegisterInfo();
163  TD = getDataLayout();
164
165  // Set up the TargetLowering object.
166  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168  // X86 is weird, it always uses i8 for shift amounts and setcc results.
169  setBooleanContents(ZeroOrOneBooleanContent);
170  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173  // For 64-bit since we have so many registers use the ILP scheduler, for
174  // 32-bit code use the register pressure specific scheduling.
175  // For Atom, always use ILP scheduling.
176  if (Subtarget->isAtom())
177    setSchedulingPreference(Sched::ILP);
178  else if (Subtarget->is64Bit())
179    setSchedulingPreference(Sched::ILP);
180  else
181    setSchedulingPreference(Sched::RegPressure);
182  setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184  // Bypass i32 with i8 on Atom when compiling with O2
185  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186    addBypassSlowDiv(32, 8);
187
188  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189    // Setup Windows compiler runtime calls.
190    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192    setLibcallName(RTLIB::SREM_I64, "_allrem");
193    setLibcallName(RTLIB::UREM_I64, "_aullrem");
194    setLibcallName(RTLIB::MUL_I64, "_allmul");
195    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201    // The _ftol2 runtime function has an unusual calling conv, which
202    // is modeled by a special pseudo-instruction.
203    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207  }
208
209  if (Subtarget->isTargetDarwin()) {
210    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211    setUseUnderscoreSetJmp(false);
212    setUseUnderscoreLongJmp(false);
213  } else if (Subtarget->isTargetMingw()) {
214    // MS runtime is weird: it exports _setjmp, but longjmp!
215    setUseUnderscoreSetJmp(true);
216    setUseUnderscoreLongJmp(false);
217  } else {
218    setUseUnderscoreSetJmp(true);
219    setUseUnderscoreLongJmp(true);
220  }
221
222  // Set up the register classes.
223  addRegisterClass(MVT::i8, &X86::GR8RegClass);
224  addRegisterClass(MVT::i16, &X86::GR16RegClass);
225  addRegisterClass(MVT::i32, &X86::GR32RegClass);
226  if (Subtarget->is64Bit())
227    addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231  // We don't accept any truncstore of integer registers.
232  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239  // SETOEQ and SETUNE require checking two conditions.
240  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248  // operation.
249  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253  if (Subtarget->is64Bit()) {
254    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256  } else if (!TM.Options.UseSoftFloat) {
257    // We have an algorithm for SSE2->double, and we turn this into a
258    // 64-bit FILD followed by conditional FADD for other targets.
259    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260    // We have an algorithm for SSE2, and we turn this into a 64-bit
261    // FILD for other targets.
262    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263  }
264
265  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266  // this operation.
267  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270  if (!TM.Options.UseSoftFloat) {
271    // SSE has no i16 to fp conversion, only i32
272    if (X86ScalarSSEf32) {
273      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274      // f32 and f64 cases are Legal, f80 case is not
275      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276    } else {
277      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279    }
280  } else {
281    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283  }
284
285  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286  // are Legal, f80 is custom lowered.
287  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291  // this operation.
292  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295  if (X86ScalarSSEf32) {
296    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297    // f32 and f64 cases are Legal, f80 case is not
298    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299  } else {
300    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302  }
303
304  // Handle FP_TO_UINT by promoting the destination to a larger signed
305  // conversion.
306  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310  if (Subtarget->is64Bit()) {
311    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313  } else if (!TM.Options.UseSoftFloat) {
314    // Since AVX is a superset of SSE3, only check for SSE here.
315    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316      // Expand FP_TO_UINT into a select.
317      // FIXME: We would like to use a Custom expander here eventually to do
318      // the optimal thing for SSE vs. the default expansion in the legalizer.
319      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320    else
321      // With SSE3 we can use fisttpll to convert to a signed i64; without
322      // SSE, we're stuck with a fistpll.
323      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324  }
325
326  if (isTargetFTOL()) {
327    // Use the _ftol2 runtime function, which has a pseudo-instruction
328    // to handle its weird calling convention.
329    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330  }
331
332  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333  if (!X86ScalarSSEf64) {
334    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336    if (Subtarget->is64Bit()) {
337      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338      // Without SSE, i64->f64 goes through memory.
339      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340    }
341  }
342
343  // Scalar integer divide and remainder are lowered to use operations that
344  // produce two results, to match the available instructions. This exposes
345  // the two-result form to trivial CSE, which is able to combine x/y and x%y
346  // into a single instruction.
347  //
348  // Scalar integer multiply-high is also lowered to use two-result
349  // operations, to match the available instructions. However, plain multiply
350  // (low) operations are left as Legal, as there are single-result
351  // instructions for this in x86. Using the two-result multiply instructions
352  // when both high and low results are needed must be arranged by dagcombine.
353  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354    MVT VT = IntVTs[i];
355    setOperationAction(ISD::MULHS, VT, Expand);
356    setOperationAction(ISD::MULHU, VT, Expand);
357    setOperationAction(ISD::SDIV, VT, Expand);
358    setOperationAction(ISD::UDIV, VT, Expand);
359    setOperationAction(ISD::SREM, VT, Expand);
360    setOperationAction(ISD::UREM, VT, Expand);
361
362    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363    setOperationAction(ISD::ADDC, VT, Custom);
364    setOperationAction(ISD::ADDE, VT, Custom);
365    setOperationAction(ISD::SUBC, VT, Custom);
366    setOperationAction(ISD::SUBE, VT, Custom);
367  }
368
369  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373  if (Subtarget->is64Bit())
374    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384  // Promote the i8 variants and force them on up to i32 which has a shorter
385  // encoding.
386  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390  if (Subtarget->hasBMI()) {
391    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393    if (Subtarget->is64Bit())
394      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395  } else {
396    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398    if (Subtarget->is64Bit())
399      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400  }
401
402  if (Subtarget->hasLZCNT()) {
403    // When promoting the i8 variants, force them to i32 for a shorter
404    // encoding.
405    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411    if (Subtarget->is64Bit())
412      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413  } else {
414    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420    if (Subtarget->is64Bit()) {
421      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423    }
424  }
425
426  if (Subtarget->hasPOPCNT()) {
427    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428  } else {
429    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432    if (Subtarget->is64Bit())
433      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434  }
435
436  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439  // These should be promoted to a larger select which is supported.
440  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441  // X86 wants to expand cmov itself.
442  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454  if (Subtarget->is64Bit()) {
455    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457  }
458  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461  // support continuation, user-level threading, and etc.. As a result, no
462  // other SjLj exception interfaces are implemented and please don't build
463  // your own exception handling based on them.
464  // LLVM/Clang supports zero-cost DWARF exception handling.
465  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468  // Darwin ABI issue.
469  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473  if (Subtarget->is64Bit())
474    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477  if (Subtarget->is64Bit()) {
478    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483  }
484  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488  if (Subtarget->is64Bit()) {
489    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492  }
493
494  if (Subtarget->hasSSE1())
495    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500  // On X86 and X86-64, atomic operations are lowered to locked instructions.
501  // Locked instructions, in turn, have implicit fence semantics (all memory
502  // operations are flushed before issuing the locked instruction, and they
503  // are not buffered), so we can fold away the common pattern of
504  // fence-atomic-fence.
505  setShouldFoldAtomicFences(true);
506
507  // Expand certain atomics
508  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509    MVT VT = IntVTs[i];
510    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513  }
514
515  if (!Subtarget->is64Bit()) {
516    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528  }
529
530  if (Subtarget->hasCmpxchg16b()) {
531    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532  }
533
534  // FIXME - use subtarget debug flags
535  if (!Subtarget->isTargetDarwin() &&
536      !Subtarget->isTargetELF() &&
537      !Subtarget->isTargetCygMing()) {
538    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539  }
540
541  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545  if (Subtarget->is64Bit()) {
546    setExceptionPointerRegister(X86::RAX);
547    setExceptionSelectorRegister(X86::RDX);
548  } else {
549    setExceptionPointerRegister(X86::EAX);
550    setExceptionSelectorRegister(X86::EDX);
551  }
552  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558  setOperationAction(ISD::TRAP, MVT::Other, Legal);
559  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564  if (Subtarget->is64Bit()) {
565    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567  } else {
568    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570  }
571
572  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                       MVT::i64 : MVT::i32, Custom);
578  else if (TM.Options.EnableSegmentedStacks)
579    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                       MVT::i64 : MVT::i32, Custom);
581  else
582    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                       MVT::i64 : MVT::i32, Expand);
584
585  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586    // f32 and f64 use SSE.
587    // Set up the FP register classes.
588    addRegisterClass(MVT::f32, &X86::FR32RegClass);
589    addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591    // Use ANDPD to simulate FABS.
592    setOperationAction(ISD::FABS , MVT::f64, Custom);
593    setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595    // Use XORP to simulate FNEG.
596    setOperationAction(ISD::FNEG , MVT::f64, Custom);
597    setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599    // Use ANDPD and ORPD to simulate FCOPYSIGN.
600    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603    // Lower this to FGETSIGNx86 plus an AND.
604    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607    // We don't support sin/cos/fmod
608    setOperationAction(ISD::FSIN   , MVT::f64, Expand);
609    setOperationAction(ISD::FCOS   , MVT::f64, Expand);
610    setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
611    setOperationAction(ISD::FSIN   , MVT::f32, Expand);
612    setOperationAction(ISD::FCOS   , MVT::f32, Expand);
613    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
614
615    // Expand FP immediates into loads from the stack, except for the special
616    // cases we handle.
617    addLegalFPImmediate(APFloat(+0.0)); // xorpd
618    addLegalFPImmediate(APFloat(+0.0f)); // xorps
619  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
620    // Use SSE for f32, x87 for f64.
621    // Set up the FP register classes.
622    addRegisterClass(MVT::f32, &X86::FR32RegClass);
623    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
624
625    // Use ANDPS to simulate FABS.
626    setOperationAction(ISD::FABS , MVT::f32, Custom);
627
628    // Use XORP to simulate FNEG.
629    setOperationAction(ISD::FNEG , MVT::f32, Custom);
630
631    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
632
633    // Use ANDPS and ORPS to simulate FCOPYSIGN.
634    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
635    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
636
637    // We don't support sin/cos/fmod
638    setOperationAction(ISD::FSIN   , MVT::f32, Expand);
639    setOperationAction(ISD::FCOS   , MVT::f32, Expand);
640    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
641
642    // Special cases we handle for FP constants.
643    addLegalFPImmediate(APFloat(+0.0f)); // xorps
644    addLegalFPImmediate(APFloat(+0.0)); // FLD0
645    addLegalFPImmediate(APFloat(+1.0)); // FLD1
646    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
647    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
648
649    if (!TM.Options.UnsafeFPMath) {
650      setOperationAction(ISD::FSIN   , MVT::f64, Expand);
651      setOperationAction(ISD::FCOS   , MVT::f64, Expand);
652      setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
653    }
654  } else if (!TM.Options.UseSoftFloat) {
655    // f32 and f64 in x87.
656    // Set up the FP register classes.
657    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
658    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
659
660    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
661    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
662    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
663    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
664
665    if (!TM.Options.UnsafeFPMath) {
666      setOperationAction(ISD::FSIN   , MVT::f64, Expand);
667      setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668      setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669      setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670      setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
671      setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672    }
673    addLegalFPImmediate(APFloat(+0.0)); // FLD0
674    addLegalFPImmediate(APFloat(+1.0)); // FLD1
675    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
676    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
677    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
678    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
679    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
680    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
681  }
682
683  // We don't support FMA.
684  setOperationAction(ISD::FMA, MVT::f64, Expand);
685  setOperationAction(ISD::FMA, MVT::f32, Expand);
686
687  // Long double always uses X87.
688  if (!TM.Options.UseSoftFloat) {
689    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
690    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
691    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
692    {
693      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
694      addLegalFPImmediate(TmpFlt);  // FLD0
695      TmpFlt.changeSign();
696      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
697
698      bool ignored;
699      APFloat TmpFlt2(+1.0);
700      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
701                      &ignored);
702      addLegalFPImmediate(TmpFlt2);  // FLD1
703      TmpFlt2.changeSign();
704      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
705    }
706
707    if (!TM.Options.UnsafeFPMath) {
708      setOperationAction(ISD::FSIN   , MVT::f80, Expand);
709      setOperationAction(ISD::FCOS   , MVT::f80, Expand);
710      setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
711    }
712
713    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
714    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
715    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
716    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
717    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
718    setOperationAction(ISD::FMA, MVT::f80, Expand);
719  }
720
721  // Always use a library call for pow.
722  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
723  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
724  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
725
726  setOperationAction(ISD::FLOG, MVT::f80, Expand);
727  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
728  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
729  setOperationAction(ISD::FEXP, MVT::f80, Expand);
730  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
731
732  // First set operation action for all vector types to either promote
733  // (for widening) or expand (for scalarization). Then we will selectively
734  // turn on ones that can be effectively codegen'd.
735  for (int i = MVT::FIRST_VECTOR_VALUETYPE;
736           i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
737    MVT VT = (MVT::SimpleValueType)i;
738    setOperationAction(ISD::ADD , VT, Expand);
739    setOperationAction(ISD::SUB , VT, Expand);
740    setOperationAction(ISD::FADD, VT, Expand);
741    setOperationAction(ISD::FNEG, VT, Expand);
742    setOperationAction(ISD::FSUB, VT, Expand);
743    setOperationAction(ISD::MUL , VT, Expand);
744    setOperationAction(ISD::FMUL, VT, Expand);
745    setOperationAction(ISD::SDIV, VT, Expand);
746    setOperationAction(ISD::UDIV, VT, Expand);
747    setOperationAction(ISD::FDIV, VT, Expand);
748    setOperationAction(ISD::SREM, VT, Expand);
749    setOperationAction(ISD::UREM, VT, Expand);
750    setOperationAction(ISD::LOAD, VT, Expand);
751    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
752    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
753    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
754    setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
755    setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
756    setOperationAction(ISD::FABS, VT, Expand);
757    setOperationAction(ISD::FSIN, VT, Expand);
758    setOperationAction(ISD::FSINCOS, VT, Expand);
759    setOperationAction(ISD::FCOS, VT, Expand);
760    setOperationAction(ISD::FSINCOS, VT, Expand);
761    setOperationAction(ISD::FREM, VT, Expand);
762    setOperationAction(ISD::FMA,  VT, Expand);
763    setOperationAction(ISD::FPOWI, VT, Expand);
764    setOperationAction(ISD::FSQRT, VT, Expand);
765    setOperationAction(ISD::FCOPYSIGN, VT, Expand);
766    setOperationAction(ISD::FFLOOR, VT, Expand);
767    setOperationAction(ISD::FCEIL, VT, Expand);
768    setOperationAction(ISD::FTRUNC, VT, Expand);
769    setOperationAction(ISD::FRINT, VT, Expand);
770    setOperationAction(ISD::FNEARBYINT, VT, Expand);
771    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
772    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
773    setOperationAction(ISD::SDIVREM, VT, Expand);
774    setOperationAction(ISD::UDIVREM, VT, Expand);
775    setOperationAction(ISD::FPOW, VT, Expand);
776    setOperationAction(ISD::CTPOP, VT, Expand);
777    setOperationAction(ISD::CTTZ, VT, Expand);
778    setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
779    setOperationAction(ISD::CTLZ, VT, Expand);
780    setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
781    setOperationAction(ISD::SHL, VT, Expand);
782    setOperationAction(ISD::SRA, VT, Expand);
783    setOperationAction(ISD::SRL, VT, Expand);
784    setOperationAction(ISD::ROTL, VT, Expand);
785    setOperationAction(ISD::ROTR, VT, Expand);
786    setOperationAction(ISD::BSWAP, VT, Expand);
787    setOperationAction(ISD::SETCC, VT, Expand);
788    setOperationAction(ISD::FLOG, VT, Expand);
789    setOperationAction(ISD::FLOG2, VT, Expand);
790    setOperationAction(ISD::FLOG10, VT, Expand);
791    setOperationAction(ISD::FEXP, VT, Expand);
792    setOperationAction(ISD::FEXP2, VT, Expand);
793    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
794    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
795    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
796    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
797    setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
798    setOperationAction(ISD::TRUNCATE, VT, Expand);
799    setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
800    setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
801    setOperationAction(ISD::ANY_EXTEND, VT, Expand);
802    setOperationAction(ISD::VSELECT, VT, Expand);
803    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
804             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
805      setTruncStoreAction(VT,
806                          (MVT::SimpleValueType)InnerVT, Expand);
807    setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
808    setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
809    setLoadExtAction(ISD::EXTLOAD, VT, Expand);
810  }
811
812  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
813  // with -msoft-float, disable use of MMX as well.
814  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
815    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
816    // No operations on x86mmx supported, everything uses intrinsics.
817  }
818
819  // MMX-sized vectors (other than x86mmx) are expected to be expanded
820  // into smaller operations.
821  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
822  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
823  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
824  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
825  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
826  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
827  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
828  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
829  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
830  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
831  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
832  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
833  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
834  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
835  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
836  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
837  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
838  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
839  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
840  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
841  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
842  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
843  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
844  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
845  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
846  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
847  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
848  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
849  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
850
851  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
852    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
853
854    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
855    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
856    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
857    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
858    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
859    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
860    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
861    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
862    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
863    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
864    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
865    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
866  }
867
868  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
869    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
870
871    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
872    // registers cannot be used even for integer operations.
873    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
874    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
875    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
876    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
877
878    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
879    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
880    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
881    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
882    setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
883    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
884    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
885    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
886    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
887    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
888    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
889    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
890    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
891    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
892    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
893    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
894    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
895    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
896
897    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
898    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
899    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
900    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
901
902    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
903    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
904    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
905    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
906    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
907
908    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
909    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910      MVT VT = (MVT::SimpleValueType)i;
911      // Do not attempt to custom lower non-power-of-2 vectors
912      if (!isPowerOf2_32(VT.getVectorNumElements()))
913        continue;
914      // Do not attempt to custom lower non-128-bit vectors
915      if (!VT.is128BitVector())
916        continue;
917      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
918      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
919      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
920    }
921
922    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
923    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
924    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
925    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
926    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
927    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
928
929    if (Subtarget->is64Bit()) {
930      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
931      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
932    }
933
934    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
935    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
936      MVT VT = (MVT::SimpleValueType)i;
937
938      // Do not attempt to promote non-128-bit vectors
939      if (!VT.is128BitVector())
940        continue;
941
942      setOperationAction(ISD::AND,    VT, Promote);
943      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
944      setOperationAction(ISD::OR,     VT, Promote);
945      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
946      setOperationAction(ISD::XOR,    VT, Promote);
947      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
948      setOperationAction(ISD::LOAD,   VT, Promote);
949      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
950      setOperationAction(ISD::SELECT, VT, Promote);
951      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
952    }
953
954    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
955
956    // Custom lower v2i64 and v2f64 selects.
957    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
958    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
959    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
960    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
961
962    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
963    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
964
965    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
966    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
967    // As there is no 64-bit GPR available, we need build a special custom
968    // sequence to convert from v2i32 to v2f32.
969    if (!Subtarget->is64Bit())
970      setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
971
972    setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
973    setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
974
975    setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
976  }
977
978  if (Subtarget->hasSSE41()) {
979    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
980    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
981    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
982    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
983    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
984    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
985    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
986    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
987    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
988    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
989
990    setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
991    setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
992    setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
993    setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
994    setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
995    setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
996    setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
997    setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
998    setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
999    setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1000
1001    // FIXME: Do we need to handle scalar-to-vector here?
1002    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1003
1004    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1005    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1006    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1007    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1008    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1009
1010    // i8 and i16 vectors are custom , because the source register and source
1011    // source memory operand types are not the same width.  f32 vectors are
1012    // custom since the immediate controlling the insert encodes additional
1013    // information.
1014    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1015    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1016    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1017    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1018
1019    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1020    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1021    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1022    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1023
1024    // FIXME: these should be Legal but thats only for the case where
1025    // the index is constant.  For now custom expand to deal with that.
1026    if (Subtarget->is64Bit()) {
1027      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1028      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1029    }
1030  }
1031
1032  if (Subtarget->hasSSE2()) {
1033    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1034    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1035
1036    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1037    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1038
1039    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1040    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1041
1042    if (Subtarget->hasInt256()) {
1043      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1044      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1045
1046      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1047      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1048
1049      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1050    } else {
1051      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1052      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1053
1054      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1055      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1056
1057      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1058    }
1059    setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1060    setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1061  }
1062
1063  if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1064    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1065    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1066    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1067    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1068    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1069    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1070
1071    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1072    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1073    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1074
1075    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1076    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1077    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1078    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1079    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1080    setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1081    setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1082    setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1083    setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1084    setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1085    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1086    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1087
1088    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1089    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1090    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1091    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1092    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1093    setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1094    setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1095    setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1096    setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1097    setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1098    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1099    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1100
1101    setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1102    setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1103
1104    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1105
1106    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1107    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1108    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1109
1110    setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1111    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1112    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1113
1114    setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1115
1116    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1117    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1118
1119    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1120    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1121
1122    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1123    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1124
1125    setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1126
1127    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1128    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1129    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1130    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1131
1132    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1133    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1134    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1135
1136    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1137    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1138    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1139    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1140
1141    setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1142    setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1143    setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1144    setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1145    setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1146    setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1147
1148    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1149      setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1150      setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1151      setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1152      setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1153      setOperationAction(ISD::FMA,             MVT::f32, Legal);
1154      setOperationAction(ISD::FMA,             MVT::f64, Legal);
1155    }
1156
1157    if (Subtarget->hasInt256()) {
1158      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1159      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1160      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1161      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1162
1163      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1164      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1165      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1166      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1167
1168      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1169      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1170      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1171      // Don't lower v32i8 because there is no 128-bit byte mul
1172
1173      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1174
1175      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1176      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1177
1178      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1179      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1180
1181      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1182
1183      setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1184    } else {
1185      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1186      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1187      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1188      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1189
1190      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1191      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1192      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1193      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1194
1195      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1196      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1197      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1198      // Don't lower v32i8 because there is no 128-bit byte mul
1199
1200      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1201      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1202
1203      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1204      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1205
1206      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1207    }
1208
1209    // Custom lower several nodes for 256-bit types.
1210    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1211             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1212      MVT VT = (MVT::SimpleValueType)i;
1213
1214      // Extract subvector is special because the value type
1215      // (result) is 128-bit but the source is 256-bit wide.
1216      if (VT.is128BitVector())
1217        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1218
1219      // Do not attempt to custom lower other non-256-bit vectors
1220      if (!VT.is256BitVector())
1221        continue;
1222
1223      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1224      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1225      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1226      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1227      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1228      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1229      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1230    }
1231
1232    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1233    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1234      MVT VT = (MVT::SimpleValueType)i;
1235
1236      // Do not attempt to promote non-256-bit vectors
1237      if (!VT.is256BitVector())
1238        continue;
1239
1240      setOperationAction(ISD::AND,    VT, Promote);
1241      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1242      setOperationAction(ISD::OR,     VT, Promote);
1243      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1244      setOperationAction(ISD::XOR,    VT, Promote);
1245      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1246      setOperationAction(ISD::LOAD,   VT, Promote);
1247      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1248      setOperationAction(ISD::SELECT, VT, Promote);
1249      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1250    }
1251  }
1252
1253  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1254  // of this type with custom code.
1255  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1256           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1257    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1258                       Custom);
1259  }
1260
1261  // We want to custom lower some of our intrinsics.
1262  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1263  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1264
1265  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1266  // handle type legalization for these operations here.
1267  //
1268  // FIXME: We really should do custom legalization for addition and
1269  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1270  // than generic legalization for 64-bit multiplication-with-overflow, though.
1271  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1272    // Add/Sub/Mul with overflow operations are custom lowered.
1273    MVT VT = IntVTs[i];
1274    setOperationAction(ISD::SADDO, VT, Custom);
1275    setOperationAction(ISD::UADDO, VT, Custom);
1276    setOperationAction(ISD::SSUBO, VT, Custom);
1277    setOperationAction(ISD::USUBO, VT, Custom);
1278    setOperationAction(ISD::SMULO, VT, Custom);
1279    setOperationAction(ISD::UMULO, VT, Custom);
1280  }
1281
1282  // There are no 8-bit 3-address imul/mul instructions
1283  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1284  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1285
1286  if (!Subtarget->is64Bit()) {
1287    // These libcalls are not available in 32-bit.
1288    setLibcallName(RTLIB::SHL_I128, 0);
1289    setLibcallName(RTLIB::SRL_I128, 0);
1290    setLibcallName(RTLIB::SRA_I128, 0);
1291  }
1292
1293  // Combine sin / cos into one node or libcall if possible.
1294  if (Subtarget->hasSinCos()) {
1295    setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1296    setLibcallName(RTLIB::SINCOS_F64, "sincos");
1297    if (Subtarget->isTargetDarwin()) {
1298      // For MacOSX, we don't want to the normal expansion of a libcall to
1299      // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1300      // traffic.
1301      setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1302      setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1303    }
1304  }
1305
1306  // We have target-specific dag combine patterns for the following nodes:
1307  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1308  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1309  setTargetDAGCombine(ISD::VSELECT);
1310  setTargetDAGCombine(ISD::SELECT);
1311  setTargetDAGCombine(ISD::SHL);
1312  setTargetDAGCombine(ISD::SRA);
1313  setTargetDAGCombine(ISD::SRL);
1314  setTargetDAGCombine(ISD::OR);
1315  setTargetDAGCombine(ISD::AND);
1316  setTargetDAGCombine(ISD::ADD);
1317  setTargetDAGCombine(ISD::FADD);
1318  setTargetDAGCombine(ISD::FSUB);
1319  setTargetDAGCombine(ISD::FMA);
1320  setTargetDAGCombine(ISD::SUB);
1321  setTargetDAGCombine(ISD::LOAD);
1322  setTargetDAGCombine(ISD::STORE);
1323  setTargetDAGCombine(ISD::ZERO_EXTEND);
1324  setTargetDAGCombine(ISD::ANY_EXTEND);
1325  setTargetDAGCombine(ISD::SIGN_EXTEND);
1326  setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1327  setTargetDAGCombine(ISD::TRUNCATE);
1328  setTargetDAGCombine(ISD::SINT_TO_FP);
1329  setTargetDAGCombine(ISD::SETCC);
1330  if (Subtarget->is64Bit())
1331    setTargetDAGCombine(ISD::MUL);
1332  setTargetDAGCombine(ISD::XOR);
1333
1334  computeRegisterProperties();
1335
1336  // On Darwin, -Os means optimize for size without hurting performance,
1337  // do not reduce the limit.
1338  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1339  MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1340  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1341  MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1342  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1343  MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1344  setPrefLoopAlignment(4); // 2^4 bytes.
1345  BenefitFromCodePlacementOpt = true;
1346
1347  // Predictable cmov don't hurt on atom because it's in-order.
1348  PredictableSelectIsExpensive = !Subtarget->isAtom();
1349
1350  setPrefFunctionAlignment(4); // 2^4 bytes.
1351}
1352
1353EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1354  if (!VT.isVector()) return MVT::i8;
1355  return VT.changeVectorElementTypeToInteger();
1356}
1357
1358/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1359/// the desired ByVal argument alignment.
1360static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1361  if (MaxAlign == 16)
1362    return;
1363  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1364    if (VTy->getBitWidth() == 128)
1365      MaxAlign = 16;
1366  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1367    unsigned EltAlign = 0;
1368    getMaxByValAlign(ATy->getElementType(), EltAlign);
1369    if (EltAlign > MaxAlign)
1370      MaxAlign = EltAlign;
1371  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1372    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1373      unsigned EltAlign = 0;
1374      getMaxByValAlign(STy->getElementType(i), EltAlign);
1375      if (EltAlign > MaxAlign)
1376        MaxAlign = EltAlign;
1377      if (MaxAlign == 16)
1378        break;
1379    }
1380  }
1381}
1382
1383/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1384/// function arguments in the caller parameter area. For X86, aggregates
1385/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1386/// are at 4-byte boundaries.
1387unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1388  if (Subtarget->is64Bit()) {
1389    // Max of 8 and alignment of type.
1390    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1391    if (TyAlign > 8)
1392      return TyAlign;
1393    return 8;
1394  }
1395
1396  unsigned Align = 4;
1397  if (Subtarget->hasSSE1())
1398    getMaxByValAlign(Ty, Align);
1399  return Align;
1400}
1401
1402/// getOptimalMemOpType - Returns the target specific optimal type for load
1403/// and store operations as a result of memset, memcpy, and memmove
1404/// lowering. If DstAlign is zero that means it's safe to destination
1405/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1406/// means there isn't a need to check it against alignment requirement,
1407/// probably because the source does not need to be loaded. If 'IsMemset' is
1408/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1409/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1410/// source is constant so it does not need to be loaded.
1411/// It returns EVT::Other if the type should be determined using generic
1412/// target-independent logic.
1413EVT
1414X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1415                                       unsigned DstAlign, unsigned SrcAlign,
1416                                       bool IsMemset, bool ZeroMemset,
1417                                       bool MemcpyStrSrc,
1418                                       MachineFunction &MF) const {
1419  const Function *F = MF.getFunction();
1420  if ((!IsMemset || ZeroMemset) &&
1421      !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1422                                       Attribute::NoImplicitFloat)) {
1423    if (Size >= 16 &&
1424        (Subtarget->isUnalignedMemAccessFast() ||
1425         ((DstAlign == 0 || DstAlign >= 16) &&
1426          (SrcAlign == 0 || SrcAlign >= 16)))) {
1427      if (Size >= 32) {
1428        if (Subtarget->hasInt256())
1429          return MVT::v8i32;
1430        if (Subtarget->hasFp256())
1431          return MVT::v8f32;
1432      }
1433      if (Subtarget->hasSSE2())
1434        return MVT::v4i32;
1435      if (Subtarget->hasSSE1())
1436        return MVT::v4f32;
1437    } else if (!MemcpyStrSrc && Size >= 8 &&
1438               !Subtarget->is64Bit() &&
1439               Subtarget->hasSSE2()) {
1440      // Do not use f64 to lower memcpy if source is string constant. It's
1441      // better to use i32 to avoid the loads.
1442      return MVT::f64;
1443    }
1444  }
1445  if (Subtarget->is64Bit() && Size >= 8)
1446    return MVT::i64;
1447  return MVT::i32;
1448}
1449
1450bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1451  if (VT == MVT::f32)
1452    return X86ScalarSSEf32;
1453  else if (VT == MVT::f64)
1454    return X86ScalarSSEf64;
1455  return true;
1456}
1457
1458bool
1459X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1460  if (Fast)
1461    *Fast = Subtarget->isUnalignedMemAccessFast();
1462  return true;
1463}
1464
1465/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1466/// current function.  The returned value is a member of the
1467/// MachineJumpTableInfo::JTEntryKind enum.
1468unsigned X86TargetLowering::getJumpTableEncoding() const {
1469  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1470  // symbol.
1471  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1472      Subtarget->isPICStyleGOT())
1473    return MachineJumpTableInfo::EK_Custom32;
1474
1475  // Otherwise, use the normal jump table encoding heuristics.
1476  return TargetLowering::getJumpTableEncoding();
1477}
1478
1479const MCExpr *
1480X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1481                                             const MachineBasicBlock *MBB,
1482                                             unsigned uid,MCContext &Ctx) const{
1483  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1484         Subtarget->isPICStyleGOT());
1485  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1486  // entries.
1487  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1488                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1489}
1490
1491/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1492/// jumptable.
1493SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1494                                                    SelectionDAG &DAG) const {
1495  if (!Subtarget->is64Bit())
1496    // This doesn't have DebugLoc associated with it, but is not really the
1497    // same as a Register.
1498    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1499  return Table;
1500}
1501
1502/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1503/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1504/// MCExpr.
1505const MCExpr *X86TargetLowering::
1506getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1507                             MCContext &Ctx) const {
1508  // X86-64 uses RIP relative addressing based on the jump table label.
1509  if (Subtarget->isPICStyleRIPRel())
1510    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1511
1512  // Otherwise, the reference is relative to the PIC base.
1513  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1514}
1515
1516// FIXME: Why this routine is here? Move to RegInfo!
1517std::pair<const TargetRegisterClass*, uint8_t>
1518X86TargetLowering::findRepresentativeClass(MVT VT) const{
1519  const TargetRegisterClass *RRC = 0;
1520  uint8_t Cost = 1;
1521  switch (VT.SimpleTy) {
1522  default:
1523    return TargetLowering::findRepresentativeClass(VT);
1524  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1525    RRC = Subtarget->is64Bit() ?
1526      (const TargetRegisterClass*)&X86::GR64RegClass :
1527      (const TargetRegisterClass*)&X86::GR32RegClass;
1528    break;
1529  case MVT::x86mmx:
1530    RRC = &X86::VR64RegClass;
1531    break;
1532  case MVT::f32: case MVT::f64:
1533  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1534  case MVT::v4f32: case MVT::v2f64:
1535  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1536  case MVT::v4f64:
1537    RRC = &X86::VR128RegClass;
1538    break;
1539  }
1540  return std::make_pair(RRC, Cost);
1541}
1542
1543bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1544                                               unsigned &Offset) const {
1545  if (!Subtarget->isTargetLinux())
1546    return false;
1547
1548  if (Subtarget->is64Bit()) {
1549    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1550    Offset = 0x28;
1551    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1552      AddressSpace = 256;
1553    else
1554      AddressSpace = 257;
1555  } else {
1556    // %gs:0x14 on i386
1557    Offset = 0x14;
1558    AddressSpace = 256;
1559  }
1560  return true;
1561}
1562
1563//===----------------------------------------------------------------------===//
1564//               Return Value Calling Convention Implementation
1565//===----------------------------------------------------------------------===//
1566
1567#include "X86GenCallingConv.inc"
1568
1569bool
1570X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1571                                  MachineFunction &MF, bool isVarArg,
1572                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1573                        LLVMContext &Context) const {
1574  SmallVector<CCValAssign, 16> RVLocs;
1575  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1576                 RVLocs, Context);
1577  return CCInfo.CheckReturn(Outs, RetCC_X86);
1578}
1579
1580SDValue
1581X86TargetLowering::LowerReturn(SDValue Chain,
1582                               CallingConv::ID CallConv, bool isVarArg,
1583                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1584                               const SmallVectorImpl<SDValue> &OutVals,
1585                               DebugLoc dl, SelectionDAG &DAG) const {
1586  MachineFunction &MF = DAG.getMachineFunction();
1587  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1588
1589  SmallVector<CCValAssign, 16> RVLocs;
1590  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1591                 RVLocs, *DAG.getContext());
1592  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1593
1594  SDValue Flag;
1595  SmallVector<SDValue, 6> RetOps;
1596  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1597  // Operand #1 = Bytes To Pop
1598  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1599                   MVT::i16));
1600
1601  // Copy the result values into the output registers.
1602  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1603    CCValAssign &VA = RVLocs[i];
1604    assert(VA.isRegLoc() && "Can only return in registers!");
1605    SDValue ValToCopy = OutVals[i];
1606    EVT ValVT = ValToCopy.getValueType();
1607
1608    // Promote values to the appropriate types
1609    if (VA.getLocInfo() == CCValAssign::SExt)
1610      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1611    else if (VA.getLocInfo() == CCValAssign::ZExt)
1612      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1613    else if (VA.getLocInfo() == CCValAssign::AExt)
1614      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1615    else if (VA.getLocInfo() == CCValAssign::BCvt)
1616      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1617
1618    // If this is x86-64, and we disabled SSE, we can't return FP values,
1619    // or SSE or MMX vectors.
1620    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1621         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1622          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1623      report_fatal_error("SSE register return with SSE disabled");
1624    }
1625    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1626    // llvm-gcc has never done it right and no one has noticed, so this
1627    // should be OK for now.
1628    if (ValVT == MVT::f64 &&
1629        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1630      report_fatal_error("SSE2 register return with SSE2 disabled");
1631
1632    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1633    // the RET instruction and handled by the FP Stackifier.
1634    if (VA.getLocReg() == X86::ST0 ||
1635        VA.getLocReg() == X86::ST1) {
1636      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1637      // change the value to the FP stack register class.
1638      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1639        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1640      RetOps.push_back(ValToCopy);
1641      // Don't emit a copytoreg.
1642      continue;
1643    }
1644
1645    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1646    // which is returned in RAX / RDX.
1647    if (Subtarget->is64Bit()) {
1648      if (ValVT == MVT::x86mmx) {
1649        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1650          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1651          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1652                                  ValToCopy);
1653          // If we don't have SSE2 available, convert to v4f32 so the generated
1654          // register is legal.
1655          if (!Subtarget->hasSSE2())
1656            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1657        }
1658      }
1659    }
1660
1661    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1662    Flag = Chain.getValue(1);
1663    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1664  }
1665
1666  // The x86-64 ABIs require that for returning structs by value we copy
1667  // the sret argument into %rax/%eax (depending on ABI) for the return.
1668  // We saved the argument into a virtual register in the entry block,
1669  // so now we copy the value out and into %rax/%eax.
1670  if (Subtarget->is64Bit() &&
1671      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1672    MachineFunction &MF = DAG.getMachineFunction();
1673    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1674    unsigned Reg = FuncInfo->getSRetReturnReg();
1675    assert(Reg &&
1676           "SRetReturnReg should have been set in LowerFormalArguments().");
1677    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1678
1679    unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1680    Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1681    Flag = Chain.getValue(1);
1682
1683    // RAX/EAX now acts like a return value.
1684    RetOps.push_back(DAG.getRegister(RetValReg, MVT::i64));
1685  }
1686
1687  RetOps[0] = Chain;  // Update chain.
1688
1689  // Add the flag if we have it.
1690  if (Flag.getNode())
1691    RetOps.push_back(Flag);
1692
1693  return DAG.getNode(X86ISD::RET_FLAG, dl,
1694                     MVT::Other, &RetOps[0], RetOps.size());
1695}
1696
1697bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1698  if (N->getNumValues() != 1)
1699    return false;
1700  if (!N->hasNUsesOfValue(1, 0))
1701    return false;
1702
1703  SDValue TCChain = Chain;
1704  SDNode *Copy = *N->use_begin();
1705  if (Copy->getOpcode() == ISD::CopyToReg) {
1706    // If the copy has a glue operand, we conservatively assume it isn't safe to
1707    // perform a tail call.
1708    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1709      return false;
1710    TCChain = Copy->getOperand(0);
1711  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1712    return false;
1713
1714  bool HasRet = false;
1715  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1716       UI != UE; ++UI) {
1717    if (UI->getOpcode() != X86ISD::RET_FLAG)
1718      return false;
1719    HasRet = true;
1720  }
1721
1722  if (!HasRet)
1723    return false;
1724
1725  Chain = TCChain;
1726  return true;
1727}
1728
1729MVT
1730X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1731                                            ISD::NodeType ExtendKind) const {
1732  MVT ReturnMVT;
1733  // TODO: Is this also valid on 32-bit?
1734  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1735    ReturnMVT = MVT::i8;
1736  else
1737    ReturnMVT = MVT::i32;
1738
1739  MVT MinVT = getRegisterType(ReturnMVT);
1740  return VT.bitsLT(MinVT) ? MinVT : VT;
1741}
1742
1743/// LowerCallResult - Lower the result values of a call into the
1744/// appropriate copies out of appropriate physical registers.
1745///
1746SDValue
1747X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1748                                   CallingConv::ID CallConv, bool isVarArg,
1749                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1750                                   DebugLoc dl, SelectionDAG &DAG,
1751                                   SmallVectorImpl<SDValue> &InVals) const {
1752
1753  // Assign locations to each value returned by this call.
1754  SmallVector<CCValAssign, 16> RVLocs;
1755  bool Is64Bit = Subtarget->is64Bit();
1756  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1757                 getTargetMachine(), RVLocs, *DAG.getContext());
1758  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1759
1760  // Copy all of the result registers out of their specified physreg.
1761  for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1762    CCValAssign &VA = RVLocs[i];
1763    EVT CopyVT = VA.getValVT();
1764
1765    // If this is x86-64, and we disabled SSE, we can't return FP values
1766    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1767        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1768      report_fatal_error("SSE register return with SSE disabled");
1769    }
1770
1771    SDValue Val;
1772
1773    // If this is a call to a function that returns an fp value on the floating
1774    // point stack, we must guarantee the value is popped from the stack, so
1775    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1776    // if the return value is not used. We use the FpPOP_RETVAL instruction
1777    // instead.
1778    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1779      // If we prefer to use the value in xmm registers, copy it out as f80 and
1780      // use a truncate to move it from fp stack reg to xmm reg.
1781      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1782      SDValue Ops[] = { Chain, InFlag };
1783      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1784                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1785      Val = Chain.getValue(0);
1786
1787      // Round the f80 to the right size, which also moves it to the appropriate
1788      // xmm register.
1789      if (CopyVT != VA.getValVT())
1790        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1791                          // This truncation won't change the value.
1792                          DAG.getIntPtrConstant(1));
1793    } else {
1794      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1795                                 CopyVT, InFlag).getValue(1);
1796      Val = Chain.getValue(0);
1797    }
1798    InFlag = Chain.getValue(2);
1799    InVals.push_back(Val);
1800  }
1801
1802  return Chain;
1803}
1804
1805//===----------------------------------------------------------------------===//
1806//                C & StdCall & Fast Calling Convention implementation
1807//===----------------------------------------------------------------------===//
1808//  StdCall calling convention seems to be standard for many Windows' API
1809//  routines and around. It differs from C calling convention just a little:
1810//  callee should clean up the stack, not caller. Symbols should be also
1811//  decorated in some fancy way :) It doesn't support any vector arguments.
1812//  For info on fast calling convention see Fast Calling Convention (tail call)
1813//  implementation LowerX86_32FastCCCallTo.
1814
1815/// CallIsStructReturn - Determines whether a call uses struct return
1816/// semantics.
1817enum StructReturnType {
1818  NotStructReturn,
1819  RegStructReturn,
1820  StackStructReturn
1821};
1822static StructReturnType
1823callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1824  if (Outs.empty())
1825    return NotStructReturn;
1826
1827  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1828  if (!Flags.isSRet())
1829    return NotStructReturn;
1830  if (Flags.isInReg())
1831    return RegStructReturn;
1832  return StackStructReturn;
1833}
1834
1835/// ArgsAreStructReturn - Determines whether a function uses struct
1836/// return semantics.
1837static StructReturnType
1838argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1839  if (Ins.empty())
1840    return NotStructReturn;
1841
1842  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1843  if (!Flags.isSRet())
1844    return NotStructReturn;
1845  if (Flags.isInReg())
1846    return RegStructReturn;
1847  return StackStructReturn;
1848}
1849
1850/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1851/// by "Src" to address "Dst" with size and alignment information specified by
1852/// the specific parameter attribute. The copy will be passed as a byval
1853/// function parameter.
1854static SDValue
1855CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1856                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1857                          DebugLoc dl) {
1858  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1859
1860  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1861                       /*isVolatile*/false, /*AlwaysInline=*/true,
1862                       MachinePointerInfo(), MachinePointerInfo());
1863}
1864
1865/// IsTailCallConvention - Return true if the calling convention is one that
1866/// supports tail call optimization.
1867static bool IsTailCallConvention(CallingConv::ID CC) {
1868  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1869          CC == CallingConv::HiPE);
1870}
1871
1872bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1873  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1874    return false;
1875
1876  CallSite CS(CI);
1877  CallingConv::ID CalleeCC = CS.getCallingConv();
1878  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1879    return false;
1880
1881  return true;
1882}
1883
1884/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1885/// a tailcall target by changing its ABI.
1886static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1887                                   bool GuaranteedTailCallOpt) {
1888  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1889}
1890
1891SDValue
1892X86TargetLowering::LowerMemArgument(SDValue Chain,
1893                                    CallingConv::ID CallConv,
1894                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1895                                    DebugLoc dl, SelectionDAG &DAG,
1896                                    const CCValAssign &VA,
1897                                    MachineFrameInfo *MFI,
1898                                    unsigned i) const {
1899  // Create the nodes corresponding to a load from this parameter slot.
1900  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1901  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1902                              getTargetMachine().Options.GuaranteedTailCallOpt);
1903  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1904  EVT ValVT;
1905
1906  // If value is passed by pointer we have address passed instead of the value
1907  // itself.
1908  if (VA.getLocInfo() == CCValAssign::Indirect)
1909    ValVT = VA.getLocVT();
1910  else
1911    ValVT = VA.getValVT();
1912
1913  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1914  // changed with more analysis.
1915  // In case of tail call optimization mark all arguments mutable. Since they
1916  // could be overwritten by lowering of arguments in case of a tail call.
1917  if (Flags.isByVal()) {
1918    unsigned Bytes = Flags.getByValSize();
1919    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1920    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1921    return DAG.getFrameIndex(FI, getPointerTy());
1922  } else {
1923    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1924                                    VA.getLocMemOffset(), isImmutable);
1925    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1926    return DAG.getLoad(ValVT, dl, Chain, FIN,
1927                       MachinePointerInfo::getFixedStack(FI),
1928                       false, false, false, 0);
1929  }
1930}
1931
1932SDValue
1933X86TargetLowering::LowerFormalArguments(SDValue Chain,
1934                                        CallingConv::ID CallConv,
1935                                        bool isVarArg,
1936                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1937                                        DebugLoc dl,
1938                                        SelectionDAG &DAG,
1939                                        SmallVectorImpl<SDValue> &InVals)
1940                                          const {
1941  MachineFunction &MF = DAG.getMachineFunction();
1942  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1943
1944  const Function* Fn = MF.getFunction();
1945  if (Fn->hasExternalLinkage() &&
1946      Subtarget->isTargetCygMing() &&
1947      Fn->getName() == "main")
1948    FuncInfo->setForceFramePointer(true);
1949
1950  MachineFrameInfo *MFI = MF.getFrameInfo();
1951  bool Is64Bit = Subtarget->is64Bit();
1952  bool IsWindows = Subtarget->isTargetWindows();
1953  bool IsWin64 = Subtarget->isTargetWin64();
1954
1955  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1956         "Var args not supported with calling convention fastcc, ghc or hipe");
1957
1958  // Assign locations to all of the incoming arguments.
1959  SmallVector<CCValAssign, 16> ArgLocs;
1960  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1961                 ArgLocs, *DAG.getContext());
1962
1963  // Allocate shadow area for Win64
1964  if (IsWin64) {
1965    CCInfo.AllocateStack(32, 8);
1966  }
1967
1968  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1969
1970  unsigned LastVal = ~0U;
1971  SDValue ArgValue;
1972  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1973    CCValAssign &VA = ArgLocs[i];
1974    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1975    // places.
1976    assert(VA.getValNo() != LastVal &&
1977           "Don't support value assigned to multiple locs yet");
1978    (void)LastVal;
1979    LastVal = VA.getValNo();
1980
1981    if (VA.isRegLoc()) {
1982      EVT RegVT = VA.getLocVT();
1983      const TargetRegisterClass *RC;
1984      if (RegVT == MVT::i32)
1985        RC = &X86::GR32RegClass;
1986      else if (Is64Bit && RegVT == MVT::i64)
1987        RC = &X86::GR64RegClass;
1988      else if (RegVT == MVT::f32)
1989        RC = &X86::FR32RegClass;
1990      else if (RegVT == MVT::f64)
1991        RC = &X86::FR64RegClass;
1992      else if (RegVT.is256BitVector())
1993        RC = &X86::VR256RegClass;
1994      else if (RegVT.is128BitVector())
1995        RC = &X86::VR128RegClass;
1996      else if (RegVT == MVT::x86mmx)
1997        RC = &X86::VR64RegClass;
1998      else
1999        llvm_unreachable("Unknown argument type!");
2000
2001      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2002      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2003
2004      // If this is an 8 or 16-bit value, it is really passed promoted to 32
2005      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2006      // right size.
2007      if (VA.getLocInfo() == CCValAssign::SExt)
2008        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2009                               DAG.getValueType(VA.getValVT()));
2010      else if (VA.getLocInfo() == CCValAssign::ZExt)
2011        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2012                               DAG.getValueType(VA.getValVT()));
2013      else if (VA.getLocInfo() == CCValAssign::BCvt)
2014        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2015
2016      if (VA.isExtInLoc()) {
2017        // Handle MMX values passed in XMM regs.
2018        if (RegVT.isVector())
2019          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2020        else
2021          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2022      }
2023    } else {
2024      assert(VA.isMemLoc());
2025      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2026    }
2027
2028    // If value is passed via pointer - do a load.
2029    if (VA.getLocInfo() == CCValAssign::Indirect)
2030      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2031                             MachinePointerInfo(), false, false, false, 0);
2032
2033    InVals.push_back(ArgValue);
2034  }
2035
2036  // The x86-64 ABIs require that for returning structs by value we copy
2037  // the sret argument into %rax/%eax (depending on ABI) for the return.
2038  // Save the argument into a virtual register so that we can access it
2039  // from the return points.
2040  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2041    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2042    unsigned Reg = FuncInfo->getSRetReturnReg();
2043    if (!Reg) {
2044      MVT PtrTy = getPointerTy();
2045      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2046      FuncInfo->setSRetReturnReg(Reg);
2047    }
2048    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2049    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2050  }
2051
2052  unsigned StackSize = CCInfo.getNextStackOffset();
2053  // Align stack specially for tail calls.
2054  if (FuncIsMadeTailCallSafe(CallConv,
2055                             MF.getTarget().Options.GuaranteedTailCallOpt))
2056    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2057
2058  // If the function takes variable number of arguments, make a frame index for
2059  // the start of the first vararg value... for expansion of llvm.va_start.
2060  if (isVarArg) {
2061    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2062                    CallConv != CallingConv::X86_ThisCall)) {
2063      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2064    }
2065    if (Is64Bit) {
2066      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2067
2068      // FIXME: We should really autogenerate these arrays
2069      static const uint16_t GPR64ArgRegsWin64[] = {
2070        X86::RCX, X86::RDX, X86::R8,  X86::R9
2071      };
2072      static const uint16_t GPR64ArgRegs64Bit[] = {
2073        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2074      };
2075      static const uint16_t XMMArgRegs64Bit[] = {
2076        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2077        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2078      };
2079      const uint16_t *GPR64ArgRegs;
2080      unsigned NumXMMRegs = 0;
2081
2082      if (IsWin64) {
2083        // The XMM registers which might contain var arg parameters are shadowed
2084        // in their paired GPR.  So we only need to save the GPR to their home
2085        // slots.
2086        TotalNumIntRegs = 4;
2087        GPR64ArgRegs = GPR64ArgRegsWin64;
2088      } else {
2089        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2090        GPR64ArgRegs = GPR64ArgRegs64Bit;
2091
2092        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2093                                                TotalNumXMMRegs);
2094      }
2095      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2096                                                       TotalNumIntRegs);
2097
2098      bool NoImplicitFloatOps = Fn->getAttributes().
2099        hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2100      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2101             "SSE register cannot be used when SSE is disabled!");
2102      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2103               NoImplicitFloatOps) &&
2104             "SSE register cannot be used when SSE is disabled!");
2105      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2106          !Subtarget->hasSSE1())
2107        // Kernel mode asks for SSE to be disabled, so don't push them
2108        // on the stack.
2109        TotalNumXMMRegs = 0;
2110
2111      if (IsWin64) {
2112        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2113        // Get to the caller-allocated home save location.  Add 8 to account
2114        // for the return address.
2115        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2116        FuncInfo->setRegSaveFrameIndex(
2117          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2118        // Fixup to set vararg frame on shadow area (4 x i64).
2119        if (NumIntRegs < 4)
2120          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2121      } else {
2122        // For X86-64, if there are vararg parameters that are passed via
2123        // registers, then we must store them to their spots on the stack so
2124        // they may be loaded by deferencing the result of va_next.
2125        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2126        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2127        FuncInfo->setRegSaveFrameIndex(
2128          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2129                               false));
2130      }
2131
2132      // Store the integer parameter registers.
2133      SmallVector<SDValue, 8> MemOps;
2134      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2135                                        getPointerTy());
2136      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2137      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2138        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2139                                  DAG.getIntPtrConstant(Offset));
2140        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2141                                     &X86::GR64RegClass);
2142        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2143        SDValue Store =
2144          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2145                       MachinePointerInfo::getFixedStack(
2146                         FuncInfo->getRegSaveFrameIndex(), Offset),
2147                       false, false, 0);
2148        MemOps.push_back(Store);
2149        Offset += 8;
2150      }
2151
2152      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2153        // Now store the XMM (fp + vector) parameter registers.
2154        SmallVector<SDValue, 11> SaveXMMOps;
2155        SaveXMMOps.push_back(Chain);
2156
2157        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2158        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2159        SaveXMMOps.push_back(ALVal);
2160
2161        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2162                               FuncInfo->getRegSaveFrameIndex()));
2163        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2164                               FuncInfo->getVarArgsFPOffset()));
2165
2166        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2167          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2168                                       &X86::VR128RegClass);
2169          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2170          SaveXMMOps.push_back(Val);
2171        }
2172        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2173                                     MVT::Other,
2174                                     &SaveXMMOps[0], SaveXMMOps.size()));
2175      }
2176
2177      if (!MemOps.empty())
2178        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2179                            &MemOps[0], MemOps.size());
2180    }
2181  }
2182
2183  // Some CCs need callee pop.
2184  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2185                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2186    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2187  } else {
2188    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2189    // If this is an sret function, the return should pop the hidden pointer.
2190    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2191        argsAreStructReturn(Ins) == StackStructReturn)
2192      FuncInfo->setBytesToPopOnReturn(4);
2193  }
2194
2195  if (!Is64Bit) {
2196    // RegSaveFrameIndex is X86-64 only.
2197    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2198    if (CallConv == CallingConv::X86_FastCall ||
2199        CallConv == CallingConv::X86_ThisCall)
2200      // fastcc functions can't have varargs.
2201      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2202  }
2203
2204  FuncInfo->setArgumentStackSize(StackSize);
2205
2206  return Chain;
2207}
2208
2209SDValue
2210X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2211                                    SDValue StackPtr, SDValue Arg,
2212                                    DebugLoc dl, SelectionDAG &DAG,
2213                                    const CCValAssign &VA,
2214                                    ISD::ArgFlagsTy Flags) const {
2215  unsigned LocMemOffset = VA.getLocMemOffset();
2216  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2217  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2218  if (Flags.isByVal())
2219    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2220
2221  return DAG.getStore(Chain, dl, Arg, PtrOff,
2222                      MachinePointerInfo::getStack(LocMemOffset),
2223                      false, false, 0);
2224}
2225
2226/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2227/// optimization is performed and it is required.
2228SDValue
2229X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2230                                           SDValue &OutRetAddr, SDValue Chain,
2231                                           bool IsTailCall, bool Is64Bit,
2232                                           int FPDiff, DebugLoc dl) const {
2233  // Adjust the Return address stack slot.
2234  EVT VT = getPointerTy();
2235  OutRetAddr = getReturnAddressFrameIndex(DAG);
2236
2237  // Load the "old" Return address.
2238  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2239                           false, false, false, 0);
2240  return SDValue(OutRetAddr.getNode(), 1);
2241}
2242
2243/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2244/// optimization is performed and it is required (FPDiff!=0).
2245static SDValue
2246EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2247                         SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2248                         unsigned SlotSize, int FPDiff, DebugLoc dl) {
2249  // Store the return address to the appropriate stack slot.
2250  if (!FPDiff) return Chain;
2251  // Calculate the new stack slot for the return address.
2252  int NewReturnAddrFI =
2253    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2254  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2255  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2256                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2257                       false, false, 0);
2258  return Chain;
2259}
2260
2261SDValue
2262X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2263                             SmallVectorImpl<SDValue> &InVals) const {
2264  SelectionDAG &DAG                     = CLI.DAG;
2265  DebugLoc &dl                          = CLI.DL;
2266  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2267  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2268  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2269  SDValue Chain                         = CLI.Chain;
2270  SDValue Callee                        = CLI.Callee;
2271  CallingConv::ID CallConv              = CLI.CallConv;
2272  bool &isTailCall                      = CLI.IsTailCall;
2273  bool isVarArg                         = CLI.IsVarArg;
2274
2275  MachineFunction &MF = DAG.getMachineFunction();
2276  bool Is64Bit        = Subtarget->is64Bit();
2277  bool IsWin64        = Subtarget->isTargetWin64();
2278  bool IsWindows      = Subtarget->isTargetWindows();
2279  StructReturnType SR = callIsStructReturn(Outs);
2280  bool IsSibcall      = false;
2281
2282  if (MF.getTarget().Options.DisableTailCalls)
2283    isTailCall = false;
2284
2285  if (isTailCall) {
2286    // Check if it's really possible to do a tail call.
2287    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2288                    isVarArg, SR != NotStructReturn,
2289                    MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2290                    Outs, OutVals, Ins, DAG);
2291
2292    // Sibcalls are automatically detected tailcalls which do not require
2293    // ABI changes.
2294    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2295      IsSibcall = true;
2296
2297    if (isTailCall)
2298      ++NumTailCalls;
2299  }
2300
2301  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2302         "Var args not supported with calling convention fastcc, ghc or hipe");
2303
2304  // Analyze operands of the call, assigning locations to each operand.
2305  SmallVector<CCValAssign, 16> ArgLocs;
2306  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2307                 ArgLocs, *DAG.getContext());
2308
2309  // Allocate shadow area for Win64
2310  if (IsWin64) {
2311    CCInfo.AllocateStack(32, 8);
2312  }
2313
2314  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2315
2316  // Get a count of how many bytes are to be pushed on the stack.
2317  unsigned NumBytes = CCInfo.getNextStackOffset();
2318  if (IsSibcall)
2319    // This is a sibcall. The memory operands are available in caller's
2320    // own caller's stack.
2321    NumBytes = 0;
2322  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2323           IsTailCallConvention(CallConv))
2324    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2325
2326  int FPDiff = 0;
2327  if (isTailCall && !IsSibcall) {
2328    // Lower arguments at fp - stackoffset + fpdiff.
2329    X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2330    unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2331
2332    FPDiff = NumBytesCallerPushed - NumBytes;
2333
2334    // Set the delta of movement of the returnaddr stackslot.
2335    // But only set if delta is greater than previous delta.
2336    if (FPDiff < X86Info->getTCReturnAddrDelta())
2337      X86Info->setTCReturnAddrDelta(FPDiff);
2338  }
2339
2340  if (!IsSibcall)
2341    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2342
2343  SDValue RetAddrFrIdx;
2344  // Load return address for tail calls.
2345  if (isTailCall && FPDiff)
2346    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2347                                    Is64Bit, FPDiff, dl);
2348
2349  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2350  SmallVector<SDValue, 8> MemOpChains;
2351  SDValue StackPtr;
2352
2353  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2354  // of tail call optimization arguments are handle later.
2355  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2356    CCValAssign &VA = ArgLocs[i];
2357    EVT RegVT = VA.getLocVT();
2358    SDValue Arg = OutVals[i];
2359    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2360    bool isByVal = Flags.isByVal();
2361
2362    // Promote the value if needed.
2363    switch (VA.getLocInfo()) {
2364    default: llvm_unreachable("Unknown loc info!");
2365    case CCValAssign::Full: break;
2366    case CCValAssign::SExt:
2367      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2368      break;
2369    case CCValAssign::ZExt:
2370      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2371      break;
2372    case CCValAssign::AExt:
2373      if (RegVT.is128BitVector()) {
2374        // Special case: passing MMX values in XMM registers.
2375        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2376        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2377        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2378      } else
2379        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2380      break;
2381    case CCValAssign::BCvt:
2382      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2383      break;
2384    case CCValAssign::Indirect: {
2385      // Store the argument.
2386      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2387      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2388      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2389                           MachinePointerInfo::getFixedStack(FI),
2390                           false, false, 0);
2391      Arg = SpillSlot;
2392      break;
2393    }
2394    }
2395
2396    if (VA.isRegLoc()) {
2397      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2398      if (isVarArg && IsWin64) {
2399        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2400        // shadow reg if callee is a varargs function.
2401        unsigned ShadowReg = 0;
2402        switch (VA.getLocReg()) {
2403        case X86::XMM0: ShadowReg = X86::RCX; break;
2404        case X86::XMM1: ShadowReg = X86::RDX; break;
2405        case X86::XMM2: ShadowReg = X86::R8; break;
2406        case X86::XMM3: ShadowReg = X86::R9; break;
2407        }
2408        if (ShadowReg)
2409          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2410      }
2411    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2412      assert(VA.isMemLoc());
2413      if (StackPtr.getNode() == 0)
2414        StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2415                                      getPointerTy());
2416      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2417                                             dl, DAG, VA, Flags));
2418    }
2419  }
2420
2421  if (!MemOpChains.empty())
2422    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2423                        &MemOpChains[0], MemOpChains.size());
2424
2425  if (Subtarget->isPICStyleGOT()) {
2426    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2427    // GOT pointer.
2428    if (!isTailCall) {
2429      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2430               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2431    } else {
2432      // If we are tail calling and generating PIC/GOT style code load the
2433      // address of the callee into ECX. The value in ecx is used as target of
2434      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2435      // for tail calls on PIC/GOT architectures. Normally we would just put the
2436      // address of GOT into ebx and then call target@PLT. But for tail calls
2437      // ebx would be restored (since ebx is callee saved) before jumping to the
2438      // target@PLT.
2439
2440      // Note: The actual moving to ECX is done further down.
2441      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2442      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2443          !G->getGlobal()->hasProtectedVisibility())
2444        Callee = LowerGlobalAddress(Callee, DAG);
2445      else if (isa<ExternalSymbolSDNode>(Callee))
2446        Callee = LowerExternalSymbol(Callee, DAG);
2447    }
2448  }
2449
2450  if (Is64Bit && isVarArg && !IsWin64) {
2451    // From AMD64 ABI document:
2452    // For calls that may call functions that use varargs or stdargs
2453    // (prototype-less calls or calls to functions containing ellipsis (...) in
2454    // the declaration) %al is used as hidden argument to specify the number
2455    // of SSE registers used. The contents of %al do not need to match exactly
2456    // the number of registers, but must be an ubound on the number of SSE
2457    // registers used and is in the range 0 - 8 inclusive.
2458
2459    // Count the number of XMM registers allocated.
2460    static const uint16_t XMMArgRegs[] = {
2461      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2462      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2463    };
2464    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2465    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2466           && "SSE registers cannot be used when SSE is disabled");
2467
2468    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2469                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2470  }
2471
2472  // For tail calls lower the arguments to the 'real' stack slot.
2473  if (isTailCall) {
2474    // Force all the incoming stack arguments to be loaded from the stack
2475    // before any new outgoing arguments are stored to the stack, because the
2476    // outgoing stack slots may alias the incoming argument stack slots, and
2477    // the alias isn't otherwise explicit. This is slightly more conservative
2478    // than necessary, because it means that each store effectively depends
2479    // on every argument instead of just those arguments it would clobber.
2480    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2481
2482    SmallVector<SDValue, 8> MemOpChains2;
2483    SDValue FIN;
2484    int FI = 0;
2485    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2486      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2487        CCValAssign &VA = ArgLocs[i];
2488        if (VA.isRegLoc())
2489          continue;
2490        assert(VA.isMemLoc());
2491        SDValue Arg = OutVals[i];
2492        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2493        // Create frame index.
2494        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2495        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2496        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2497        FIN = DAG.getFrameIndex(FI, getPointerTy());
2498
2499        if (Flags.isByVal()) {
2500          // Copy relative to framepointer.
2501          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2502          if (StackPtr.getNode() == 0)
2503            StackPtr = DAG.getCopyFromReg(Chain, dl,
2504                                          RegInfo->getStackRegister(),
2505                                          getPointerTy());
2506          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2507
2508          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2509                                                           ArgChain,
2510                                                           Flags, DAG, dl));
2511        } else {
2512          // Store relative to framepointer.
2513          MemOpChains2.push_back(
2514            DAG.getStore(ArgChain, dl, Arg, FIN,
2515                         MachinePointerInfo::getFixedStack(FI),
2516                         false, false, 0));
2517        }
2518      }
2519    }
2520
2521    if (!MemOpChains2.empty())
2522      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2523                          &MemOpChains2[0], MemOpChains2.size());
2524
2525    // Store the return address to the appropriate stack slot.
2526    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2527                                     getPointerTy(), RegInfo->getSlotSize(),
2528                                     FPDiff, dl);
2529  }
2530
2531  // Build a sequence of copy-to-reg nodes chained together with token chain
2532  // and flag operands which copy the outgoing args into registers.
2533  SDValue InFlag;
2534  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2535    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2536                             RegsToPass[i].second, InFlag);
2537    InFlag = Chain.getValue(1);
2538  }
2539
2540  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2541    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2542    // In the 64-bit large code model, we have to make all calls
2543    // through a register, since the call instruction's 32-bit
2544    // pc-relative offset may not be large enough to hold the whole
2545    // address.
2546  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2547    // If the callee is a GlobalAddress node (quite common, every direct call
2548    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2549    // it.
2550
2551    // We should use extra load for direct calls to dllimported functions in
2552    // non-JIT mode.
2553    const GlobalValue *GV = G->getGlobal();
2554    if (!GV->hasDLLImportLinkage()) {
2555      unsigned char OpFlags = 0;
2556      bool ExtraLoad = false;
2557      unsigned WrapperKind = ISD::DELETED_NODE;
2558
2559      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2560      // external symbols most go through the PLT in PIC mode.  If the symbol
2561      // has hidden or protected visibility, or if it is static or local, then
2562      // we don't need to use the PLT - we can directly call it.
2563      if (Subtarget->isTargetELF() &&
2564          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2565          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2566        OpFlags = X86II::MO_PLT;
2567      } else if (Subtarget->isPICStyleStubAny() &&
2568                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2569                 (!Subtarget->getTargetTriple().isMacOSX() ||
2570                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2571        // PC-relative references to external symbols should go through $stub,
2572        // unless we're building with the leopard linker or later, which
2573        // automatically synthesizes these stubs.
2574        OpFlags = X86II::MO_DARWIN_STUB;
2575      } else if (Subtarget->isPICStyleRIPRel() &&
2576                 isa<Function>(GV) &&
2577                 cast<Function>(GV)->getAttributes().
2578                   hasAttribute(AttributeSet::FunctionIndex,
2579                                Attribute::NonLazyBind)) {
2580        // If the function is marked as non-lazy, generate an indirect call
2581        // which loads from the GOT directly. This avoids runtime overhead
2582        // at the cost of eager binding (and one extra byte of encoding).
2583        OpFlags = X86II::MO_GOTPCREL;
2584        WrapperKind = X86ISD::WrapperRIP;
2585        ExtraLoad = true;
2586      }
2587
2588      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2589                                          G->getOffset(), OpFlags);
2590
2591      // Add a wrapper if needed.
2592      if (WrapperKind != ISD::DELETED_NODE)
2593        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2594      // Add extra indirection if needed.
2595      if (ExtraLoad)
2596        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2597                             MachinePointerInfo::getGOT(),
2598                             false, false, false, 0);
2599    }
2600  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2601    unsigned char OpFlags = 0;
2602
2603    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2604    // external symbols should go through the PLT.
2605    if (Subtarget->isTargetELF() &&
2606        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2607      OpFlags = X86II::MO_PLT;
2608    } else if (Subtarget->isPICStyleStubAny() &&
2609               (!Subtarget->getTargetTriple().isMacOSX() ||
2610                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2611      // PC-relative references to external symbols should go through $stub,
2612      // unless we're building with the leopard linker or later, which
2613      // automatically synthesizes these stubs.
2614      OpFlags = X86II::MO_DARWIN_STUB;
2615    }
2616
2617    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2618                                         OpFlags);
2619  }
2620
2621  // Returns a chain & a flag for retval copy to use.
2622  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2623  SmallVector<SDValue, 8> Ops;
2624
2625  if (!IsSibcall && isTailCall) {
2626    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2627                           DAG.getIntPtrConstant(0, true), InFlag);
2628    InFlag = Chain.getValue(1);
2629  }
2630
2631  Ops.push_back(Chain);
2632  Ops.push_back(Callee);
2633
2634  if (isTailCall)
2635    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2636
2637  // Add argument registers to the end of the list so that they are known live
2638  // into the call.
2639  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2640    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2641                                  RegsToPass[i].second.getValueType()));
2642
2643  // Add a register mask operand representing the call-preserved registers.
2644  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2645  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2646  assert(Mask && "Missing call preserved mask for calling convention");
2647  Ops.push_back(DAG.getRegisterMask(Mask));
2648
2649  if (InFlag.getNode())
2650    Ops.push_back(InFlag);
2651
2652  if (isTailCall) {
2653    // We used to do:
2654    //// If this is the first return lowered for this function, add the regs
2655    //// to the liveout set for the function.
2656    // This isn't right, although it's probably harmless on x86; liveouts
2657    // should be computed from returns not tail calls.  Consider a void
2658    // function making a tail call to a function returning int.
2659    return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2660  }
2661
2662  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2663  InFlag = Chain.getValue(1);
2664
2665  // Create the CALLSEQ_END node.
2666  unsigned NumBytesForCalleeToPush;
2667  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2668                       getTargetMachine().Options.GuaranteedTailCallOpt))
2669    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2670  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2671           SR == StackStructReturn)
2672    // If this is a call to a struct-return function, the callee
2673    // pops the hidden struct pointer, so we have to push it back.
2674    // This is common for Darwin/X86, Linux & Mingw32 targets.
2675    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2676    NumBytesForCalleeToPush = 4;
2677  else
2678    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2679
2680  // Returns a flag for retval copy to use.
2681  if (!IsSibcall) {
2682    Chain = DAG.getCALLSEQ_END(Chain,
2683                               DAG.getIntPtrConstant(NumBytes, true),
2684                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2685                                                     true),
2686                               InFlag);
2687    InFlag = Chain.getValue(1);
2688  }
2689
2690  // Handle result values, copying them out of physregs into vregs that we
2691  // return.
2692  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2693                         Ins, dl, DAG, InVals);
2694}
2695
2696//===----------------------------------------------------------------------===//
2697//                Fast Calling Convention (tail call) implementation
2698//===----------------------------------------------------------------------===//
2699
2700//  Like std call, callee cleans arguments, convention except that ECX is
2701//  reserved for storing the tail called function address. Only 2 registers are
2702//  free for argument passing (inreg). Tail call optimization is performed
2703//  provided:
2704//                * tailcallopt is enabled
2705//                * caller/callee are fastcc
2706//  On X86_64 architecture with GOT-style position independent code only local
2707//  (within module) calls are supported at the moment.
2708//  To keep the stack aligned according to platform abi the function
2709//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2710//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2711//  If a tail called function callee has more arguments than the caller the
2712//  caller needs to make sure that there is room to move the RETADDR to. This is
2713//  achieved by reserving an area the size of the argument delta right after the
2714//  original REtADDR, but before the saved framepointer or the spilled registers
2715//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2716//  stack layout:
2717//    arg1
2718//    arg2
2719//    RETADDR
2720//    [ new RETADDR
2721//      move area ]
2722//    (possible EBP)
2723//    ESI
2724//    EDI
2725//    local1 ..
2726
2727/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2728/// for a 16 byte align requirement.
2729unsigned
2730X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2731                                               SelectionDAG& DAG) const {
2732  MachineFunction &MF = DAG.getMachineFunction();
2733  const TargetMachine &TM = MF.getTarget();
2734  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2735  unsigned StackAlignment = TFI.getStackAlignment();
2736  uint64_t AlignMask = StackAlignment - 1;
2737  int64_t Offset = StackSize;
2738  unsigned SlotSize = RegInfo->getSlotSize();
2739  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2740    // Number smaller than 12 so just add the difference.
2741    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2742  } else {
2743    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2744    Offset = ((~AlignMask) & Offset) + StackAlignment +
2745      (StackAlignment-SlotSize);
2746  }
2747  return Offset;
2748}
2749
2750/// MatchingStackOffset - Return true if the given stack call argument is
2751/// already available in the same position (relatively) of the caller's
2752/// incoming argument stack.
2753static
2754bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2755                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2756                         const X86InstrInfo *TII) {
2757  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2758  int FI = INT_MAX;
2759  if (Arg.getOpcode() == ISD::CopyFromReg) {
2760    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2761    if (!TargetRegisterInfo::isVirtualRegister(VR))
2762      return false;
2763    MachineInstr *Def = MRI->getVRegDef(VR);
2764    if (!Def)
2765      return false;
2766    if (!Flags.isByVal()) {
2767      if (!TII->isLoadFromStackSlot(Def, FI))
2768        return false;
2769    } else {
2770      unsigned Opcode = Def->getOpcode();
2771      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2772          Def->getOperand(1).isFI()) {
2773        FI = Def->getOperand(1).getIndex();
2774        Bytes = Flags.getByValSize();
2775      } else
2776        return false;
2777    }
2778  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2779    if (Flags.isByVal())
2780      // ByVal argument is passed in as a pointer but it's now being
2781      // dereferenced. e.g.
2782      // define @foo(%struct.X* %A) {
2783      //   tail call @bar(%struct.X* byval %A)
2784      // }
2785      return false;
2786    SDValue Ptr = Ld->getBasePtr();
2787    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2788    if (!FINode)
2789      return false;
2790    FI = FINode->getIndex();
2791  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2792    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2793    FI = FINode->getIndex();
2794    Bytes = Flags.getByValSize();
2795  } else
2796    return false;
2797
2798  assert(FI != INT_MAX);
2799  if (!MFI->isFixedObjectIndex(FI))
2800    return false;
2801  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2802}
2803
2804/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2805/// for tail call optimization. Targets which want to do tail call
2806/// optimization should implement this function.
2807bool
2808X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2809                                                     CallingConv::ID CalleeCC,
2810                                                     bool isVarArg,
2811                                                     bool isCalleeStructRet,
2812                                                     bool isCallerStructRet,
2813                                                     Type *RetTy,
2814                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2815                                    const SmallVectorImpl<SDValue> &OutVals,
2816                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2817                                                     SelectionDAG &DAG) const {
2818  if (!IsTailCallConvention(CalleeCC) &&
2819      CalleeCC != CallingConv::C)
2820    return false;
2821
2822  // If -tailcallopt is specified, make fastcc functions tail-callable.
2823  const MachineFunction &MF = DAG.getMachineFunction();
2824  const Function *CallerF = DAG.getMachineFunction().getFunction();
2825
2826  // If the function return type is x86_fp80 and the callee return type is not,
2827  // then the FP_EXTEND of the call result is not a nop. It's not safe to
2828  // perform a tailcall optimization here.
2829  if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2830    return false;
2831
2832  CallingConv::ID CallerCC = CallerF->getCallingConv();
2833  bool CCMatch = CallerCC == CalleeCC;
2834
2835  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2836    if (IsTailCallConvention(CalleeCC) && CCMatch)
2837      return true;
2838    return false;
2839  }
2840
2841  // Look for obvious safe cases to perform tail call optimization that do not
2842  // require ABI changes. This is what gcc calls sibcall.
2843
2844  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2845  // emit a special epilogue.
2846  if (RegInfo->needsStackRealignment(MF))
2847    return false;
2848
2849  // Also avoid sibcall optimization if either caller or callee uses struct
2850  // return semantics.
2851  if (isCalleeStructRet || isCallerStructRet)
2852    return false;
2853
2854  // An stdcall caller is expected to clean up its arguments; the callee
2855  // isn't going to do that.
2856  if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2857    return false;
2858
2859  // Do not sibcall optimize vararg calls unless all arguments are passed via
2860  // registers.
2861  if (isVarArg && !Outs.empty()) {
2862
2863    // Optimizing for varargs on Win64 is unlikely to be safe without
2864    // additional testing.
2865    if (Subtarget->isTargetWin64())
2866      return false;
2867
2868    SmallVector<CCValAssign, 16> ArgLocs;
2869    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2870                   getTargetMachine(), ArgLocs, *DAG.getContext());
2871
2872    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2873    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2874      if (!ArgLocs[i].isRegLoc())
2875        return false;
2876  }
2877
2878  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2879  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2880  // this into a sibcall.
2881  bool Unused = false;
2882  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2883    if (!Ins[i].Used) {
2884      Unused = true;
2885      break;
2886    }
2887  }
2888  if (Unused) {
2889    SmallVector<CCValAssign, 16> RVLocs;
2890    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2891                   getTargetMachine(), RVLocs, *DAG.getContext());
2892    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2893    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2894      CCValAssign &VA = RVLocs[i];
2895      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2896        return false;
2897    }
2898  }
2899
2900  // If the calling conventions do not match, then we'd better make sure the
2901  // results are returned in the same way as what the caller expects.
2902  if (!CCMatch) {
2903    SmallVector<CCValAssign, 16> RVLocs1;
2904    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2905                    getTargetMachine(), RVLocs1, *DAG.getContext());
2906    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2907
2908    SmallVector<CCValAssign, 16> RVLocs2;
2909    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2910                    getTargetMachine(), RVLocs2, *DAG.getContext());
2911    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2912
2913    if (RVLocs1.size() != RVLocs2.size())
2914      return false;
2915    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2916      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2917        return false;
2918      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2919        return false;
2920      if (RVLocs1[i].isRegLoc()) {
2921        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2922          return false;
2923      } else {
2924        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2925          return false;
2926      }
2927    }
2928  }
2929
2930  // If the callee takes no arguments then go on to check the results of the
2931  // call.
2932  if (!Outs.empty()) {
2933    // Check if stack adjustment is needed. For now, do not do this if any
2934    // argument is passed on the stack.
2935    SmallVector<CCValAssign, 16> ArgLocs;
2936    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2937                   getTargetMachine(), ArgLocs, *DAG.getContext());
2938
2939    // Allocate shadow area for Win64
2940    if (Subtarget->isTargetWin64()) {
2941      CCInfo.AllocateStack(32, 8);
2942    }
2943
2944    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2945    if (CCInfo.getNextStackOffset()) {
2946      MachineFunction &MF = DAG.getMachineFunction();
2947      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2948        return false;
2949
2950      // Check if the arguments are already laid out in the right way as
2951      // the caller's fixed stack objects.
2952      MachineFrameInfo *MFI = MF.getFrameInfo();
2953      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2954      const X86InstrInfo *TII =
2955        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2956      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2957        CCValAssign &VA = ArgLocs[i];
2958        SDValue Arg = OutVals[i];
2959        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2960        if (VA.getLocInfo() == CCValAssign::Indirect)
2961          return false;
2962        if (!VA.isRegLoc()) {
2963          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2964                                   MFI, MRI, TII))
2965            return false;
2966        }
2967      }
2968    }
2969
2970    // If the tailcall address may be in a register, then make sure it's
2971    // possible to register allocate for it. In 32-bit, the call address can
2972    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2973    // callee-saved registers are restored. These happen to be the same
2974    // registers used to pass 'inreg' arguments so watch out for those.
2975    if (!Subtarget->is64Bit() &&
2976        ((!isa<GlobalAddressSDNode>(Callee) &&
2977          !isa<ExternalSymbolSDNode>(Callee)) ||
2978         getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2979      unsigned NumInRegs = 0;
2980      // In PIC we need an extra register to formulate the address computation
2981      // for the callee.
2982      unsigned MaxInRegs =
2983          (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
2984
2985      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2986        CCValAssign &VA = ArgLocs[i];
2987        if (!VA.isRegLoc())
2988          continue;
2989        unsigned Reg = VA.getLocReg();
2990        switch (Reg) {
2991        default: break;
2992        case X86::EAX: case X86::EDX: case X86::ECX:
2993          if (++NumInRegs == MaxInRegs)
2994            return false;
2995          break;
2996        }
2997      }
2998    }
2999  }
3000
3001  return true;
3002}
3003
3004FastISel *
3005X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3006                                  const TargetLibraryInfo *libInfo) const {
3007  return X86::createFastISel(funcInfo, libInfo);
3008}
3009
3010//===----------------------------------------------------------------------===//
3011//                           Other Lowering Hooks
3012//===----------------------------------------------------------------------===//
3013
3014static bool MayFoldLoad(SDValue Op) {
3015  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3016}
3017
3018static bool MayFoldIntoStore(SDValue Op) {
3019  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3020}
3021
3022static bool isTargetShuffle(unsigned Opcode) {
3023  switch(Opcode) {
3024  default: return false;
3025  case X86ISD::PSHUFD:
3026  case X86ISD::PSHUFHW:
3027  case X86ISD::PSHUFLW:
3028  case X86ISD::SHUFP:
3029  case X86ISD::PALIGNR:
3030  case X86ISD::MOVLHPS:
3031  case X86ISD::MOVLHPD:
3032  case X86ISD::MOVHLPS:
3033  case X86ISD::MOVLPS:
3034  case X86ISD::MOVLPD:
3035  case X86ISD::MOVSHDUP:
3036  case X86ISD::MOVSLDUP:
3037  case X86ISD::MOVDDUP:
3038  case X86ISD::MOVSS:
3039  case X86ISD::MOVSD:
3040  case X86ISD::UNPCKL:
3041  case X86ISD::UNPCKH:
3042  case X86ISD::VPERMILP:
3043  case X86ISD::VPERM2X128:
3044  case X86ISD::VPERMI:
3045    return true;
3046  }
3047}
3048
3049static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3050                                    SDValue V1, SelectionDAG &DAG) {
3051  switch(Opc) {
3052  default: llvm_unreachable("Unknown x86 shuffle node");
3053  case X86ISD::MOVSHDUP:
3054  case X86ISD::MOVSLDUP:
3055  case X86ISD::MOVDDUP:
3056    return DAG.getNode(Opc, dl, VT, V1);
3057  }
3058}
3059
3060static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3061                                    SDValue V1, unsigned TargetMask,
3062                                    SelectionDAG &DAG) {
3063  switch(Opc) {
3064  default: llvm_unreachable("Unknown x86 shuffle node");
3065  case X86ISD::PSHUFD:
3066  case X86ISD::PSHUFHW:
3067  case X86ISD::PSHUFLW:
3068  case X86ISD::VPERMILP:
3069  case X86ISD::VPERMI:
3070    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3071  }
3072}
3073
3074static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3075                                    SDValue V1, SDValue V2, unsigned TargetMask,
3076                                    SelectionDAG &DAG) {
3077  switch(Opc) {
3078  default: llvm_unreachable("Unknown x86 shuffle node");
3079  case X86ISD::PALIGNR:
3080  case X86ISD::SHUFP:
3081  case X86ISD::VPERM2X128:
3082    return DAG.getNode(Opc, dl, VT, V1, V2,
3083                       DAG.getConstant(TargetMask, MVT::i8));
3084  }
3085}
3086
3087static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3088                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
3089  switch(Opc) {
3090  default: llvm_unreachable("Unknown x86 shuffle node");
3091  case X86ISD::MOVLHPS:
3092  case X86ISD::MOVLHPD:
3093  case X86ISD::MOVHLPS:
3094  case X86ISD::MOVLPS:
3095  case X86ISD::MOVLPD:
3096  case X86ISD::MOVSS:
3097  case X86ISD::MOVSD:
3098  case X86ISD::UNPCKL:
3099  case X86ISD::UNPCKH:
3100    return DAG.getNode(Opc, dl, VT, V1, V2);
3101  }
3102}
3103
3104SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3105  MachineFunction &MF = DAG.getMachineFunction();
3106  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3107  int ReturnAddrIndex = FuncInfo->getRAIndex();
3108
3109  if (ReturnAddrIndex == 0) {
3110    // Set up a frame object for the return address.
3111    unsigned SlotSize = RegInfo->getSlotSize();
3112    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3113                                                           false);
3114    FuncInfo->setRAIndex(ReturnAddrIndex);
3115  }
3116
3117  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3118}
3119
3120bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3121                                       bool hasSymbolicDisplacement) {
3122  // Offset should fit into 32 bit immediate field.
3123  if (!isInt<32>(Offset))
3124    return false;
3125
3126  // If we don't have a symbolic displacement - we don't have any extra
3127  // restrictions.
3128  if (!hasSymbolicDisplacement)
3129    return true;
3130
3131  // FIXME: Some tweaks might be needed for medium code model.
3132  if (M != CodeModel::Small && M != CodeModel::Kernel)
3133    return false;
3134
3135  // For small code model we assume that latest object is 16MB before end of 31
3136  // bits boundary. We may also accept pretty large negative constants knowing
3137  // that all objects are in the positive half of address space.
3138  if (M == CodeModel::Small && Offset < 16*1024*1024)
3139    return true;
3140
3141  // For kernel code model we know that all object resist in the negative half
3142  // of 32bits address space. We may not accept negative offsets, since they may
3143  // be just off and we may accept pretty large positive ones.
3144  if (M == CodeModel::Kernel && Offset > 0)
3145    return true;
3146
3147  return false;
3148}
3149
3150/// isCalleePop - Determines whether the callee is required to pop its
3151/// own arguments. Callee pop is necessary to support tail calls.
3152bool X86::isCalleePop(CallingConv::ID CallingConv,
3153                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3154  if (IsVarArg)
3155    return false;
3156
3157  switch (CallingConv) {
3158  default:
3159    return false;
3160  case CallingConv::X86_StdCall:
3161    return !is64Bit;
3162  case CallingConv::X86_FastCall:
3163    return !is64Bit;
3164  case CallingConv::X86_ThisCall:
3165    return !is64Bit;
3166  case CallingConv::Fast:
3167    return TailCallOpt;
3168  case CallingConv::GHC:
3169    return TailCallOpt;
3170  case CallingConv::HiPE:
3171    return TailCallOpt;
3172  }
3173}
3174
3175/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3176/// specific condition code, returning the condition code and the LHS/RHS of the
3177/// comparison to make.
3178static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3179                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3180  if (!isFP) {
3181    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3182      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3183        // X > -1   -> X == 0, jump !sign.
3184        RHS = DAG.getConstant(0, RHS.getValueType());
3185        return X86::COND_NS;
3186      }
3187      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3188        // X < 0   -> X == 0, jump on sign.
3189        return X86::COND_S;
3190      }
3191      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3192        // X < 1   -> X <= 0
3193        RHS = DAG.getConstant(0, RHS.getValueType());
3194        return X86::COND_LE;
3195      }
3196    }
3197
3198    switch (SetCCOpcode) {
3199    default: llvm_unreachable("Invalid integer condition!");
3200    case ISD::SETEQ:  return X86::COND_E;
3201    case ISD::SETGT:  return X86::COND_G;
3202    case ISD::SETGE:  return X86::COND_GE;
3203    case ISD::SETLT:  return X86::COND_L;
3204    case ISD::SETLE:  return X86::COND_LE;
3205    case ISD::SETNE:  return X86::COND_NE;
3206    case ISD::SETULT: return X86::COND_B;
3207    case ISD::SETUGT: return X86::COND_A;
3208    case ISD::SETULE: return X86::COND_BE;
3209    case ISD::SETUGE: return X86::COND_AE;
3210    }
3211  }
3212
3213  // First determine if it is required or is profitable to flip the operands.
3214
3215  // If LHS is a foldable load, but RHS is not, flip the condition.
3216  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3217      !ISD::isNON_EXTLoad(RHS.getNode())) {
3218    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3219    std::swap(LHS, RHS);
3220  }
3221
3222  switch (SetCCOpcode) {
3223  default: break;
3224  case ISD::SETOLT:
3225  case ISD::SETOLE:
3226  case ISD::SETUGT:
3227  case ISD::SETUGE:
3228    std::swap(LHS, RHS);
3229    break;
3230  }
3231
3232  // On a floating point condition, the flags are set as follows:
3233  // ZF  PF  CF   op
3234  //  0 | 0 | 0 | X > Y
3235  //  0 | 0 | 1 | X < Y
3236  //  1 | 0 | 0 | X == Y
3237  //  1 | 1 | 1 | unordered
3238  switch (SetCCOpcode) {
3239  default: llvm_unreachable("Condcode should be pre-legalized away");
3240  case ISD::SETUEQ:
3241  case ISD::SETEQ:   return X86::COND_E;
3242  case ISD::SETOLT:              // flipped
3243  case ISD::SETOGT:
3244  case ISD::SETGT:   return X86::COND_A;
3245  case ISD::SETOLE:              // flipped
3246  case ISD::SETOGE:
3247  case ISD::SETGE:   return X86::COND_AE;
3248  case ISD::SETUGT:              // flipped
3249  case ISD::SETULT:
3250  case ISD::SETLT:   return X86::COND_B;
3251  case ISD::SETUGE:              // flipped
3252  case ISD::SETULE:
3253  case ISD::SETLE:   return X86::COND_BE;
3254  case ISD::SETONE:
3255  case ISD::SETNE:   return X86::COND_NE;
3256  case ISD::SETUO:   return X86::COND_P;
3257  case ISD::SETO:    return X86::COND_NP;
3258  case ISD::SETOEQ:
3259  case ISD::SETUNE:  return X86::COND_INVALID;
3260  }
3261}
3262
3263/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3264/// code. Current x86 isa includes the following FP cmov instructions:
3265/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3266static bool hasFPCMov(unsigned X86CC) {
3267  switch (X86CC) {
3268  default:
3269    return false;
3270  case X86::COND_B:
3271  case X86::COND_BE:
3272  case X86::COND_E:
3273  case X86::COND_P:
3274  case X86::COND_A:
3275  case X86::COND_AE:
3276  case X86::COND_NE:
3277  case X86::COND_NP:
3278    return true;
3279  }
3280}
3281
3282/// isFPImmLegal - Returns true if the target can instruction select the
3283/// specified FP immediate natively. If false, the legalizer will
3284/// materialize the FP immediate as a load from a constant pool.
3285bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3286  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3287    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3288      return true;
3289  }
3290  return false;
3291}
3292
3293/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3294/// the specified range (L, H].
3295static bool isUndefOrInRange(int Val, int Low, int Hi) {
3296  return (Val < 0) || (Val >= Low && Val < Hi);
3297}
3298
3299/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3300/// specified value.
3301static bool isUndefOrEqual(int Val, int CmpVal) {
3302  return (Val < 0 || Val == CmpVal);
3303}
3304
3305/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3306/// from position Pos and ending in Pos+Size, falls within the specified
3307/// sequential range (L, L+Pos]. or is undef.
3308static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3309                                       unsigned Pos, unsigned Size, int Low) {
3310  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3311    if (!isUndefOrEqual(Mask[i], Low))
3312      return false;
3313  return true;
3314}
3315
3316/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3317/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3318/// the second operand.
3319static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3320  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3321    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3322  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3323    return (Mask[0] < 2 && Mask[1] < 2);
3324  return false;
3325}
3326
3327/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3328/// is suitable for input to PSHUFHW.
3329static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3330  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3331    return false;
3332
3333  // Lower quadword copied in order or undef.
3334  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3335    return false;
3336
3337  // Upper quadword shuffled.
3338  for (unsigned i = 4; i != 8; ++i)
3339    if (!isUndefOrInRange(Mask[i], 4, 8))
3340      return false;
3341
3342  if (VT == MVT::v16i16) {
3343    // Lower quadword copied in order or undef.
3344    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3345      return false;
3346
3347    // Upper quadword shuffled.
3348    for (unsigned i = 12; i != 16; ++i)
3349      if (!isUndefOrInRange(Mask[i], 12, 16))
3350        return false;
3351  }
3352
3353  return true;
3354}
3355
3356/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3357/// is suitable for input to PSHUFLW.
3358static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3359  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3360    return false;
3361
3362  // Upper quadword copied in order.
3363  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3364    return false;
3365
3366  // Lower quadword shuffled.
3367  for (unsigned i = 0; i != 4; ++i)
3368    if (!isUndefOrInRange(Mask[i], 0, 4))
3369      return false;
3370
3371  if (VT == MVT::v16i16) {
3372    // Upper quadword copied in order.
3373    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3374      return false;
3375
3376    // Lower quadword shuffled.
3377    for (unsigned i = 8; i != 12; ++i)
3378      if (!isUndefOrInRange(Mask[i], 8, 12))
3379        return false;
3380  }
3381
3382  return true;
3383}
3384
3385/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3386/// is suitable for input to PALIGNR.
3387static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3388                          const X86Subtarget *Subtarget) {
3389  if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3390      (VT.is256BitVector() && !Subtarget->hasInt256()))
3391    return false;
3392
3393  unsigned NumElts = VT.getVectorNumElements();
3394  unsigned NumLanes = VT.getSizeInBits()/128;
3395  unsigned NumLaneElts = NumElts/NumLanes;
3396
3397  // Do not handle 64-bit element shuffles with palignr.
3398  if (NumLaneElts == 2)
3399    return false;
3400
3401  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3402    unsigned i;
3403    for (i = 0; i != NumLaneElts; ++i) {
3404      if (Mask[i+l] >= 0)
3405        break;
3406    }
3407
3408    // Lane is all undef, go to next lane
3409    if (i == NumLaneElts)
3410      continue;
3411
3412    int Start = Mask[i+l];
3413
3414    // Make sure its in this lane in one of the sources
3415    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3416        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3417      return false;
3418
3419    // If not lane 0, then we must match lane 0
3420    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3421      return false;
3422
3423    // Correct second source to be contiguous with first source
3424    if (Start >= (int)NumElts)
3425      Start -= NumElts - NumLaneElts;
3426
3427    // Make sure we're shifting in the right direction.
3428    if (Start <= (int)(i+l))
3429      return false;
3430
3431    Start -= i;
3432
3433    // Check the rest of the elements to see if they are consecutive.
3434    for (++i; i != NumLaneElts; ++i) {
3435      int Idx = Mask[i+l];
3436
3437      // Make sure its in this lane
3438      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3439          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3440        return false;
3441
3442      // If not lane 0, then we must match lane 0
3443      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3444        return false;
3445
3446      if (Idx >= (int)NumElts)
3447        Idx -= NumElts - NumLaneElts;
3448
3449      if (!isUndefOrEqual(Idx, Start+i))
3450        return false;
3451
3452    }
3453  }
3454
3455  return true;
3456}
3457
3458/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3459/// the two vector operands have swapped position.
3460static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3461                                     unsigned NumElems) {
3462  for (unsigned i = 0; i != NumElems; ++i) {
3463    int idx = Mask[i];
3464    if (idx < 0)
3465      continue;
3466    else if (idx < (int)NumElems)
3467      Mask[i] = idx + NumElems;
3468    else
3469      Mask[i] = idx - NumElems;
3470  }
3471}
3472
3473/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3474/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3475/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3476/// reverse of what x86 shuffles want.
3477static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3478                        bool Commuted = false) {
3479  if (!HasFp256 && VT.is256BitVector())
3480    return false;
3481
3482  unsigned NumElems = VT.getVectorNumElements();
3483  unsigned NumLanes = VT.getSizeInBits()/128;
3484  unsigned NumLaneElems = NumElems/NumLanes;
3485
3486  if (NumLaneElems != 2 && NumLaneElems != 4)
3487    return false;
3488
3489  // VSHUFPSY divides the resulting vector into 4 chunks.
3490  // The sources are also splitted into 4 chunks, and each destination
3491  // chunk must come from a different source chunk.
3492  //
3493  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3494  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3495  //
3496  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3497  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3498  //
3499  // VSHUFPDY divides the resulting vector into 4 chunks.
3500  // The sources are also splitted into 4 chunks, and each destination
3501  // chunk must come from a different source chunk.
3502  //
3503  //  SRC1 =>      X3       X2       X1       X0
3504  //  SRC2 =>      Y3       Y2       Y1       Y0
3505  //
3506  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3507  //
3508  unsigned HalfLaneElems = NumLaneElems/2;
3509  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3510    for (unsigned i = 0; i != NumLaneElems; ++i) {
3511      int Idx = Mask[i+l];
3512      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3513      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3514        return false;
3515      // For VSHUFPSY, the mask of the second half must be the same as the
3516      // first but with the appropriate offsets. This works in the same way as
3517      // VPERMILPS works with masks.
3518      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3519        continue;
3520      if (!isUndefOrEqual(Idx, Mask[i]+l))
3521        return false;
3522    }
3523  }
3524
3525  return true;
3526}
3527
3528/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3529/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3530static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3531  if (!VT.is128BitVector())
3532    return false;
3533
3534  unsigned NumElems = VT.getVectorNumElements();
3535
3536  if (NumElems != 4)
3537    return false;
3538
3539  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3540  return isUndefOrEqual(Mask[0], 6) &&
3541         isUndefOrEqual(Mask[1], 7) &&
3542         isUndefOrEqual(Mask[2], 2) &&
3543         isUndefOrEqual(Mask[3], 3);
3544}
3545
3546/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3547/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3548/// <2, 3, 2, 3>
3549static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3550  if (!VT.is128BitVector())
3551    return false;
3552
3553  unsigned NumElems = VT.getVectorNumElements();
3554
3555  if (NumElems != 4)
3556    return false;
3557
3558  return isUndefOrEqual(Mask[0], 2) &&
3559         isUndefOrEqual(Mask[1], 3) &&
3560         isUndefOrEqual(Mask[2], 2) &&
3561         isUndefOrEqual(Mask[3], 3);
3562}
3563
3564/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3565/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3566static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3567  if (!VT.is128BitVector())
3568    return false;
3569
3570  unsigned NumElems = VT.getVectorNumElements();
3571
3572  if (NumElems != 2 && NumElems != 4)
3573    return false;
3574
3575  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3576    if (!isUndefOrEqual(Mask[i], i + NumElems))
3577      return false;
3578
3579  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3580    if (!isUndefOrEqual(Mask[i], i))
3581      return false;
3582
3583  return true;
3584}
3585
3586/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3587/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3588static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3589  if (!VT.is128BitVector())
3590    return false;
3591
3592  unsigned NumElems = VT.getVectorNumElements();
3593
3594  if (NumElems != 2 && NumElems != 4)
3595    return false;
3596
3597  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3598    if (!isUndefOrEqual(Mask[i], i))
3599      return false;
3600
3601  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3602    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3603      return false;
3604
3605  return true;
3606}
3607
3608//
3609// Some special combinations that can be optimized.
3610//
3611static
3612SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3613                               SelectionDAG &DAG) {
3614  MVT VT = SVOp->getValueType(0).getSimpleVT();
3615  DebugLoc dl = SVOp->getDebugLoc();
3616
3617  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3618    return SDValue();
3619
3620  ArrayRef<int> Mask = SVOp->getMask();
3621
3622  // These are the special masks that may be optimized.
3623  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3624  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3625  bool MatchEvenMask = true;
3626  bool MatchOddMask  = true;
3627  for (int i=0; i<8; ++i) {
3628    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3629      MatchEvenMask = false;
3630    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3631      MatchOddMask = false;
3632  }
3633
3634  if (!MatchEvenMask && !MatchOddMask)
3635    return SDValue();
3636
3637  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3638
3639  SDValue Op0 = SVOp->getOperand(0);
3640  SDValue Op1 = SVOp->getOperand(1);
3641
3642  if (MatchEvenMask) {
3643    // Shift the second operand right to 32 bits.
3644    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3645    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3646  } else {
3647    // Shift the first operand left to 32 bits.
3648    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3649    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3650  }
3651  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3652  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3653}
3654
3655/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3656/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3657static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3658                         bool HasInt256, bool V2IsSplat = false) {
3659  unsigned NumElts = VT.getVectorNumElements();
3660
3661  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3662         "Unsupported vector type for unpckh");
3663
3664  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3665      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3666    return false;
3667
3668  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3669  // independently on 128-bit lanes.
3670  unsigned NumLanes = VT.getSizeInBits()/128;
3671  unsigned NumLaneElts = NumElts/NumLanes;
3672
3673  for (unsigned l = 0; l != NumLanes; ++l) {
3674    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3675         i != (l+1)*NumLaneElts;
3676         i += 2, ++j) {
3677      int BitI  = Mask[i];
3678      int BitI1 = Mask[i+1];
3679      if (!isUndefOrEqual(BitI, j))
3680        return false;
3681      if (V2IsSplat) {
3682        if (!isUndefOrEqual(BitI1, NumElts))
3683          return false;
3684      } else {
3685        if (!isUndefOrEqual(BitI1, j + NumElts))
3686          return false;
3687      }
3688    }
3689  }
3690
3691  return true;
3692}
3693
3694/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3695/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3696static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3697                         bool HasInt256, bool V2IsSplat = false) {
3698  unsigned NumElts = VT.getVectorNumElements();
3699
3700  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3701         "Unsupported vector type for unpckh");
3702
3703  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3704      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3705    return false;
3706
3707  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3708  // independently on 128-bit lanes.
3709  unsigned NumLanes = VT.getSizeInBits()/128;
3710  unsigned NumLaneElts = NumElts/NumLanes;
3711
3712  for (unsigned l = 0; l != NumLanes; ++l) {
3713    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3714         i != (l+1)*NumLaneElts; i += 2, ++j) {
3715      int BitI  = Mask[i];
3716      int BitI1 = Mask[i+1];
3717      if (!isUndefOrEqual(BitI, j))
3718        return false;
3719      if (V2IsSplat) {
3720        if (isUndefOrEqual(BitI1, NumElts))
3721          return false;
3722      } else {
3723        if (!isUndefOrEqual(BitI1, j+NumElts))
3724          return false;
3725      }
3726    }
3727  }
3728  return true;
3729}
3730
3731/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3732/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3733/// <0, 0, 1, 1>
3734static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3735  unsigned NumElts = VT.getVectorNumElements();
3736  bool Is256BitVec = VT.is256BitVector();
3737
3738  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3739         "Unsupported vector type for unpckh");
3740
3741  if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3742      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3743    return false;
3744
3745  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3746  // FIXME: Need a better way to get rid of this, there's no latency difference
3747  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3748  // the former later. We should also remove the "_undef" special mask.
3749  if (NumElts == 4 && Is256BitVec)
3750    return false;
3751
3752  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3753  // independently on 128-bit lanes.
3754  unsigned NumLanes = VT.getSizeInBits()/128;
3755  unsigned NumLaneElts = NumElts/NumLanes;
3756
3757  for (unsigned l = 0; l != NumLanes; ++l) {
3758    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3759         i != (l+1)*NumLaneElts;
3760         i += 2, ++j) {
3761      int BitI  = Mask[i];
3762      int BitI1 = Mask[i+1];
3763
3764      if (!isUndefOrEqual(BitI, j))
3765        return false;
3766      if (!isUndefOrEqual(BitI1, j))
3767        return false;
3768    }
3769  }
3770
3771  return true;
3772}
3773
3774/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3775/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3776/// <2, 2, 3, 3>
3777static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3778  unsigned NumElts = VT.getVectorNumElements();
3779
3780  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3781         "Unsupported vector type for unpckh");
3782
3783  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3784      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3785    return false;
3786
3787  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3788  // independently on 128-bit lanes.
3789  unsigned NumLanes = VT.getSizeInBits()/128;
3790  unsigned NumLaneElts = NumElts/NumLanes;
3791
3792  for (unsigned l = 0; l != NumLanes; ++l) {
3793    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3794         i != (l+1)*NumLaneElts; i += 2, ++j) {
3795      int BitI  = Mask[i];
3796      int BitI1 = Mask[i+1];
3797      if (!isUndefOrEqual(BitI, j))
3798        return false;
3799      if (!isUndefOrEqual(BitI1, j))
3800        return false;
3801    }
3802  }
3803  return true;
3804}
3805
3806/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3807/// specifies a shuffle of elements that is suitable for input to MOVSS,
3808/// MOVSD, and MOVD, i.e. setting the lowest element.
3809static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3810  if (VT.getVectorElementType().getSizeInBits() < 32)
3811    return false;
3812  if (!VT.is128BitVector())
3813    return false;
3814
3815  unsigned NumElts = VT.getVectorNumElements();
3816
3817  if (!isUndefOrEqual(Mask[0], NumElts))
3818    return false;
3819
3820  for (unsigned i = 1; i != NumElts; ++i)
3821    if (!isUndefOrEqual(Mask[i], i))
3822      return false;
3823
3824  return true;
3825}
3826
3827/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3828/// as permutations between 128-bit chunks or halves. As an example: this
3829/// shuffle bellow:
3830///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3831/// The first half comes from the second half of V1 and the second half from the
3832/// the second half of V2.
3833static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3834  if (!HasFp256 || !VT.is256BitVector())
3835    return false;
3836
3837  // The shuffle result is divided into half A and half B. In total the two
3838  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3839  // B must come from C, D, E or F.
3840  unsigned HalfSize = VT.getVectorNumElements()/2;
3841  bool MatchA = false, MatchB = false;
3842
3843  // Check if A comes from one of C, D, E, F.
3844  for (unsigned Half = 0; Half != 4; ++Half) {
3845    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3846      MatchA = true;
3847      break;
3848    }
3849  }
3850
3851  // Check if B comes from one of C, D, E, F.
3852  for (unsigned Half = 0; Half != 4; ++Half) {
3853    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3854      MatchB = true;
3855      break;
3856    }
3857  }
3858
3859  return MatchA && MatchB;
3860}
3861
3862/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3863/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3864static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3865  MVT VT = SVOp->getValueType(0).getSimpleVT();
3866
3867  unsigned HalfSize = VT.getVectorNumElements()/2;
3868
3869  unsigned FstHalf = 0, SndHalf = 0;
3870  for (unsigned i = 0; i < HalfSize; ++i) {
3871    if (SVOp->getMaskElt(i) > 0) {
3872      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3873      break;
3874    }
3875  }
3876  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3877    if (SVOp->getMaskElt(i) > 0) {
3878      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3879      break;
3880    }
3881  }
3882
3883  return (FstHalf | (SndHalf << 4));
3884}
3885
3886/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3887/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3888/// Note that VPERMIL mask matching is different depending whether theunderlying
3889/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3890/// to the same elements of the low, but to the higher half of the source.
3891/// In VPERMILPD the two lanes could be shuffled independently of each other
3892/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3893static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3894  if (!HasFp256)
3895    return false;
3896
3897  unsigned NumElts = VT.getVectorNumElements();
3898  // Only match 256-bit with 32/64-bit types
3899  if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3900    return false;
3901
3902  unsigned NumLanes = VT.getSizeInBits()/128;
3903  unsigned LaneSize = NumElts/NumLanes;
3904  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3905    for (unsigned i = 0; i != LaneSize; ++i) {
3906      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3907        return false;
3908      if (NumElts != 8 || l == 0)
3909        continue;
3910      // VPERMILPS handling
3911      if (Mask[i] < 0)
3912        continue;
3913      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3914        return false;
3915    }
3916  }
3917
3918  return true;
3919}
3920
3921/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3922/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3923/// element of vector 2 and the other elements to come from vector 1 in order.
3924static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3925                               bool V2IsSplat = false, bool V2IsUndef = false) {
3926  if (!VT.is128BitVector())
3927    return false;
3928
3929  unsigned NumOps = VT.getVectorNumElements();
3930  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3931    return false;
3932
3933  if (!isUndefOrEqual(Mask[0], 0))
3934    return false;
3935
3936  for (unsigned i = 1; i != NumOps; ++i)
3937    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3938          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3939          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3940      return false;
3941
3942  return true;
3943}
3944
3945/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3946/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3947/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3948static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3949                           const X86Subtarget *Subtarget) {
3950  if (!Subtarget->hasSSE3())
3951    return false;
3952
3953  unsigned NumElems = VT.getVectorNumElements();
3954
3955  if ((VT.is128BitVector() && NumElems != 4) ||
3956      (VT.is256BitVector() && NumElems != 8))
3957    return false;
3958
3959  // "i+1" is the value the indexed mask element must have
3960  for (unsigned i = 0; i != NumElems; i += 2)
3961    if (!isUndefOrEqual(Mask[i], i+1) ||
3962        !isUndefOrEqual(Mask[i+1], i+1))
3963      return false;
3964
3965  return true;
3966}
3967
3968/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3969/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3970/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3971static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3972                           const X86Subtarget *Subtarget) {
3973  if (!Subtarget->hasSSE3())
3974    return false;
3975
3976  unsigned NumElems = VT.getVectorNumElements();
3977
3978  if ((VT.is128BitVector() && NumElems != 4) ||
3979      (VT.is256BitVector() && NumElems != 8))
3980    return false;
3981
3982  // "i" is the value the indexed mask element must have
3983  for (unsigned i = 0; i != NumElems; i += 2)
3984    if (!isUndefOrEqual(Mask[i], i) ||
3985        !isUndefOrEqual(Mask[i+1], i))
3986      return false;
3987
3988  return true;
3989}
3990
3991/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3992/// specifies a shuffle of elements that is suitable for input to 256-bit
3993/// version of MOVDDUP.
3994static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3995  if (!HasFp256 || !VT.is256BitVector())
3996    return false;
3997
3998  unsigned NumElts = VT.getVectorNumElements();
3999  if (NumElts != 4)
4000    return false;
4001
4002  for (unsigned i = 0; i != NumElts/2; ++i)
4003    if (!isUndefOrEqual(Mask[i], 0))
4004      return false;
4005  for (unsigned i = NumElts/2; i != NumElts; ++i)
4006    if (!isUndefOrEqual(Mask[i], NumElts/2))
4007      return false;
4008  return true;
4009}
4010
4011/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4012/// specifies a shuffle of elements that is suitable for input to 128-bit
4013/// version of MOVDDUP.
4014static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4015  if (!VT.is128BitVector())
4016    return false;
4017
4018  unsigned e = VT.getVectorNumElements() / 2;
4019  for (unsigned i = 0; i != e; ++i)
4020    if (!isUndefOrEqual(Mask[i], i))
4021      return false;
4022  for (unsigned i = 0; i != e; ++i)
4023    if (!isUndefOrEqual(Mask[e+i], i))
4024      return false;
4025  return true;
4026}
4027
4028/// isVEXTRACTF128Index - Return true if the specified
4029/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4030/// suitable for input to VEXTRACTF128.
4031bool X86::isVEXTRACTF128Index(SDNode *N) {
4032  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4033    return false;
4034
4035  // The index should be aligned on a 128-bit boundary.
4036  uint64_t Index =
4037    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4038
4039  MVT VT = N->getValueType(0).getSimpleVT();
4040  unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4041  bool Result = (Index * ElSize) % 128 == 0;
4042
4043  return Result;
4044}
4045
4046/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4047/// operand specifies a subvector insert that is suitable for input to
4048/// VINSERTF128.
4049bool X86::isVINSERTF128Index(SDNode *N) {
4050  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4051    return false;
4052
4053  // The index should be aligned on a 128-bit boundary.
4054  uint64_t Index =
4055    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4056
4057  MVT VT = N->getValueType(0).getSimpleVT();
4058  unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4059  bool Result = (Index * ElSize) % 128 == 0;
4060
4061  return Result;
4062}
4063
4064/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4065/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4066/// Handles 128-bit and 256-bit.
4067static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4068  MVT VT = N->getValueType(0).getSimpleVT();
4069
4070  assert((VT.is128BitVector() || VT.is256BitVector()) &&
4071         "Unsupported vector type for PSHUF/SHUFP");
4072
4073  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4074  // independently on 128-bit lanes.
4075  unsigned NumElts = VT.getVectorNumElements();
4076  unsigned NumLanes = VT.getSizeInBits()/128;
4077  unsigned NumLaneElts = NumElts/NumLanes;
4078
4079  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4080         "Only supports 2 or 4 elements per lane");
4081
4082  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4083  unsigned Mask = 0;
4084  for (unsigned i = 0; i != NumElts; ++i) {
4085    int Elt = N->getMaskElt(i);
4086    if (Elt < 0) continue;
4087    Elt &= NumLaneElts - 1;
4088    unsigned ShAmt = (i << Shift) % 8;
4089    Mask |= Elt << ShAmt;
4090  }
4091
4092  return Mask;
4093}
4094
4095/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4096/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4097static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4098  MVT VT = N->getValueType(0).getSimpleVT();
4099
4100  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4101         "Unsupported vector type for PSHUFHW");
4102
4103  unsigned NumElts = VT.getVectorNumElements();
4104
4105  unsigned Mask = 0;
4106  for (unsigned l = 0; l != NumElts; l += 8) {
4107    // 8 nodes per lane, but we only care about the last 4.
4108    for (unsigned i = 0; i < 4; ++i) {
4109      int Elt = N->getMaskElt(l+i+4);
4110      if (Elt < 0) continue;
4111      Elt &= 0x3; // only 2-bits.
4112      Mask |= Elt << (i * 2);
4113    }
4114  }
4115
4116  return Mask;
4117}
4118
4119/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4120/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4121static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4122  MVT VT = N->getValueType(0).getSimpleVT();
4123
4124  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4125         "Unsupported vector type for PSHUFHW");
4126
4127  unsigned NumElts = VT.getVectorNumElements();
4128
4129  unsigned Mask = 0;
4130  for (unsigned l = 0; l != NumElts; l += 8) {
4131    // 8 nodes per lane, but we only care about the first 4.
4132    for (unsigned i = 0; i < 4; ++i) {
4133      int Elt = N->getMaskElt(l+i);
4134      if (Elt < 0) continue;
4135      Elt &= 0x3; // only 2-bits
4136      Mask |= Elt << (i * 2);
4137    }
4138  }
4139
4140  return Mask;
4141}
4142
4143/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4144/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4145static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4146  MVT VT = SVOp->getValueType(0).getSimpleVT();
4147  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4148
4149  unsigned NumElts = VT.getVectorNumElements();
4150  unsigned NumLanes = VT.getSizeInBits()/128;
4151  unsigned NumLaneElts = NumElts/NumLanes;
4152
4153  int Val = 0;
4154  unsigned i;
4155  for (i = 0; i != NumElts; ++i) {
4156    Val = SVOp->getMaskElt(i);
4157    if (Val >= 0)
4158      break;
4159  }
4160  if (Val >= (int)NumElts)
4161    Val -= NumElts - NumLaneElts;
4162
4163  assert(Val - i > 0 && "PALIGNR imm should be positive");
4164  return (Val - i) * EltSize;
4165}
4166
4167/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4168/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4169/// instructions.
4170unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4171  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4172    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4173
4174  uint64_t Index =
4175    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4176
4177  MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4178  MVT ElVT = VecVT.getVectorElementType();
4179
4180  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4181  return Index / NumElemsPerChunk;
4182}
4183
4184/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4185/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4186/// instructions.
4187unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4188  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4189    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4190
4191  uint64_t Index =
4192    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4193
4194  MVT VecVT = N->getValueType(0).getSimpleVT();
4195  MVT ElVT = VecVT.getVectorElementType();
4196
4197  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4198  return Index / NumElemsPerChunk;
4199}
4200
4201/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4202/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4203/// Handles 256-bit.
4204static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4205  MVT VT = N->getValueType(0).getSimpleVT();
4206
4207  unsigned NumElts = VT.getVectorNumElements();
4208
4209  assert((VT.is256BitVector() && NumElts == 4) &&
4210         "Unsupported vector type for VPERMQ/VPERMPD");
4211
4212  unsigned Mask = 0;
4213  for (unsigned i = 0; i != NumElts; ++i) {
4214    int Elt = N->getMaskElt(i);
4215    if (Elt < 0)
4216      continue;
4217    Mask |= Elt << (i*2);
4218  }
4219
4220  return Mask;
4221}
4222/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4223/// constant +0.0.
4224bool X86::isZeroNode(SDValue Elt) {
4225  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4226    return CN->isNullValue();
4227  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4228    return CFP->getValueAPF().isPosZero();
4229  return false;
4230}
4231
4232/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4233/// their permute mask.
4234static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4235                                    SelectionDAG &DAG) {
4236  MVT VT = SVOp->getValueType(0).getSimpleVT();
4237  unsigned NumElems = VT.getVectorNumElements();
4238  SmallVector<int, 8> MaskVec;
4239
4240  for (unsigned i = 0; i != NumElems; ++i) {
4241    int Idx = SVOp->getMaskElt(i);
4242    if (Idx >= 0) {
4243      if (Idx < (int)NumElems)
4244        Idx += NumElems;
4245      else
4246        Idx -= NumElems;
4247    }
4248    MaskVec.push_back(Idx);
4249  }
4250  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4251                              SVOp->getOperand(0), &MaskVec[0]);
4252}
4253
4254/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4255/// match movhlps. The lower half elements should come from upper half of
4256/// V1 (and in order), and the upper half elements should come from the upper
4257/// half of V2 (and in order).
4258static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4259  if (!VT.is128BitVector())
4260    return false;
4261  if (VT.getVectorNumElements() != 4)
4262    return false;
4263  for (unsigned i = 0, e = 2; i != e; ++i)
4264    if (!isUndefOrEqual(Mask[i], i+2))
4265      return false;
4266  for (unsigned i = 2; i != 4; ++i)
4267    if (!isUndefOrEqual(Mask[i], i+4))
4268      return false;
4269  return true;
4270}
4271
4272/// isScalarLoadToVector - Returns true if the node is a scalar load that
4273/// is promoted to a vector. It also returns the LoadSDNode by reference if
4274/// required.
4275static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4276  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4277    return false;
4278  N = N->getOperand(0).getNode();
4279  if (!ISD::isNON_EXTLoad(N))
4280    return false;
4281  if (LD)
4282    *LD = cast<LoadSDNode>(N);
4283  return true;
4284}
4285
4286// Test whether the given value is a vector value which will be legalized
4287// into a load.
4288static bool WillBeConstantPoolLoad(SDNode *N) {
4289  if (N->getOpcode() != ISD::BUILD_VECTOR)
4290    return false;
4291
4292  // Check for any non-constant elements.
4293  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4294    switch (N->getOperand(i).getNode()->getOpcode()) {
4295    case ISD::UNDEF:
4296    case ISD::ConstantFP:
4297    case ISD::Constant:
4298      break;
4299    default:
4300      return false;
4301    }
4302
4303  // Vectors of all-zeros and all-ones are materialized with special
4304  // instructions rather than being loaded.
4305  return !ISD::isBuildVectorAllZeros(N) &&
4306         !ISD::isBuildVectorAllOnes(N);
4307}
4308
4309/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4310/// match movlp{s|d}. The lower half elements should come from lower half of
4311/// V1 (and in order), and the upper half elements should come from the upper
4312/// half of V2 (and in order). And since V1 will become the source of the
4313/// MOVLP, it must be either a vector load or a scalar load to vector.
4314static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4315                               ArrayRef<int> Mask, EVT VT) {
4316  if (!VT.is128BitVector())
4317    return false;
4318
4319  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4320    return false;
4321  // Is V2 is a vector load, don't do this transformation. We will try to use
4322  // load folding shufps op.
4323  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4324    return false;
4325
4326  unsigned NumElems = VT.getVectorNumElements();
4327
4328  if (NumElems != 2 && NumElems != 4)
4329    return false;
4330  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4331    if (!isUndefOrEqual(Mask[i], i))
4332      return false;
4333  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4334    if (!isUndefOrEqual(Mask[i], i+NumElems))
4335      return false;
4336  return true;
4337}
4338
4339/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4340/// all the same.
4341static bool isSplatVector(SDNode *N) {
4342  if (N->getOpcode() != ISD::BUILD_VECTOR)
4343    return false;
4344
4345  SDValue SplatValue = N->getOperand(0);
4346  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4347    if (N->getOperand(i) != SplatValue)
4348      return false;
4349  return true;
4350}
4351
4352/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4353/// to an zero vector.
4354/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4355static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4356  SDValue V1 = N->getOperand(0);
4357  SDValue V2 = N->getOperand(1);
4358  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4359  for (unsigned i = 0; i != NumElems; ++i) {
4360    int Idx = N->getMaskElt(i);
4361    if (Idx >= (int)NumElems) {
4362      unsigned Opc = V2.getOpcode();
4363      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4364        continue;
4365      if (Opc != ISD::BUILD_VECTOR ||
4366          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4367        return false;
4368    } else if (Idx >= 0) {
4369      unsigned Opc = V1.getOpcode();
4370      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4371        continue;
4372      if (Opc != ISD::BUILD_VECTOR ||
4373          !X86::isZeroNode(V1.getOperand(Idx)))
4374        return false;
4375    }
4376  }
4377  return true;
4378}
4379
4380/// getZeroVector - Returns a vector of specified type with all zero elements.
4381///
4382static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4383                             SelectionDAG &DAG, DebugLoc dl) {
4384  assert(VT.isVector() && "Expected a vector type");
4385
4386  // Always build SSE zero vectors as <4 x i32> bitcasted
4387  // to their dest type. This ensures they get CSE'd.
4388  SDValue Vec;
4389  if (VT.is128BitVector()) {  // SSE
4390    if (Subtarget->hasSSE2()) {  // SSE2
4391      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4392      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4393    } else { // SSE1
4394      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4395      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4396    }
4397  } else if (VT.is256BitVector()) { // AVX
4398    if (Subtarget->hasInt256()) { // AVX2
4399      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4400      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4401      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4402    } else {
4403      // 256-bit logic and arithmetic instructions in AVX are all
4404      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4405      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4406      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4407      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4408    }
4409  } else
4410    llvm_unreachable("Unexpected vector type");
4411
4412  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4413}
4414
4415/// getOnesVector - Returns a vector of specified type with all bits set.
4416/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4417/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4418/// Then bitcast to their original type, ensuring they get CSE'd.
4419static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4420                             DebugLoc dl) {
4421  assert(VT.isVector() && "Expected a vector type");
4422
4423  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4424  SDValue Vec;
4425  if (VT.is256BitVector()) {
4426    if (HasInt256) { // AVX2
4427      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4428      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4429    } else { // AVX
4430      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4431      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4432    }
4433  } else if (VT.is128BitVector()) {
4434    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4435  } else
4436    llvm_unreachable("Unexpected vector type");
4437
4438  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4439}
4440
4441/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4442/// that point to V2 points to its first element.
4443static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4444  for (unsigned i = 0; i != NumElems; ++i) {
4445    if (Mask[i] > (int)NumElems) {
4446      Mask[i] = NumElems;
4447    }
4448  }
4449}
4450
4451/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4452/// operation of specified width.
4453static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4454                       SDValue V2) {
4455  unsigned NumElems = VT.getVectorNumElements();
4456  SmallVector<int, 8> Mask;
4457  Mask.push_back(NumElems);
4458  for (unsigned i = 1; i != NumElems; ++i)
4459    Mask.push_back(i);
4460  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4461}
4462
4463/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4464static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4465                          SDValue V2) {
4466  unsigned NumElems = VT.getVectorNumElements();
4467  SmallVector<int, 8> Mask;
4468  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4469    Mask.push_back(i);
4470    Mask.push_back(i + NumElems);
4471  }
4472  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4473}
4474
4475/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4476static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4477                          SDValue V2) {
4478  unsigned NumElems = VT.getVectorNumElements();
4479  SmallVector<int, 8> Mask;
4480  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4481    Mask.push_back(i + Half);
4482    Mask.push_back(i + NumElems + Half);
4483  }
4484  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4485}
4486
4487// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4488// a generic shuffle instruction because the target has no such instructions.
4489// Generate shuffles which repeat i16 and i8 several times until they can be
4490// represented by v4f32 and then be manipulated by target suported shuffles.
4491static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4492  EVT VT = V.getValueType();
4493  int NumElems = VT.getVectorNumElements();
4494  DebugLoc dl = V.getDebugLoc();
4495
4496  while (NumElems > 4) {
4497    if (EltNo < NumElems/2) {
4498      V = getUnpackl(DAG, dl, VT, V, V);
4499    } else {
4500      V = getUnpackh(DAG, dl, VT, V, V);
4501      EltNo -= NumElems/2;
4502    }
4503    NumElems >>= 1;
4504  }
4505  return V;
4506}
4507
4508/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4509static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4510  EVT VT = V.getValueType();
4511  DebugLoc dl = V.getDebugLoc();
4512
4513  if (VT.is128BitVector()) {
4514    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4515    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4516    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4517                             &SplatMask[0]);
4518  } else if (VT.is256BitVector()) {
4519    // To use VPERMILPS to splat scalars, the second half of indicies must
4520    // refer to the higher part, which is a duplication of the lower one,
4521    // because VPERMILPS can only handle in-lane permutations.
4522    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4523                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4524
4525    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4526    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4527                             &SplatMask[0]);
4528  } else
4529    llvm_unreachable("Vector size not supported");
4530
4531  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4532}
4533
4534/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4535static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4536  EVT SrcVT = SV->getValueType(0);
4537  SDValue V1 = SV->getOperand(0);
4538  DebugLoc dl = SV->getDebugLoc();
4539
4540  int EltNo = SV->getSplatIndex();
4541  int NumElems = SrcVT.getVectorNumElements();
4542  bool Is256BitVec = SrcVT.is256BitVector();
4543
4544  assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4545         "Unknown how to promote splat for type");
4546
4547  // Extract the 128-bit part containing the splat element and update
4548  // the splat element index when it refers to the higher register.
4549  if (Is256BitVec) {
4550    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4551    if (EltNo >= NumElems/2)
4552      EltNo -= NumElems/2;
4553  }
4554
4555  // All i16 and i8 vector types can't be used directly by a generic shuffle
4556  // instruction because the target has no such instruction. Generate shuffles
4557  // which repeat i16 and i8 several times until they fit in i32, and then can
4558  // be manipulated by target suported shuffles.
4559  EVT EltVT = SrcVT.getVectorElementType();
4560  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4561    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4562
4563  // Recreate the 256-bit vector and place the same 128-bit vector
4564  // into the low and high part. This is necessary because we want
4565  // to use VPERM* to shuffle the vectors
4566  if (Is256BitVec) {
4567    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4568  }
4569
4570  return getLegalSplat(DAG, V1, EltNo);
4571}
4572
4573/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4574/// vector of zero or undef vector.  This produces a shuffle where the low
4575/// element of V2 is swizzled into the zero/undef vector, landing at element
4576/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4577static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4578                                           bool IsZero,
4579                                           const X86Subtarget *Subtarget,
4580                                           SelectionDAG &DAG) {
4581  EVT VT = V2.getValueType();
4582  SDValue V1 = IsZero
4583    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4584  unsigned NumElems = VT.getVectorNumElements();
4585  SmallVector<int, 16> MaskVec;
4586  for (unsigned i = 0; i != NumElems; ++i)
4587    // If this is the insertion idx, put the low elt of V2 here.
4588    MaskVec.push_back(i == Idx ? NumElems : i);
4589  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4590}
4591
4592/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4593/// target specific opcode. Returns true if the Mask could be calculated.
4594/// Sets IsUnary to true if only uses one source.
4595static bool getTargetShuffleMask(SDNode *N, MVT VT,
4596                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4597  unsigned NumElems = VT.getVectorNumElements();
4598  SDValue ImmN;
4599
4600  IsUnary = false;
4601  switch(N->getOpcode()) {
4602  case X86ISD::SHUFP:
4603    ImmN = N->getOperand(N->getNumOperands()-1);
4604    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4605    break;
4606  case X86ISD::UNPCKH:
4607    DecodeUNPCKHMask(VT, Mask);
4608    break;
4609  case X86ISD::UNPCKL:
4610    DecodeUNPCKLMask(VT, Mask);
4611    break;
4612  case X86ISD::MOVHLPS:
4613    DecodeMOVHLPSMask(NumElems, Mask);
4614    break;
4615  case X86ISD::MOVLHPS:
4616    DecodeMOVLHPSMask(NumElems, Mask);
4617    break;
4618  case X86ISD::PALIGNR:
4619    ImmN = N->getOperand(N->getNumOperands()-1);
4620    DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4621    break;
4622  case X86ISD::PSHUFD:
4623  case X86ISD::VPERMILP:
4624    ImmN = N->getOperand(N->getNumOperands()-1);
4625    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4626    IsUnary = true;
4627    break;
4628  case X86ISD::PSHUFHW:
4629    ImmN = N->getOperand(N->getNumOperands()-1);
4630    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4631    IsUnary = true;
4632    break;
4633  case X86ISD::PSHUFLW:
4634    ImmN = N->getOperand(N->getNumOperands()-1);
4635    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4636    IsUnary = true;
4637    break;
4638  case X86ISD::VPERMI:
4639    ImmN = N->getOperand(N->getNumOperands()-1);
4640    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4641    IsUnary = true;
4642    break;
4643  case X86ISD::MOVSS:
4644  case X86ISD::MOVSD: {
4645    // The index 0 always comes from the first element of the second source,
4646    // this is why MOVSS and MOVSD are used in the first place. The other
4647    // elements come from the other positions of the first source vector
4648    Mask.push_back(NumElems);
4649    for (unsigned i = 1; i != NumElems; ++i) {
4650      Mask.push_back(i);
4651    }
4652    break;
4653  }
4654  case X86ISD::VPERM2X128:
4655    ImmN = N->getOperand(N->getNumOperands()-1);
4656    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4657    if (Mask.empty()) return false;
4658    break;
4659  case X86ISD::MOVDDUP:
4660  case X86ISD::MOVLHPD:
4661  case X86ISD::MOVLPD:
4662  case X86ISD::MOVLPS:
4663  case X86ISD::MOVSHDUP:
4664  case X86ISD::MOVSLDUP:
4665    // Not yet implemented
4666    return false;
4667  default: llvm_unreachable("unknown target shuffle node");
4668  }
4669
4670  return true;
4671}
4672
4673/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4674/// element of the result of the vector shuffle.
4675static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4676                                   unsigned Depth) {
4677  if (Depth == 6)
4678    return SDValue();  // Limit search depth.
4679
4680  SDValue V = SDValue(N, 0);
4681  EVT VT = V.getValueType();
4682  unsigned Opcode = V.getOpcode();
4683
4684  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4685  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4686    int Elt = SV->getMaskElt(Index);
4687
4688    if (Elt < 0)
4689      return DAG.getUNDEF(VT.getVectorElementType());
4690
4691    unsigned NumElems = VT.getVectorNumElements();
4692    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4693                                         : SV->getOperand(1);
4694    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4695  }
4696
4697  // Recurse into target specific vector shuffles to find scalars.
4698  if (isTargetShuffle(Opcode)) {
4699    MVT ShufVT = V.getValueType().getSimpleVT();
4700    unsigned NumElems = ShufVT.getVectorNumElements();
4701    SmallVector<int, 16> ShuffleMask;
4702    bool IsUnary;
4703
4704    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4705      return SDValue();
4706
4707    int Elt = ShuffleMask[Index];
4708    if (Elt < 0)
4709      return DAG.getUNDEF(ShufVT.getVectorElementType());
4710
4711    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4712                                         : N->getOperand(1);
4713    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4714                               Depth+1);
4715  }
4716
4717  // Actual nodes that may contain scalar elements
4718  if (Opcode == ISD::BITCAST) {
4719    V = V.getOperand(0);
4720    EVT SrcVT = V.getValueType();
4721    unsigned NumElems = VT.getVectorNumElements();
4722
4723    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4724      return SDValue();
4725  }
4726
4727  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4728    return (Index == 0) ? V.getOperand(0)
4729                        : DAG.getUNDEF(VT.getVectorElementType());
4730
4731  if (V.getOpcode() == ISD::BUILD_VECTOR)
4732    return V.getOperand(Index);
4733
4734  return SDValue();
4735}
4736
4737/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4738/// shuffle operation which come from a consecutively from a zero. The
4739/// search can start in two different directions, from left or right.
4740static
4741unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4742                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4743  unsigned i;
4744  for (i = 0; i != NumElems; ++i) {
4745    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4746    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4747    if (!(Elt.getNode() &&
4748         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4749      break;
4750  }
4751
4752  return i;
4753}
4754
4755/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4756/// correspond consecutively to elements from one of the vector operands,
4757/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4758static
4759bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4760                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4761                              unsigned NumElems, unsigned &OpNum) {
4762  bool SeenV1 = false;
4763  bool SeenV2 = false;
4764
4765  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4766    int Idx = SVOp->getMaskElt(i);
4767    // Ignore undef indicies
4768    if (Idx < 0)
4769      continue;
4770
4771    if (Idx < (int)NumElems)
4772      SeenV1 = true;
4773    else
4774      SeenV2 = true;
4775
4776    // Only accept consecutive elements from the same vector
4777    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4778      return false;
4779  }
4780
4781  OpNum = SeenV1 ? 0 : 1;
4782  return true;
4783}
4784
4785/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4786/// logical left shift of a vector.
4787static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4788                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4789  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4790  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4791              false /* check zeros from right */, DAG);
4792  unsigned OpSrc;
4793
4794  if (!NumZeros)
4795    return false;
4796
4797  // Considering the elements in the mask that are not consecutive zeros,
4798  // check if they consecutively come from only one of the source vectors.
4799  //
4800  //               V1 = {X, A, B, C}     0
4801  //                         \  \  \    /
4802  //   vector_shuffle V1, V2 <1, 2, 3, X>
4803  //
4804  if (!isShuffleMaskConsecutive(SVOp,
4805            0,                   // Mask Start Index
4806            NumElems-NumZeros,   // Mask End Index(exclusive)
4807            NumZeros,            // Where to start looking in the src vector
4808            NumElems,            // Number of elements in vector
4809            OpSrc))              // Which source operand ?
4810    return false;
4811
4812  isLeft = false;
4813  ShAmt = NumZeros;
4814  ShVal = SVOp->getOperand(OpSrc);
4815  return true;
4816}
4817
4818/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4819/// logical left shift of a vector.
4820static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4821                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4822  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4823  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4824              true /* check zeros from left */, DAG);
4825  unsigned OpSrc;
4826
4827  if (!NumZeros)
4828    return false;
4829
4830  // Considering the elements in the mask that are not consecutive zeros,
4831  // check if they consecutively come from only one of the source vectors.
4832  //
4833  //                           0    { A, B, X, X } = V2
4834  //                          / \    /  /
4835  //   vector_shuffle V1, V2 <X, X, 4, 5>
4836  //
4837  if (!isShuffleMaskConsecutive(SVOp,
4838            NumZeros,     // Mask Start Index
4839            NumElems,     // Mask End Index(exclusive)
4840            0,            // Where to start looking in the src vector
4841            NumElems,     // Number of elements in vector
4842            OpSrc))       // Which source operand ?
4843    return false;
4844
4845  isLeft = true;
4846  ShAmt = NumZeros;
4847  ShVal = SVOp->getOperand(OpSrc);
4848  return true;
4849}
4850
4851/// isVectorShift - Returns true if the shuffle can be implemented as a
4852/// logical left or right shift of a vector.
4853static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4854                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4855  // Although the logic below support any bitwidth size, there are no
4856  // shift instructions which handle more than 128-bit vectors.
4857  if (!SVOp->getValueType(0).is128BitVector())
4858    return false;
4859
4860  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4861      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4862    return true;
4863
4864  return false;
4865}
4866
4867/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4868///
4869static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4870                                       unsigned NumNonZero, unsigned NumZero,
4871                                       SelectionDAG &DAG,
4872                                       const X86Subtarget* Subtarget,
4873                                       const TargetLowering &TLI) {
4874  if (NumNonZero > 8)
4875    return SDValue();
4876
4877  DebugLoc dl = Op.getDebugLoc();
4878  SDValue V(0, 0);
4879  bool First = true;
4880  for (unsigned i = 0; i < 16; ++i) {
4881    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4882    if (ThisIsNonZero && First) {
4883      if (NumZero)
4884        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4885      else
4886        V = DAG.getUNDEF(MVT::v8i16);
4887      First = false;
4888    }
4889
4890    if ((i & 1) != 0) {
4891      SDValue ThisElt(0, 0), LastElt(0, 0);
4892      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4893      if (LastIsNonZero) {
4894        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4895                              MVT::i16, Op.getOperand(i-1));
4896      }
4897      if (ThisIsNonZero) {
4898        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4899        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4900                              ThisElt, DAG.getConstant(8, MVT::i8));
4901        if (LastIsNonZero)
4902          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4903      } else
4904        ThisElt = LastElt;
4905
4906      if (ThisElt.getNode())
4907        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4908                        DAG.getIntPtrConstant(i/2));
4909    }
4910  }
4911
4912  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4913}
4914
4915/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4916///
4917static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4918                                     unsigned NumNonZero, unsigned NumZero,
4919                                     SelectionDAG &DAG,
4920                                     const X86Subtarget* Subtarget,
4921                                     const TargetLowering &TLI) {
4922  if (NumNonZero > 4)
4923    return SDValue();
4924
4925  DebugLoc dl = Op.getDebugLoc();
4926  SDValue V(0, 0);
4927  bool First = true;
4928  for (unsigned i = 0; i < 8; ++i) {
4929    bool isNonZero = (NonZeros & (1 << i)) != 0;
4930    if (isNonZero) {
4931      if (First) {
4932        if (NumZero)
4933          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4934        else
4935          V = DAG.getUNDEF(MVT::v8i16);
4936        First = false;
4937      }
4938      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4939                      MVT::v8i16, V, Op.getOperand(i),
4940                      DAG.getIntPtrConstant(i));
4941    }
4942  }
4943
4944  return V;
4945}
4946
4947/// getVShift - Return a vector logical shift node.
4948///
4949static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4950                         unsigned NumBits, SelectionDAG &DAG,
4951                         const TargetLowering &TLI, DebugLoc dl) {
4952  assert(VT.is128BitVector() && "Unknown type for VShift");
4953  EVT ShVT = MVT::v2i64;
4954  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4955  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4956  return DAG.getNode(ISD::BITCAST, dl, VT,
4957                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4958                             DAG.getConstant(NumBits,
4959                                  TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4960}
4961
4962SDValue
4963X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4964                                          SelectionDAG &DAG) const {
4965
4966  // Check if the scalar load can be widened into a vector load. And if
4967  // the address is "base + cst" see if the cst can be "absorbed" into
4968  // the shuffle mask.
4969  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4970    SDValue Ptr = LD->getBasePtr();
4971    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4972      return SDValue();
4973    EVT PVT = LD->getValueType(0);
4974    if (PVT != MVT::i32 && PVT != MVT::f32)
4975      return SDValue();
4976
4977    int FI = -1;
4978    int64_t Offset = 0;
4979    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4980      FI = FINode->getIndex();
4981      Offset = 0;
4982    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4983               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4984      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4985      Offset = Ptr.getConstantOperandVal(1);
4986      Ptr = Ptr.getOperand(0);
4987    } else {
4988      return SDValue();
4989    }
4990
4991    // FIXME: 256-bit vector instructions don't require a strict alignment,
4992    // improve this code to support it better.
4993    unsigned RequiredAlign = VT.getSizeInBits()/8;
4994    SDValue Chain = LD->getChain();
4995    // Make sure the stack object alignment is at least 16 or 32.
4996    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4997    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4998      if (MFI->isFixedObjectIndex(FI)) {
4999        // Can't change the alignment. FIXME: It's possible to compute
5000        // the exact stack offset and reference FI + adjust offset instead.
5001        // If someone *really* cares about this. That's the way to implement it.
5002        return SDValue();
5003      } else {
5004        MFI->setObjectAlignment(FI, RequiredAlign);
5005      }
5006    }
5007
5008    // (Offset % 16 or 32) must be multiple of 4. Then address is then
5009    // Ptr + (Offset & ~15).
5010    if (Offset < 0)
5011      return SDValue();
5012    if ((Offset % RequiredAlign) & 3)
5013      return SDValue();
5014    int64_t StartOffset = Offset & ~(RequiredAlign-1);
5015    if (StartOffset)
5016      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5017                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5018
5019    int EltNo = (Offset - StartOffset) >> 2;
5020    unsigned NumElems = VT.getVectorNumElements();
5021
5022    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5023    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5024                             LD->getPointerInfo().getWithOffset(StartOffset),
5025                             false, false, false, 0);
5026
5027    SmallVector<int, 8> Mask;
5028    for (unsigned i = 0; i != NumElems; ++i)
5029      Mask.push_back(EltNo);
5030
5031    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5032  }
5033
5034  return SDValue();
5035}
5036
5037/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5038/// vector of type 'VT', see if the elements can be replaced by a single large
5039/// load which has the same value as a build_vector whose operands are 'elts'.
5040///
5041/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5042///
5043/// FIXME: we'd also like to handle the case where the last elements are zero
5044/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5045/// There's even a handy isZeroNode for that purpose.
5046static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5047                                        DebugLoc &DL, SelectionDAG &DAG) {
5048  EVT EltVT = VT.getVectorElementType();
5049  unsigned NumElems = Elts.size();
5050
5051  LoadSDNode *LDBase = NULL;
5052  unsigned LastLoadedElt = -1U;
5053
5054  // For each element in the initializer, see if we've found a load or an undef.
5055  // If we don't find an initial load element, or later load elements are
5056  // non-consecutive, bail out.
5057  for (unsigned i = 0; i < NumElems; ++i) {
5058    SDValue Elt = Elts[i];
5059
5060    if (!Elt.getNode() ||
5061        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5062      return SDValue();
5063    if (!LDBase) {
5064      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5065        return SDValue();
5066      LDBase = cast<LoadSDNode>(Elt.getNode());
5067      LastLoadedElt = i;
5068      continue;
5069    }
5070    if (Elt.getOpcode() == ISD::UNDEF)
5071      continue;
5072
5073    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5074    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5075      return SDValue();
5076    LastLoadedElt = i;
5077  }
5078
5079  // If we have found an entire vector of loads and undefs, then return a large
5080  // load of the entire vector width starting at the base pointer.  If we found
5081  // consecutive loads for the low half, generate a vzext_load node.
5082  if (LastLoadedElt == NumElems - 1) {
5083    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5084      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5085                         LDBase->getPointerInfo(),
5086                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5087                         LDBase->isInvariant(), 0);
5088    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5089                       LDBase->getPointerInfo(),
5090                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5091                       LDBase->isInvariant(), LDBase->getAlignment());
5092  }
5093  if (NumElems == 4 && LastLoadedElt == 1 &&
5094      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5095    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5096    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5097    SDValue ResNode =
5098        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5099                                LDBase->getPointerInfo(),
5100                                LDBase->getAlignment(),
5101                                false/*isVolatile*/, true/*ReadMem*/,
5102                                false/*WriteMem*/);
5103
5104    // Make sure the newly-created LOAD is in the same position as LDBase in
5105    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5106    // update uses of LDBase's output chain to use the TokenFactor.
5107    if (LDBase->hasAnyUseOfValue(1)) {
5108      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5109                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5110      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5111      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5112                             SDValue(ResNode.getNode(), 1));
5113    }
5114
5115    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5116  }
5117  return SDValue();
5118}
5119
5120/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5121/// to generate a splat value for the following cases:
5122/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5123/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5124/// a scalar load, or a constant.
5125/// The VBROADCAST node is returned when a pattern is found,
5126/// or SDValue() otherwise.
5127SDValue
5128X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5129  if (!Subtarget->hasFp256())
5130    return SDValue();
5131
5132  MVT VT = Op.getValueType().getSimpleVT();
5133  DebugLoc dl = Op.getDebugLoc();
5134
5135  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5136         "Unsupported vector type for broadcast.");
5137
5138  SDValue Ld;
5139  bool ConstSplatVal;
5140
5141  switch (Op.getOpcode()) {
5142    default:
5143      // Unknown pattern found.
5144      return SDValue();
5145
5146    case ISD::BUILD_VECTOR: {
5147      // The BUILD_VECTOR node must be a splat.
5148      if (!isSplatVector(Op.getNode()))
5149        return SDValue();
5150
5151      Ld = Op.getOperand(0);
5152      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5153                     Ld.getOpcode() == ISD::ConstantFP);
5154
5155      // The suspected load node has several users. Make sure that all
5156      // of its users are from the BUILD_VECTOR node.
5157      // Constants may have multiple users.
5158      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5159        return SDValue();
5160      break;
5161    }
5162
5163    case ISD::VECTOR_SHUFFLE: {
5164      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5165
5166      // Shuffles must have a splat mask where the first element is
5167      // broadcasted.
5168      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5169        return SDValue();
5170
5171      SDValue Sc = Op.getOperand(0);
5172      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5173          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5174
5175        if (!Subtarget->hasInt256())
5176          return SDValue();
5177
5178        // Use the register form of the broadcast instruction available on AVX2.
5179        if (VT.is256BitVector())
5180          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5181        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5182      }
5183
5184      Ld = Sc.getOperand(0);
5185      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5186                       Ld.getOpcode() == ISD::ConstantFP);
5187
5188      // The scalar_to_vector node and the suspected
5189      // load node must have exactly one user.
5190      // Constants may have multiple users.
5191      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5192        return SDValue();
5193      break;
5194    }
5195  }
5196
5197  bool Is256 = VT.is256BitVector();
5198
5199  // Handle the broadcasting a single constant scalar from the constant pool
5200  // into a vector. On Sandybridge it is still better to load a constant vector
5201  // from the constant pool and not to broadcast it from a scalar.
5202  if (ConstSplatVal && Subtarget->hasInt256()) {
5203    EVT CVT = Ld.getValueType();
5204    assert(!CVT.isVector() && "Must not broadcast a vector type");
5205    unsigned ScalarSize = CVT.getSizeInBits();
5206
5207    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5208      const Constant *C = 0;
5209      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5210        C = CI->getConstantIntValue();
5211      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5212        C = CF->getConstantFPValue();
5213
5214      assert(C && "Invalid constant type");
5215
5216      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5217      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5218      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5219                       MachinePointerInfo::getConstantPool(),
5220                       false, false, false, Alignment);
5221
5222      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5223    }
5224  }
5225
5226  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5227  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5228
5229  // Handle AVX2 in-register broadcasts.
5230  if (!IsLoad && Subtarget->hasInt256() &&
5231      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5232    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5233
5234  // The scalar source must be a normal load.
5235  if (!IsLoad)
5236    return SDValue();
5237
5238  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5239    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5240
5241  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5242  // double since there is no vbroadcastsd xmm
5243  if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5244    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5245      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5246  }
5247
5248  // Unsupported broadcast.
5249  return SDValue();
5250}
5251
5252SDValue
5253X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5254  EVT VT = Op.getValueType();
5255
5256  // Skip if insert_vec_elt is not supported.
5257  if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5258    return SDValue();
5259
5260  DebugLoc DL = Op.getDebugLoc();
5261  unsigned NumElems = Op.getNumOperands();
5262
5263  SDValue VecIn1;
5264  SDValue VecIn2;
5265  SmallVector<unsigned, 4> InsertIndices;
5266  SmallVector<int, 8> Mask(NumElems, -1);
5267
5268  for (unsigned i = 0; i != NumElems; ++i) {
5269    unsigned Opc = Op.getOperand(i).getOpcode();
5270
5271    if (Opc == ISD::UNDEF)
5272      continue;
5273
5274    if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5275      // Quit if more than 1 elements need inserting.
5276      if (InsertIndices.size() > 1)
5277        return SDValue();
5278
5279      InsertIndices.push_back(i);
5280      continue;
5281    }
5282
5283    SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5284    SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5285
5286    // Quit if extracted from vector of different type.
5287    if (ExtractedFromVec.getValueType() != VT)
5288      return SDValue();
5289
5290    // Quit if non-constant index.
5291    if (!isa<ConstantSDNode>(ExtIdx))
5292      return SDValue();
5293
5294    if (VecIn1.getNode() == 0)
5295      VecIn1 = ExtractedFromVec;
5296    else if (VecIn1 != ExtractedFromVec) {
5297      if (VecIn2.getNode() == 0)
5298        VecIn2 = ExtractedFromVec;
5299      else if (VecIn2 != ExtractedFromVec)
5300        // Quit if more than 2 vectors to shuffle
5301        return SDValue();
5302    }
5303
5304    unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5305
5306    if (ExtractedFromVec == VecIn1)
5307      Mask[i] = Idx;
5308    else if (ExtractedFromVec == VecIn2)
5309      Mask[i] = Idx + NumElems;
5310  }
5311
5312  if (VecIn1.getNode() == 0)
5313    return SDValue();
5314
5315  VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5316  SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5317  for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5318    unsigned Idx = InsertIndices[i];
5319    NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5320                     DAG.getIntPtrConstant(Idx));
5321  }
5322
5323  return NV;
5324}
5325
5326SDValue
5327X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5328  DebugLoc dl = Op.getDebugLoc();
5329
5330  MVT VT = Op.getValueType().getSimpleVT();
5331  MVT ExtVT = VT.getVectorElementType();
5332  unsigned NumElems = Op.getNumOperands();
5333
5334  // Vectors containing all zeros can be matched by pxor and xorps later
5335  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5336    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5337    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5338    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5339      return Op;
5340
5341    return getZeroVector(VT, Subtarget, DAG, dl);
5342  }
5343
5344  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5345  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5346  // vpcmpeqd on 256-bit vectors.
5347  if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5348    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5349      return Op;
5350
5351    return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5352  }
5353
5354  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5355  if (Broadcast.getNode())
5356    return Broadcast;
5357
5358  unsigned EVTBits = ExtVT.getSizeInBits();
5359
5360  unsigned NumZero  = 0;
5361  unsigned NumNonZero = 0;
5362  unsigned NonZeros = 0;
5363  bool IsAllConstants = true;
5364  SmallSet<SDValue, 8> Values;
5365  for (unsigned i = 0; i < NumElems; ++i) {
5366    SDValue Elt = Op.getOperand(i);
5367    if (Elt.getOpcode() == ISD::UNDEF)
5368      continue;
5369    Values.insert(Elt);
5370    if (Elt.getOpcode() != ISD::Constant &&
5371        Elt.getOpcode() != ISD::ConstantFP)
5372      IsAllConstants = false;
5373    if (X86::isZeroNode(Elt))
5374      NumZero++;
5375    else {
5376      NonZeros |= (1 << i);
5377      NumNonZero++;
5378    }
5379  }
5380
5381  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5382  if (NumNonZero == 0)
5383    return DAG.getUNDEF(VT);
5384
5385  // Special case for single non-zero, non-undef, element.
5386  if (NumNonZero == 1) {
5387    unsigned Idx = CountTrailingZeros_32(NonZeros);
5388    SDValue Item = Op.getOperand(Idx);
5389
5390    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5391    // the value are obviously zero, truncate the value to i32 and do the
5392    // insertion that way.  Only do this if the value is non-constant or if the
5393    // value is a constant being inserted into element 0.  It is cheaper to do
5394    // a constant pool load than it is to do a movd + shuffle.
5395    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5396        (!IsAllConstants || Idx == 0)) {
5397      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5398        // Handle SSE only.
5399        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5400        EVT VecVT = MVT::v4i32;
5401        unsigned VecElts = 4;
5402
5403        // Truncate the value (which may itself be a constant) to i32, and
5404        // convert it to a vector with movd (S2V+shuffle to zero extend).
5405        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5406        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5407        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5408
5409        // Now we have our 32-bit value zero extended in the low element of
5410        // a vector.  If Idx != 0, swizzle it into place.
5411        if (Idx != 0) {
5412          SmallVector<int, 4> Mask;
5413          Mask.push_back(Idx);
5414          for (unsigned i = 1; i != VecElts; ++i)
5415            Mask.push_back(i);
5416          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5417                                      &Mask[0]);
5418        }
5419        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5420      }
5421    }
5422
5423    // If we have a constant or non-constant insertion into the low element of
5424    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5425    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5426    // depending on what the source datatype is.
5427    if (Idx == 0) {
5428      if (NumZero == 0)
5429        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5430
5431      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5432          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5433        if (VT.is256BitVector()) {
5434          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5435          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5436                             Item, DAG.getIntPtrConstant(0));
5437        }
5438        assert(VT.is128BitVector() && "Expected an SSE value type!");
5439        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5440        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5441        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5442      }
5443
5444      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5445        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5446        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5447        if (VT.is256BitVector()) {
5448          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5449          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5450        } else {
5451          assert(VT.is128BitVector() && "Expected an SSE value type!");
5452          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5453        }
5454        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5455      }
5456    }
5457
5458    // Is it a vector logical left shift?
5459    if (NumElems == 2 && Idx == 1 &&
5460        X86::isZeroNode(Op.getOperand(0)) &&
5461        !X86::isZeroNode(Op.getOperand(1))) {
5462      unsigned NumBits = VT.getSizeInBits();
5463      return getVShift(true, VT,
5464                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5465                                   VT, Op.getOperand(1)),
5466                       NumBits/2, DAG, *this, dl);
5467    }
5468
5469    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5470      return SDValue();
5471
5472    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5473    // is a non-constant being inserted into an element other than the low one,
5474    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5475    // movd/movss) to move this into the low element, then shuffle it into
5476    // place.
5477    if (EVTBits == 32) {
5478      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5479
5480      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5481      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5482      SmallVector<int, 8> MaskVec;
5483      for (unsigned i = 0; i != NumElems; ++i)
5484        MaskVec.push_back(i == Idx ? 0 : 1);
5485      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5486    }
5487  }
5488
5489  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5490  if (Values.size() == 1) {
5491    if (EVTBits == 32) {
5492      // Instead of a shuffle like this:
5493      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5494      // Check if it's possible to issue this instead.
5495      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5496      unsigned Idx = CountTrailingZeros_32(NonZeros);
5497      SDValue Item = Op.getOperand(Idx);
5498      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5499        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5500    }
5501    return SDValue();
5502  }
5503
5504  // A vector full of immediates; various special cases are already
5505  // handled, so this is best done with a single constant-pool load.
5506  if (IsAllConstants)
5507    return SDValue();
5508
5509  // For AVX-length vectors, build the individual 128-bit pieces and use
5510  // shuffles to put them in place.
5511  if (VT.is256BitVector()) {
5512    SmallVector<SDValue, 32> V;
5513    for (unsigned i = 0; i != NumElems; ++i)
5514      V.push_back(Op.getOperand(i));
5515
5516    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5517
5518    // Build both the lower and upper subvector.
5519    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5520    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5521                                NumElems/2);
5522
5523    // Recreate the wider vector with the lower and upper part.
5524    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5525  }
5526
5527  // Let legalizer expand 2-wide build_vectors.
5528  if (EVTBits == 64) {
5529    if (NumNonZero == 1) {
5530      // One half is zero or undef.
5531      unsigned Idx = CountTrailingZeros_32(NonZeros);
5532      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5533                                 Op.getOperand(Idx));
5534      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5535    }
5536    return SDValue();
5537  }
5538
5539  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5540  if (EVTBits == 8 && NumElems == 16) {
5541    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5542                                        Subtarget, *this);
5543    if (V.getNode()) return V;
5544  }
5545
5546  if (EVTBits == 16 && NumElems == 8) {
5547    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5548                                      Subtarget, *this);
5549    if (V.getNode()) return V;
5550  }
5551
5552  // If element VT is == 32 bits, turn it into a number of shuffles.
5553  SmallVector<SDValue, 8> V(NumElems);
5554  if (NumElems == 4 && NumZero > 0) {
5555    for (unsigned i = 0; i < 4; ++i) {
5556      bool isZero = !(NonZeros & (1 << i));
5557      if (isZero)
5558        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5559      else
5560        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5561    }
5562
5563    for (unsigned i = 0; i < 2; ++i) {
5564      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5565        default: break;
5566        case 0:
5567          V[i] = V[i*2];  // Must be a zero vector.
5568          break;
5569        case 1:
5570          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5571          break;
5572        case 2:
5573          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5574          break;
5575        case 3:
5576          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5577          break;
5578      }
5579    }
5580
5581    bool Reverse1 = (NonZeros & 0x3) == 2;
5582    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5583    int MaskVec[] = {
5584      Reverse1 ? 1 : 0,
5585      Reverse1 ? 0 : 1,
5586      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5587      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5588    };
5589    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5590  }
5591
5592  if (Values.size() > 1 && VT.is128BitVector()) {
5593    // Check for a build vector of consecutive loads.
5594    for (unsigned i = 0; i < NumElems; ++i)
5595      V[i] = Op.getOperand(i);
5596
5597    // Check for elements which are consecutive loads.
5598    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5599    if (LD.getNode())
5600      return LD;
5601
5602    // Check for a build vector from mostly shuffle plus few inserting.
5603    SDValue Sh = buildFromShuffleMostly(Op, DAG);
5604    if (Sh.getNode())
5605      return Sh;
5606
5607    // For SSE 4.1, use insertps to put the high elements into the low element.
5608    if (getSubtarget()->hasSSE41()) {
5609      SDValue Result;
5610      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5611        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5612      else
5613        Result = DAG.getUNDEF(VT);
5614
5615      for (unsigned i = 1; i < NumElems; ++i) {
5616        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5617        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5618                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5619      }
5620      return Result;
5621    }
5622
5623    // Otherwise, expand into a number of unpckl*, start by extending each of
5624    // our (non-undef) elements to the full vector width with the element in the
5625    // bottom slot of the vector (which generates no code for SSE).
5626    for (unsigned i = 0; i < NumElems; ++i) {
5627      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5628        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5629      else
5630        V[i] = DAG.getUNDEF(VT);
5631    }
5632
5633    // Next, we iteratively mix elements, e.g. for v4f32:
5634    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5635    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5636    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5637    unsigned EltStride = NumElems >> 1;
5638    while (EltStride != 0) {
5639      for (unsigned i = 0; i < EltStride; ++i) {
5640        // If V[i+EltStride] is undef and this is the first round of mixing,
5641        // then it is safe to just drop this shuffle: V[i] is already in the
5642        // right place, the one element (since it's the first round) being
5643        // inserted as undef can be dropped.  This isn't safe for successive
5644        // rounds because they will permute elements within both vectors.
5645        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5646            EltStride == NumElems/2)
5647          continue;
5648
5649        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5650      }
5651      EltStride >>= 1;
5652    }
5653    return V[0];
5654  }
5655  return SDValue();
5656}
5657
5658// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5659// to create 256-bit vectors from two other 128-bit ones.
5660static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5661  DebugLoc dl = Op.getDebugLoc();
5662  MVT ResVT = Op.getValueType().getSimpleVT();
5663
5664  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5665
5666  SDValue V1 = Op.getOperand(0);
5667  SDValue V2 = Op.getOperand(1);
5668  unsigned NumElems = ResVT.getVectorNumElements();
5669
5670  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5671}
5672
5673static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5674  assert(Op.getNumOperands() == 2);
5675
5676  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5677  // from two other 128-bit ones.
5678  return LowerAVXCONCAT_VECTORS(Op, DAG);
5679}
5680
5681// Try to lower a shuffle node into a simple blend instruction.
5682static SDValue
5683LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5684                           const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5685  SDValue V1 = SVOp->getOperand(0);
5686  SDValue V2 = SVOp->getOperand(1);
5687  DebugLoc dl = SVOp->getDebugLoc();
5688  MVT VT = SVOp->getValueType(0).getSimpleVT();
5689  MVT EltVT = VT.getVectorElementType();
5690  unsigned NumElems = VT.getVectorNumElements();
5691
5692  if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5693    return SDValue();
5694  if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5695    return SDValue();
5696
5697  // Check the mask for BLEND and build the value.
5698  unsigned MaskValue = 0;
5699  // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5700  unsigned NumLanes = (NumElems-1)/8 + 1;
5701  unsigned NumElemsInLane = NumElems / NumLanes;
5702
5703  // Blend for v16i16 should be symetric for the both lanes.
5704  for (unsigned i = 0; i < NumElemsInLane; ++i) {
5705
5706    int SndLaneEltIdx = (NumLanes == 2) ?
5707      SVOp->getMaskElt(i + NumElemsInLane) : -1;
5708    int EltIdx = SVOp->getMaskElt(i);
5709
5710    if ((EltIdx < 0 || EltIdx == (int)i) &&
5711        (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5712      continue;
5713
5714    if (((unsigned)EltIdx == (i + NumElems)) &&
5715        (SndLaneEltIdx < 0 ||
5716         (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5717      MaskValue |= (1<<i);
5718    else
5719      return SDValue();
5720  }
5721
5722  // Convert i32 vectors to floating point if it is not AVX2.
5723  // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5724  MVT BlendVT = VT;
5725  if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5726    BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5727                               NumElems);
5728    V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5729    V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5730  }
5731
5732  SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5733                            DAG.getConstant(MaskValue, MVT::i32));
5734  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5735}
5736
5737// v8i16 shuffles - Prefer shuffles in the following order:
5738// 1. [all]   pshuflw, pshufhw, optional move
5739// 2. [ssse3] 1 x pshufb
5740// 3. [ssse3] 2 x pshufb + 1 x por
5741// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5742static SDValue
5743LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5744                         SelectionDAG &DAG) {
5745  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5746  SDValue V1 = SVOp->getOperand(0);
5747  SDValue V2 = SVOp->getOperand(1);
5748  DebugLoc dl = SVOp->getDebugLoc();
5749  SmallVector<int, 8> MaskVals;
5750
5751  // Determine if more than 1 of the words in each of the low and high quadwords
5752  // of the result come from the same quadword of one of the two inputs.  Undef
5753  // mask values count as coming from any quadword, for better codegen.
5754  unsigned LoQuad[] = { 0, 0, 0, 0 };
5755  unsigned HiQuad[] = { 0, 0, 0, 0 };
5756  std::bitset<4> InputQuads;
5757  for (unsigned i = 0; i < 8; ++i) {
5758    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5759    int EltIdx = SVOp->getMaskElt(i);
5760    MaskVals.push_back(EltIdx);
5761    if (EltIdx < 0) {
5762      ++Quad[0];
5763      ++Quad[1];
5764      ++Quad[2];
5765      ++Quad[3];
5766      continue;
5767    }
5768    ++Quad[EltIdx / 4];
5769    InputQuads.set(EltIdx / 4);
5770  }
5771
5772  int BestLoQuad = -1;
5773  unsigned MaxQuad = 1;
5774  for (unsigned i = 0; i < 4; ++i) {
5775    if (LoQuad[i] > MaxQuad) {
5776      BestLoQuad = i;
5777      MaxQuad = LoQuad[i];
5778    }
5779  }
5780
5781  int BestHiQuad = -1;
5782  MaxQuad = 1;
5783  for (unsigned i = 0; i < 4; ++i) {
5784    if (HiQuad[i] > MaxQuad) {
5785      BestHiQuad = i;
5786      MaxQuad = HiQuad[i];
5787    }
5788  }
5789
5790  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5791  // of the two input vectors, shuffle them into one input vector so only a
5792  // single pshufb instruction is necessary. If There are more than 2 input
5793  // quads, disable the next transformation since it does not help SSSE3.
5794  bool V1Used = InputQuads[0] || InputQuads[1];
5795  bool V2Used = InputQuads[2] || InputQuads[3];
5796  if (Subtarget->hasSSSE3()) {
5797    if (InputQuads.count() == 2 && V1Used && V2Used) {
5798      BestLoQuad = InputQuads[0] ? 0 : 1;
5799      BestHiQuad = InputQuads[2] ? 2 : 3;
5800    }
5801    if (InputQuads.count() > 2) {
5802      BestLoQuad = -1;
5803      BestHiQuad = -1;
5804    }
5805  }
5806
5807  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5808  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5809  // words from all 4 input quadwords.
5810  SDValue NewV;
5811  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5812    int MaskV[] = {
5813      BestLoQuad < 0 ? 0 : BestLoQuad,
5814      BestHiQuad < 0 ? 1 : BestHiQuad
5815    };
5816    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5817                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5818                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5819    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5820
5821    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5822    // source words for the shuffle, to aid later transformations.
5823    bool AllWordsInNewV = true;
5824    bool InOrder[2] = { true, true };
5825    for (unsigned i = 0; i != 8; ++i) {
5826      int idx = MaskVals[i];
5827      if (idx != (int)i)
5828        InOrder[i/4] = false;
5829      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5830        continue;
5831      AllWordsInNewV = false;
5832      break;
5833    }
5834
5835    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5836    if (AllWordsInNewV) {
5837      for (int i = 0; i != 8; ++i) {
5838        int idx = MaskVals[i];
5839        if (idx < 0)
5840          continue;
5841        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5842        if ((idx != i) && idx < 4)
5843          pshufhw = false;
5844        if ((idx != i) && idx > 3)
5845          pshuflw = false;
5846      }
5847      V1 = NewV;
5848      V2Used = false;
5849      BestLoQuad = 0;
5850      BestHiQuad = 1;
5851    }
5852
5853    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5854    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5855    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5856      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5857      unsigned TargetMask = 0;
5858      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5859                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5860      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5861      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5862                             getShufflePSHUFLWImmediate(SVOp);
5863      V1 = NewV.getOperand(0);
5864      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5865    }
5866  }
5867
5868  // Promote splats to a larger type which usually leads to more efficient code.
5869  // FIXME: Is this true if pshufb is available?
5870  if (SVOp->isSplat())
5871    return PromoteSplat(SVOp, DAG);
5872
5873  // If we have SSSE3, and all words of the result are from 1 input vector,
5874  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5875  // is present, fall back to case 4.
5876  if (Subtarget->hasSSSE3()) {
5877    SmallVector<SDValue,16> pshufbMask;
5878
5879    // If we have elements from both input vectors, set the high bit of the
5880    // shuffle mask element to zero out elements that come from V2 in the V1
5881    // mask, and elements that come from V1 in the V2 mask, so that the two
5882    // results can be OR'd together.
5883    bool TwoInputs = V1Used && V2Used;
5884    for (unsigned i = 0; i != 8; ++i) {
5885      int EltIdx = MaskVals[i] * 2;
5886      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5887      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5888      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5889      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5890    }
5891    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5892    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5893                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5894                                 MVT::v16i8, &pshufbMask[0], 16));
5895    if (!TwoInputs)
5896      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5897
5898    // Calculate the shuffle mask for the second input, shuffle it, and
5899    // OR it with the first shuffled input.
5900    pshufbMask.clear();
5901    for (unsigned i = 0; i != 8; ++i) {
5902      int EltIdx = MaskVals[i] * 2;
5903      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5904      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5905      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5906      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5907    }
5908    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5909    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5910                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5911                                 MVT::v16i8, &pshufbMask[0], 16));
5912    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5913    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5914  }
5915
5916  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5917  // and update MaskVals with new element order.
5918  std::bitset<8> InOrder;
5919  if (BestLoQuad >= 0) {
5920    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5921    for (int i = 0; i != 4; ++i) {
5922      int idx = MaskVals[i];
5923      if (idx < 0) {
5924        InOrder.set(i);
5925      } else if ((idx / 4) == BestLoQuad) {
5926        MaskV[i] = idx & 3;
5927        InOrder.set(i);
5928      }
5929    }
5930    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5931                                &MaskV[0]);
5932
5933    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5934      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5935      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5936                                  NewV.getOperand(0),
5937                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5938    }
5939  }
5940
5941  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5942  // and update MaskVals with the new element order.
5943  if (BestHiQuad >= 0) {
5944    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5945    for (unsigned i = 4; i != 8; ++i) {
5946      int idx = MaskVals[i];
5947      if (idx < 0) {
5948        InOrder.set(i);
5949      } else if ((idx / 4) == BestHiQuad) {
5950        MaskV[i] = (idx & 3) + 4;
5951        InOrder.set(i);
5952      }
5953    }
5954    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5955                                &MaskV[0]);
5956
5957    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5958      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5959      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5960                                  NewV.getOperand(0),
5961                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5962    }
5963  }
5964
5965  // In case BestHi & BestLo were both -1, which means each quadword has a word
5966  // from each of the four input quadwords, calculate the InOrder bitvector now
5967  // before falling through to the insert/extract cleanup.
5968  if (BestLoQuad == -1 && BestHiQuad == -1) {
5969    NewV = V1;
5970    for (int i = 0; i != 8; ++i)
5971      if (MaskVals[i] < 0 || MaskVals[i] == i)
5972        InOrder.set(i);
5973  }
5974
5975  // The other elements are put in the right place using pextrw and pinsrw.
5976  for (unsigned i = 0; i != 8; ++i) {
5977    if (InOrder[i])
5978      continue;
5979    int EltIdx = MaskVals[i];
5980    if (EltIdx < 0)
5981      continue;
5982    SDValue ExtOp = (EltIdx < 8) ?
5983      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5984                  DAG.getIntPtrConstant(EltIdx)) :
5985      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5986                  DAG.getIntPtrConstant(EltIdx - 8));
5987    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5988                       DAG.getIntPtrConstant(i));
5989  }
5990  return NewV;
5991}
5992
5993// v16i8 shuffles - Prefer shuffles in the following order:
5994// 1. [ssse3] 1 x pshufb
5995// 2. [ssse3] 2 x pshufb + 1 x por
5996// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5997static
5998SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5999                                 SelectionDAG &DAG,
6000                                 const X86TargetLowering &TLI) {
6001  SDValue V1 = SVOp->getOperand(0);
6002  SDValue V2 = SVOp->getOperand(1);
6003  DebugLoc dl = SVOp->getDebugLoc();
6004  ArrayRef<int> MaskVals = SVOp->getMask();
6005
6006  // Promote splats to a larger type which usually leads to more efficient code.
6007  // FIXME: Is this true if pshufb is available?
6008  if (SVOp->isSplat())
6009    return PromoteSplat(SVOp, DAG);
6010
6011  // If we have SSSE3, case 1 is generated when all result bytes come from
6012  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6013  // present, fall back to case 3.
6014
6015  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6016  if (TLI.getSubtarget()->hasSSSE3()) {
6017    SmallVector<SDValue,16> pshufbMask;
6018
6019    // If all result elements are from one input vector, then only translate
6020    // undef mask values to 0x80 (zero out result) in the pshufb mask.
6021    //
6022    // Otherwise, we have elements from both input vectors, and must zero out
6023    // elements that come from V2 in the first mask, and V1 in the second mask
6024    // so that we can OR them together.
6025    for (unsigned i = 0; i != 16; ++i) {
6026      int EltIdx = MaskVals[i];
6027      if (EltIdx < 0 || EltIdx >= 16)
6028        EltIdx = 0x80;
6029      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6030    }
6031    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6032                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6033                                 MVT::v16i8, &pshufbMask[0], 16));
6034
6035    // As PSHUFB will zero elements with negative indices, it's safe to ignore
6036    // the 2nd operand if it's undefined or zero.
6037    if (V2.getOpcode() == ISD::UNDEF ||
6038        ISD::isBuildVectorAllZeros(V2.getNode()))
6039      return V1;
6040
6041    // Calculate the shuffle mask for the second input, shuffle it, and
6042    // OR it with the first shuffled input.
6043    pshufbMask.clear();
6044    for (unsigned i = 0; i != 16; ++i) {
6045      int EltIdx = MaskVals[i];
6046      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6047      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6048    }
6049    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6050                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6051                                 MVT::v16i8, &pshufbMask[0], 16));
6052    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6053  }
6054
6055  // No SSSE3 - Calculate in place words and then fix all out of place words
6056  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6057  // the 16 different words that comprise the two doublequadword input vectors.
6058  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6059  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6060  SDValue NewV = V1;
6061  for (int i = 0; i != 8; ++i) {
6062    int Elt0 = MaskVals[i*2];
6063    int Elt1 = MaskVals[i*2+1];
6064
6065    // This word of the result is all undef, skip it.
6066    if (Elt0 < 0 && Elt1 < 0)
6067      continue;
6068
6069    // This word of the result is already in the correct place, skip it.
6070    if ((Elt0 == i*2) && (Elt1 == i*2+1))
6071      continue;
6072
6073    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6074    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6075    SDValue InsElt;
6076
6077    // If Elt0 and Elt1 are defined, are consecutive, and can be load
6078    // using a single extract together, load it and store it.
6079    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6080      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6081                           DAG.getIntPtrConstant(Elt1 / 2));
6082      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6083                        DAG.getIntPtrConstant(i));
6084      continue;
6085    }
6086
6087    // If Elt1 is defined, extract it from the appropriate source.  If the
6088    // source byte is not also odd, shift the extracted word left 8 bits
6089    // otherwise clear the bottom 8 bits if we need to do an or.
6090    if (Elt1 >= 0) {
6091      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6092                           DAG.getIntPtrConstant(Elt1 / 2));
6093      if ((Elt1 & 1) == 0)
6094        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6095                             DAG.getConstant(8,
6096                                  TLI.getShiftAmountTy(InsElt.getValueType())));
6097      else if (Elt0 >= 0)
6098        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6099                             DAG.getConstant(0xFF00, MVT::i16));
6100    }
6101    // If Elt0 is defined, extract it from the appropriate source.  If the
6102    // source byte is not also even, shift the extracted word right 8 bits. If
6103    // Elt1 was also defined, OR the extracted values together before
6104    // inserting them in the result.
6105    if (Elt0 >= 0) {
6106      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6107                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6108      if ((Elt0 & 1) != 0)
6109        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6110                              DAG.getConstant(8,
6111                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6112      else if (Elt1 >= 0)
6113        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6114                             DAG.getConstant(0x00FF, MVT::i16));
6115      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6116                         : InsElt0;
6117    }
6118    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6119                       DAG.getIntPtrConstant(i));
6120  }
6121  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6122}
6123
6124// v32i8 shuffles - Translate to VPSHUFB if possible.
6125static
6126SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6127                                 const X86Subtarget *Subtarget,
6128                                 SelectionDAG &DAG) {
6129  MVT VT = SVOp->getValueType(0).getSimpleVT();
6130  SDValue V1 = SVOp->getOperand(0);
6131  SDValue V2 = SVOp->getOperand(1);
6132  DebugLoc dl = SVOp->getDebugLoc();
6133  SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6134
6135  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6136  bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6137  bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6138
6139  // VPSHUFB may be generated if
6140  // (1) one of input vector is undefined or zeroinitializer.
6141  // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6142  // And (2) the mask indexes don't cross the 128-bit lane.
6143  if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6144      (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6145    return SDValue();
6146
6147  if (V1IsAllZero && !V2IsAllZero) {
6148    CommuteVectorShuffleMask(MaskVals, 32);
6149    V1 = V2;
6150  }
6151  SmallVector<SDValue, 32> pshufbMask;
6152  for (unsigned i = 0; i != 32; i++) {
6153    int EltIdx = MaskVals[i];
6154    if (EltIdx < 0 || EltIdx >= 32)
6155      EltIdx = 0x80;
6156    else {
6157      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6158        // Cross lane is not allowed.
6159        return SDValue();
6160      EltIdx &= 0xf;
6161    }
6162    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6163  }
6164  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6165                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6166                                  MVT::v32i8, &pshufbMask[0], 32));
6167}
6168
6169/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6170/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6171/// done when every pair / quad of shuffle mask elements point to elements in
6172/// the right sequence. e.g.
6173/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6174static
6175SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6176                                 SelectionDAG &DAG) {
6177  MVT VT = SVOp->getValueType(0).getSimpleVT();
6178  DebugLoc dl = SVOp->getDebugLoc();
6179  unsigned NumElems = VT.getVectorNumElements();
6180  MVT NewVT;
6181  unsigned Scale;
6182  switch (VT.SimpleTy) {
6183  default: llvm_unreachable("Unexpected!");
6184  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6185  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6186  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6187  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6188  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6189  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6190  }
6191
6192  SmallVector<int, 8> MaskVec;
6193  for (unsigned i = 0; i != NumElems; i += Scale) {
6194    int StartIdx = -1;
6195    for (unsigned j = 0; j != Scale; ++j) {
6196      int EltIdx = SVOp->getMaskElt(i+j);
6197      if (EltIdx < 0)
6198        continue;
6199      if (StartIdx < 0)
6200        StartIdx = (EltIdx / Scale);
6201      if (EltIdx != (int)(StartIdx*Scale + j))
6202        return SDValue();
6203    }
6204    MaskVec.push_back(StartIdx);
6205  }
6206
6207  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6208  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6209  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6210}
6211
6212/// getVZextMovL - Return a zero-extending vector move low node.
6213///
6214static SDValue getVZextMovL(MVT VT, EVT OpVT,
6215                            SDValue SrcOp, SelectionDAG &DAG,
6216                            const X86Subtarget *Subtarget, DebugLoc dl) {
6217  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6218    LoadSDNode *LD = NULL;
6219    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6220      LD = dyn_cast<LoadSDNode>(SrcOp);
6221    if (!LD) {
6222      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6223      // instead.
6224      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6225      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6226          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6227          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6228          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6229        // PR2108
6230        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6231        return DAG.getNode(ISD::BITCAST, dl, VT,
6232                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6233                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6234                                                   OpVT,
6235                                                   SrcOp.getOperand(0)
6236                                                          .getOperand(0))));
6237      }
6238    }
6239  }
6240
6241  return DAG.getNode(ISD::BITCAST, dl, VT,
6242                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6243                                 DAG.getNode(ISD::BITCAST, dl,
6244                                             OpVT, SrcOp)));
6245}
6246
6247/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6248/// which could not be matched by any known target speficic shuffle
6249static SDValue
6250LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6251
6252  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6253  if (NewOp.getNode())
6254    return NewOp;
6255
6256  MVT VT = SVOp->getValueType(0).getSimpleVT();
6257
6258  unsigned NumElems = VT.getVectorNumElements();
6259  unsigned NumLaneElems = NumElems / 2;
6260
6261  DebugLoc dl = SVOp->getDebugLoc();
6262  MVT EltVT = VT.getVectorElementType();
6263  MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6264  SDValue Output[2];
6265
6266  SmallVector<int, 16> Mask;
6267  for (unsigned l = 0; l < 2; ++l) {
6268    // Build a shuffle mask for the output, discovering on the fly which
6269    // input vectors to use as shuffle operands (recorded in InputUsed).
6270    // If building a suitable shuffle vector proves too hard, then bail
6271    // out with UseBuildVector set.
6272    bool UseBuildVector = false;
6273    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6274    unsigned LaneStart = l * NumLaneElems;
6275    for (unsigned i = 0; i != NumLaneElems; ++i) {
6276      // The mask element.  This indexes into the input.
6277      int Idx = SVOp->getMaskElt(i+LaneStart);
6278      if (Idx < 0) {
6279        // the mask element does not index into any input vector.
6280        Mask.push_back(-1);
6281        continue;
6282      }
6283
6284      // The input vector this mask element indexes into.
6285      int Input = Idx / NumLaneElems;
6286
6287      // Turn the index into an offset from the start of the input vector.
6288      Idx -= Input * NumLaneElems;
6289
6290      // Find or create a shuffle vector operand to hold this input.
6291      unsigned OpNo;
6292      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6293        if (InputUsed[OpNo] == Input)
6294          // This input vector is already an operand.
6295          break;
6296        if (InputUsed[OpNo] < 0) {
6297          // Create a new operand for this input vector.
6298          InputUsed[OpNo] = Input;
6299          break;
6300        }
6301      }
6302
6303      if (OpNo >= array_lengthof(InputUsed)) {
6304        // More than two input vectors used!  Give up on trying to create a
6305        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6306        UseBuildVector = true;
6307        break;
6308      }
6309
6310      // Add the mask index for the new shuffle vector.
6311      Mask.push_back(Idx + OpNo * NumLaneElems);
6312    }
6313
6314    if (UseBuildVector) {
6315      SmallVector<SDValue, 16> SVOps;
6316      for (unsigned i = 0; i != NumLaneElems; ++i) {
6317        // The mask element.  This indexes into the input.
6318        int Idx = SVOp->getMaskElt(i+LaneStart);
6319        if (Idx < 0) {
6320          SVOps.push_back(DAG.getUNDEF(EltVT));
6321          continue;
6322        }
6323
6324        // The input vector this mask element indexes into.
6325        int Input = Idx / NumElems;
6326
6327        // Turn the index into an offset from the start of the input vector.
6328        Idx -= Input * NumElems;
6329
6330        // Extract the vector element by hand.
6331        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6332                                    SVOp->getOperand(Input),
6333                                    DAG.getIntPtrConstant(Idx)));
6334      }
6335
6336      // Construct the output using a BUILD_VECTOR.
6337      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6338                              SVOps.size());
6339    } else if (InputUsed[0] < 0) {
6340      // No input vectors were used! The result is undefined.
6341      Output[l] = DAG.getUNDEF(NVT);
6342    } else {
6343      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6344                                        (InputUsed[0] % 2) * NumLaneElems,
6345                                        DAG, dl);
6346      // If only one input was used, use an undefined vector for the other.
6347      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6348        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6349                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6350      // At least one input vector was used. Create a new shuffle vector.
6351      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6352    }
6353
6354    Mask.clear();
6355  }
6356
6357  // Concatenate the result back
6358  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6359}
6360
6361/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6362/// 4 elements, and match them with several different shuffle types.
6363static SDValue
6364LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6365  SDValue V1 = SVOp->getOperand(0);
6366  SDValue V2 = SVOp->getOperand(1);
6367  DebugLoc dl = SVOp->getDebugLoc();
6368  MVT VT = SVOp->getValueType(0).getSimpleVT();
6369
6370  assert(VT.is128BitVector() && "Unsupported vector size");
6371
6372  std::pair<int, int> Locs[4];
6373  int Mask1[] = { -1, -1, -1, -1 };
6374  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6375
6376  unsigned NumHi = 0;
6377  unsigned NumLo = 0;
6378  for (unsigned i = 0; i != 4; ++i) {
6379    int Idx = PermMask[i];
6380    if (Idx < 0) {
6381      Locs[i] = std::make_pair(-1, -1);
6382    } else {
6383      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6384      if (Idx < 4) {
6385        Locs[i] = std::make_pair(0, NumLo);
6386        Mask1[NumLo] = Idx;
6387        NumLo++;
6388      } else {
6389        Locs[i] = std::make_pair(1, NumHi);
6390        if (2+NumHi < 4)
6391          Mask1[2+NumHi] = Idx;
6392        NumHi++;
6393      }
6394    }
6395  }
6396
6397  if (NumLo <= 2 && NumHi <= 2) {
6398    // If no more than two elements come from either vector. This can be
6399    // implemented with two shuffles. First shuffle gather the elements.
6400    // The second shuffle, which takes the first shuffle as both of its
6401    // vector operands, put the elements into the right order.
6402    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6403
6404    int Mask2[] = { -1, -1, -1, -1 };
6405
6406    for (unsigned i = 0; i != 4; ++i)
6407      if (Locs[i].first != -1) {
6408        unsigned Idx = (i < 2) ? 0 : 4;
6409        Idx += Locs[i].first * 2 + Locs[i].second;
6410        Mask2[i] = Idx;
6411      }
6412
6413    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6414  }
6415
6416  if (NumLo == 3 || NumHi == 3) {
6417    // Otherwise, we must have three elements from one vector, call it X, and
6418    // one element from the other, call it Y.  First, use a shufps to build an
6419    // intermediate vector with the one element from Y and the element from X
6420    // that will be in the same half in the final destination (the indexes don't
6421    // matter). Then, use a shufps to build the final vector, taking the half
6422    // containing the element from Y from the intermediate, and the other half
6423    // from X.
6424    if (NumHi == 3) {
6425      // Normalize it so the 3 elements come from V1.
6426      CommuteVectorShuffleMask(PermMask, 4);
6427      std::swap(V1, V2);
6428    }
6429
6430    // Find the element from V2.
6431    unsigned HiIndex;
6432    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6433      int Val = PermMask[HiIndex];
6434      if (Val < 0)
6435        continue;
6436      if (Val >= 4)
6437        break;
6438    }
6439
6440    Mask1[0] = PermMask[HiIndex];
6441    Mask1[1] = -1;
6442    Mask1[2] = PermMask[HiIndex^1];
6443    Mask1[3] = -1;
6444    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6445
6446    if (HiIndex >= 2) {
6447      Mask1[0] = PermMask[0];
6448      Mask1[1] = PermMask[1];
6449      Mask1[2] = HiIndex & 1 ? 6 : 4;
6450      Mask1[3] = HiIndex & 1 ? 4 : 6;
6451      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6452    }
6453
6454    Mask1[0] = HiIndex & 1 ? 2 : 0;
6455    Mask1[1] = HiIndex & 1 ? 0 : 2;
6456    Mask1[2] = PermMask[2];
6457    Mask1[3] = PermMask[3];
6458    if (Mask1[2] >= 0)
6459      Mask1[2] += 4;
6460    if (Mask1[3] >= 0)
6461      Mask1[3] += 4;
6462    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6463  }
6464
6465  // Break it into (shuffle shuffle_hi, shuffle_lo).
6466  int LoMask[] = { -1, -1, -1, -1 };
6467  int HiMask[] = { -1, -1, -1, -1 };
6468
6469  int *MaskPtr = LoMask;
6470  unsigned MaskIdx = 0;
6471  unsigned LoIdx = 0;
6472  unsigned HiIdx = 2;
6473  for (unsigned i = 0; i != 4; ++i) {
6474    if (i == 2) {
6475      MaskPtr = HiMask;
6476      MaskIdx = 1;
6477      LoIdx = 0;
6478      HiIdx = 2;
6479    }
6480    int Idx = PermMask[i];
6481    if (Idx < 0) {
6482      Locs[i] = std::make_pair(-1, -1);
6483    } else if (Idx < 4) {
6484      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6485      MaskPtr[LoIdx] = Idx;
6486      LoIdx++;
6487    } else {
6488      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6489      MaskPtr[HiIdx] = Idx;
6490      HiIdx++;
6491    }
6492  }
6493
6494  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6495  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6496  int MaskOps[] = { -1, -1, -1, -1 };
6497  for (unsigned i = 0; i != 4; ++i)
6498    if (Locs[i].first != -1)
6499      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6500  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6501}
6502
6503static bool MayFoldVectorLoad(SDValue V) {
6504  while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6505    V = V.getOperand(0);
6506
6507  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6508    V = V.getOperand(0);
6509  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6510      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6511    // BUILD_VECTOR (load), undef
6512    V = V.getOperand(0);
6513
6514  return MayFoldLoad(V);
6515}
6516
6517static
6518SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6519  EVT VT = Op.getValueType();
6520
6521  // Canonizalize to v2f64.
6522  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6523  return DAG.getNode(ISD::BITCAST, dl, VT,
6524                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6525                                          V1, DAG));
6526}
6527
6528static
6529SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6530                        bool HasSSE2) {
6531  SDValue V1 = Op.getOperand(0);
6532  SDValue V2 = Op.getOperand(1);
6533  EVT VT = Op.getValueType();
6534
6535  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6536
6537  if (HasSSE2 && VT == MVT::v2f64)
6538    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6539
6540  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6541  return DAG.getNode(ISD::BITCAST, dl, VT,
6542                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6543                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6544                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6545}
6546
6547static
6548SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6549  SDValue V1 = Op.getOperand(0);
6550  SDValue V2 = Op.getOperand(1);
6551  EVT VT = Op.getValueType();
6552
6553  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6554         "unsupported shuffle type");
6555
6556  if (V2.getOpcode() == ISD::UNDEF)
6557    V2 = V1;
6558
6559  // v4i32 or v4f32
6560  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6561}
6562
6563static
6564SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6565  SDValue V1 = Op.getOperand(0);
6566  SDValue V2 = Op.getOperand(1);
6567  EVT VT = Op.getValueType();
6568  unsigned NumElems = VT.getVectorNumElements();
6569
6570  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6571  // operand of these instructions is only memory, so check if there's a
6572  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6573  // same masks.
6574  bool CanFoldLoad = false;
6575
6576  // Trivial case, when V2 comes from a load.
6577  if (MayFoldVectorLoad(V2))
6578    CanFoldLoad = true;
6579
6580  // When V1 is a load, it can be folded later into a store in isel, example:
6581  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6582  //    turns into:
6583  //  (MOVLPSmr addr:$src1, VR128:$src2)
6584  // So, recognize this potential and also use MOVLPS or MOVLPD
6585  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6586    CanFoldLoad = true;
6587
6588  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6589  if (CanFoldLoad) {
6590    if (HasSSE2 && NumElems == 2)
6591      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6592
6593    if (NumElems == 4)
6594      // If we don't care about the second element, proceed to use movss.
6595      if (SVOp->getMaskElt(1) != -1)
6596        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6597  }
6598
6599  // movl and movlp will both match v2i64, but v2i64 is never matched by
6600  // movl earlier because we make it strict to avoid messing with the movlp load
6601  // folding logic (see the code above getMOVLP call). Match it here then,
6602  // this is horrible, but will stay like this until we move all shuffle
6603  // matching to x86 specific nodes. Note that for the 1st condition all
6604  // types are matched with movsd.
6605  if (HasSSE2) {
6606    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6607    // as to remove this logic from here, as much as possible
6608    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6609      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6610    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6611  }
6612
6613  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6614
6615  // Invert the operand order and use SHUFPS to match it.
6616  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6617                              getShuffleSHUFImmediate(SVOp), DAG);
6618}
6619
6620// Reduce a vector shuffle to zext.
6621SDValue
6622X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6623  // PMOVZX is only available from SSE41.
6624  if (!Subtarget->hasSSE41())
6625    return SDValue();
6626
6627  EVT VT = Op.getValueType();
6628
6629  // Only AVX2 support 256-bit vector integer extending.
6630  if (!Subtarget->hasInt256() && VT.is256BitVector())
6631    return SDValue();
6632
6633  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6634  DebugLoc DL = Op.getDebugLoc();
6635  SDValue V1 = Op.getOperand(0);
6636  SDValue V2 = Op.getOperand(1);
6637  unsigned NumElems = VT.getVectorNumElements();
6638
6639  // Extending is an unary operation and the element type of the source vector
6640  // won't be equal to or larger than i64.
6641  if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6642      VT.getVectorElementType() == MVT::i64)
6643    return SDValue();
6644
6645  // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6646  unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6647  while ((1U << Shift) < NumElems) {
6648    if (SVOp->getMaskElt(1U << Shift) == 1)
6649      break;
6650    Shift += 1;
6651    // The maximal ratio is 8, i.e. from i8 to i64.
6652    if (Shift > 3)
6653      return SDValue();
6654  }
6655
6656  // Check the shuffle mask.
6657  unsigned Mask = (1U << Shift) - 1;
6658  for (unsigned i = 0; i != NumElems; ++i) {
6659    int EltIdx = SVOp->getMaskElt(i);
6660    if ((i & Mask) != 0 && EltIdx != -1)
6661      return SDValue();
6662    if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6663      return SDValue();
6664  }
6665
6666  LLVMContext *Context = DAG.getContext();
6667  unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6668  EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6669  EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6670
6671  if (!isTypeLegal(NVT))
6672    return SDValue();
6673
6674  // Simplify the operand as it's prepared to be fed into shuffle.
6675  unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6676  if (V1.getOpcode() == ISD::BITCAST &&
6677      V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6678      V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6679      V1.getOperand(0)
6680        .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6681    // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6682    SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6683    ConstantSDNode *CIdx =
6684      dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6685    // If it's foldable, i.e. normal load with single use, we will let code
6686    // selection to fold it. Otherwise, we will short the conversion sequence.
6687    if (CIdx && CIdx->getZExtValue() == 0 &&
6688        (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6689      if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6690        // The "ext_vec_elt" node is wider than the result node.
6691        // In this case we should extract subvector from V.
6692        // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6693        unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6694        EVT FullVT = V.getValueType();
6695        EVT SubVecVT = EVT::getVectorVT(*Context,
6696                                        FullVT.getVectorElementType(),
6697                                        FullVT.getVectorNumElements()/Ratio);
6698        V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6699                        DAG.getIntPtrConstant(0));
6700      }
6701      V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6702    }
6703  }
6704
6705  return DAG.getNode(ISD::BITCAST, DL, VT,
6706                     DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6707}
6708
6709SDValue
6710X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6711  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6712  MVT VT = Op.getValueType().getSimpleVT();
6713  DebugLoc dl = Op.getDebugLoc();
6714  SDValue V1 = Op.getOperand(0);
6715  SDValue V2 = Op.getOperand(1);
6716
6717  if (isZeroShuffle(SVOp))
6718    return getZeroVector(VT, Subtarget, DAG, dl);
6719
6720  // Handle splat operations
6721  if (SVOp->isSplat()) {
6722    // Use vbroadcast whenever the splat comes from a foldable load
6723    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6724    if (Broadcast.getNode())
6725      return Broadcast;
6726  }
6727
6728  // Check integer expanding shuffles.
6729  SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6730  if (NewOp.getNode())
6731    return NewOp;
6732
6733  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6734  // do it!
6735  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6736      VT == MVT::v16i16 || VT == MVT::v32i8) {
6737    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6738    if (NewOp.getNode())
6739      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6740  } else if ((VT == MVT::v4i32 ||
6741             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6742    // FIXME: Figure out a cleaner way to do this.
6743    // Try to make use of movq to zero out the top part.
6744    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6745      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6746      if (NewOp.getNode()) {
6747        MVT NewVT = NewOp.getValueType().getSimpleVT();
6748        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6749                               NewVT, true, false))
6750          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6751                              DAG, Subtarget, dl);
6752      }
6753    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6754      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6755      if (NewOp.getNode()) {
6756        MVT NewVT = NewOp.getValueType().getSimpleVT();
6757        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6758          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6759                              DAG, Subtarget, dl);
6760      }
6761    }
6762  }
6763  return SDValue();
6764}
6765
6766SDValue
6767X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6768  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6769  SDValue V1 = Op.getOperand(0);
6770  SDValue V2 = Op.getOperand(1);
6771  MVT VT = Op.getValueType().getSimpleVT();
6772  DebugLoc dl = Op.getDebugLoc();
6773  unsigned NumElems = VT.getVectorNumElements();
6774  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6775  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6776  bool V1IsSplat = false;
6777  bool V2IsSplat = false;
6778  bool HasSSE2 = Subtarget->hasSSE2();
6779  bool HasFp256    = Subtarget->hasFp256();
6780  bool HasInt256   = Subtarget->hasInt256();
6781  MachineFunction &MF = DAG.getMachineFunction();
6782  bool OptForSize = MF.getFunction()->getAttributes().
6783    hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6784
6785  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6786
6787  if (V1IsUndef && V2IsUndef)
6788    return DAG.getUNDEF(VT);
6789
6790  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6791
6792  // Vector shuffle lowering takes 3 steps:
6793  //
6794  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6795  //    narrowing and commutation of operands should be handled.
6796  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6797  //    shuffle nodes.
6798  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6799  //    so the shuffle can be broken into other shuffles and the legalizer can
6800  //    try the lowering again.
6801  //
6802  // The general idea is that no vector_shuffle operation should be left to
6803  // be matched during isel, all of them must be converted to a target specific
6804  // node here.
6805
6806  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6807  // narrowing and commutation of operands should be handled. The actual code
6808  // doesn't include all of those, work in progress...
6809  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6810  if (NewOp.getNode())
6811    return NewOp;
6812
6813  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6814
6815  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6816  // unpckh_undef). Only use pshufd if speed is more important than size.
6817  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6818    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6819  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6820    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6821
6822  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6823      V2IsUndef && MayFoldVectorLoad(V1))
6824    return getMOVDDup(Op, dl, V1, DAG);
6825
6826  if (isMOVHLPS_v_undef_Mask(M, VT))
6827    return getMOVHighToLow(Op, dl, DAG);
6828
6829  // Use to match splats
6830  if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6831      (VT == MVT::v2f64 || VT == MVT::v2i64))
6832    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6833
6834  if (isPSHUFDMask(M, VT)) {
6835    // The actual implementation will match the mask in the if above and then
6836    // during isel it can match several different instructions, not only pshufd
6837    // as its name says, sad but true, emulate the behavior for now...
6838    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6839      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6840
6841    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6842
6843    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6844      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6845
6846    if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6847      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6848                                  DAG);
6849
6850    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6851                                TargetMask, DAG);
6852  }
6853
6854  // Check if this can be converted into a logical shift.
6855  bool isLeft = false;
6856  unsigned ShAmt = 0;
6857  SDValue ShVal;
6858  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6859  if (isShift && ShVal.hasOneUse()) {
6860    // If the shifted value has multiple uses, it may be cheaper to use
6861    // v_set0 + movlhps or movhlps, etc.
6862    MVT EltVT = VT.getVectorElementType();
6863    ShAmt *= EltVT.getSizeInBits();
6864    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6865  }
6866
6867  if (isMOVLMask(M, VT)) {
6868    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6869      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6870    if (!isMOVLPMask(M, VT)) {
6871      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6872        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6873
6874      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6875        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6876    }
6877  }
6878
6879  // FIXME: fold these into legal mask.
6880  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6881    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6882
6883  if (isMOVHLPSMask(M, VT))
6884    return getMOVHighToLow(Op, dl, DAG);
6885
6886  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6887    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6888
6889  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6890    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6891
6892  if (isMOVLPMask(M, VT))
6893    return getMOVLP(Op, dl, DAG, HasSSE2);
6894
6895  if (ShouldXformToMOVHLPS(M, VT) ||
6896      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6897    return CommuteVectorShuffle(SVOp, DAG);
6898
6899  if (isShift) {
6900    // No better options. Use a vshldq / vsrldq.
6901    MVT EltVT = VT.getVectorElementType();
6902    ShAmt *= EltVT.getSizeInBits();
6903    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6904  }
6905
6906  bool Commuted = false;
6907  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6908  // 1,1,1,1 -> v8i16 though.
6909  V1IsSplat = isSplatVector(V1.getNode());
6910  V2IsSplat = isSplatVector(V2.getNode());
6911
6912  // Canonicalize the splat or undef, if present, to be on the RHS.
6913  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6914    CommuteVectorShuffleMask(M, NumElems);
6915    std::swap(V1, V2);
6916    std::swap(V1IsSplat, V2IsSplat);
6917    Commuted = true;
6918  }
6919
6920  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6921    // Shuffling low element of v1 into undef, just return v1.
6922    if (V2IsUndef)
6923      return V1;
6924    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6925    // the instruction selector will not match, so get a canonical MOVL with
6926    // swapped operands to undo the commute.
6927    return getMOVL(DAG, dl, VT, V2, V1);
6928  }
6929
6930  if (isUNPCKLMask(M, VT, HasInt256))
6931    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6932
6933  if (isUNPCKHMask(M, VT, HasInt256))
6934    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6935
6936  if (V2IsSplat) {
6937    // Normalize mask so all entries that point to V2 points to its first
6938    // element then try to match unpck{h|l} again. If match, return a
6939    // new vector_shuffle with the corrected mask.p
6940    SmallVector<int, 8> NewMask(M.begin(), M.end());
6941    NormalizeMask(NewMask, NumElems);
6942    if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6943      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6944    if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6945      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6946  }
6947
6948  if (Commuted) {
6949    // Commute is back and try unpck* again.
6950    // FIXME: this seems wrong.
6951    CommuteVectorShuffleMask(M, NumElems);
6952    std::swap(V1, V2);
6953    std::swap(V1IsSplat, V2IsSplat);
6954    Commuted = false;
6955
6956    if (isUNPCKLMask(M, VT, HasInt256))
6957      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6958
6959    if (isUNPCKHMask(M, VT, HasInt256))
6960      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6961  }
6962
6963  // Normalize the node to match x86 shuffle ops if needed
6964  if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6965    return CommuteVectorShuffle(SVOp, DAG);
6966
6967  // The checks below are all present in isShuffleMaskLegal, but they are
6968  // inlined here right now to enable us to directly emit target specific
6969  // nodes, and remove one by one until they don't return Op anymore.
6970
6971  if (isPALIGNRMask(M, VT, Subtarget))
6972    return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6973                                getShufflePALIGNRImmediate(SVOp),
6974                                DAG);
6975
6976  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6977      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6978    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6979      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6980  }
6981
6982  if (isPSHUFHWMask(M, VT, HasInt256))
6983    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6984                                getShufflePSHUFHWImmediate(SVOp),
6985                                DAG);
6986
6987  if (isPSHUFLWMask(M, VT, HasInt256))
6988    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6989                                getShufflePSHUFLWImmediate(SVOp),
6990                                DAG);
6991
6992  if (isSHUFPMask(M, VT, HasFp256))
6993    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6994                                getShuffleSHUFImmediate(SVOp), DAG);
6995
6996  if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6997    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6998  if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6999    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7000
7001  //===--------------------------------------------------------------------===//
7002  // Generate target specific nodes for 128 or 256-bit shuffles only
7003  // supported in the AVX instruction set.
7004  //
7005
7006  // Handle VMOVDDUPY permutations
7007  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7008    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7009
7010  // Handle VPERMILPS/D* permutations
7011  if (isVPERMILPMask(M, VT, HasFp256)) {
7012    if (HasInt256 && VT == MVT::v8i32)
7013      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7014                                  getShuffleSHUFImmediate(SVOp), DAG);
7015    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7016                                getShuffleSHUFImmediate(SVOp), DAG);
7017  }
7018
7019  // Handle VPERM2F128/VPERM2I128 permutations
7020  if (isVPERM2X128Mask(M, VT, HasFp256))
7021    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7022                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7023
7024  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7025  if (BlendOp.getNode())
7026    return BlendOp;
7027
7028  if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7029    SmallVector<SDValue, 8> permclMask;
7030    for (unsigned i = 0; i != 8; ++i) {
7031      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7032    }
7033    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7034                               &permclMask[0], 8);
7035    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7036    return DAG.getNode(X86ISD::VPERMV, dl, VT,
7037                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7038  }
7039
7040  if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7041    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7042                                getShuffleCLImmediate(SVOp), DAG);
7043
7044  //===--------------------------------------------------------------------===//
7045  // Since no target specific shuffle was selected for this generic one,
7046  // lower it into other known shuffles. FIXME: this isn't true yet, but
7047  // this is the plan.
7048  //
7049
7050  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7051  if (VT == MVT::v8i16) {
7052    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7053    if (NewOp.getNode())
7054      return NewOp;
7055  }
7056
7057  if (VT == MVT::v16i8) {
7058    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7059    if (NewOp.getNode())
7060      return NewOp;
7061  }
7062
7063  if (VT == MVT::v32i8) {
7064    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7065    if (NewOp.getNode())
7066      return NewOp;
7067  }
7068
7069  // Handle all 128-bit wide vectors with 4 elements, and match them with
7070  // several different shuffle types.
7071  if (NumElems == 4 && VT.is128BitVector())
7072    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7073
7074  // Handle general 256-bit shuffles
7075  if (VT.is256BitVector())
7076    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7077
7078  return SDValue();
7079}
7080
7081static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7082  MVT VT = Op.getValueType().getSimpleVT();
7083  DebugLoc dl = Op.getDebugLoc();
7084
7085  if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7086    return SDValue();
7087
7088  if (VT.getSizeInBits() == 8) {
7089    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7090                                  Op.getOperand(0), Op.getOperand(1));
7091    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7092                                  DAG.getValueType(VT));
7093    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7094  }
7095
7096  if (VT.getSizeInBits() == 16) {
7097    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7098    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7099    if (Idx == 0)
7100      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7101                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7102                                     DAG.getNode(ISD::BITCAST, dl,
7103                                                 MVT::v4i32,
7104                                                 Op.getOperand(0)),
7105                                     Op.getOperand(1)));
7106    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7107                                  Op.getOperand(0), Op.getOperand(1));
7108    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7109                                  DAG.getValueType(VT));
7110    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7111  }
7112
7113  if (VT == MVT::f32) {
7114    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7115    // the result back to FR32 register. It's only worth matching if the
7116    // result has a single use which is a store or a bitcast to i32.  And in
7117    // the case of a store, it's not worth it if the index is a constant 0,
7118    // because a MOVSSmr can be used instead, which is smaller and faster.
7119    if (!Op.hasOneUse())
7120      return SDValue();
7121    SDNode *User = *Op.getNode()->use_begin();
7122    if ((User->getOpcode() != ISD::STORE ||
7123         (isa<ConstantSDNode>(Op.getOperand(1)) &&
7124          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7125        (User->getOpcode() != ISD::BITCAST ||
7126         User->getValueType(0) != MVT::i32))
7127      return SDValue();
7128    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7129                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7130                                              Op.getOperand(0)),
7131                                              Op.getOperand(1));
7132    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7133  }
7134
7135  if (VT == MVT::i32 || VT == MVT::i64) {
7136    // ExtractPS/pextrq works with constant index.
7137    if (isa<ConstantSDNode>(Op.getOperand(1)))
7138      return Op;
7139  }
7140  return SDValue();
7141}
7142
7143SDValue
7144X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7145                                           SelectionDAG &DAG) const {
7146  if (!isa<ConstantSDNode>(Op.getOperand(1)))
7147    return SDValue();
7148
7149  SDValue Vec = Op.getOperand(0);
7150  MVT VecVT = Vec.getValueType().getSimpleVT();
7151
7152  // If this is a 256-bit vector result, first extract the 128-bit vector and
7153  // then extract the element from the 128-bit vector.
7154  if (VecVT.is256BitVector()) {
7155    DebugLoc dl = Op.getNode()->getDebugLoc();
7156    unsigned NumElems = VecVT.getVectorNumElements();
7157    SDValue Idx = Op.getOperand(1);
7158    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7159
7160    // Get the 128-bit vector.
7161    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7162
7163    if (IdxVal >= NumElems/2)
7164      IdxVal -= NumElems/2;
7165    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7166                       DAG.getConstant(IdxVal, MVT::i32));
7167  }
7168
7169  assert(VecVT.is128BitVector() && "Unexpected vector length");
7170
7171  if (Subtarget->hasSSE41()) {
7172    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7173    if (Res.getNode())
7174      return Res;
7175  }
7176
7177  MVT VT = Op.getValueType().getSimpleVT();
7178  DebugLoc dl = Op.getDebugLoc();
7179  // TODO: handle v16i8.
7180  if (VT.getSizeInBits() == 16) {
7181    SDValue Vec = Op.getOperand(0);
7182    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7183    if (Idx == 0)
7184      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7185                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7186                                     DAG.getNode(ISD::BITCAST, dl,
7187                                                 MVT::v4i32, Vec),
7188                                     Op.getOperand(1)));
7189    // Transform it so it match pextrw which produces a 32-bit result.
7190    MVT EltVT = MVT::i32;
7191    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7192                                  Op.getOperand(0), Op.getOperand(1));
7193    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7194                                  DAG.getValueType(VT));
7195    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7196  }
7197
7198  if (VT.getSizeInBits() == 32) {
7199    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7200    if (Idx == 0)
7201      return Op;
7202
7203    // SHUFPS the element to the lowest double word, then movss.
7204    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7205    MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7206    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7207                                       DAG.getUNDEF(VVT), Mask);
7208    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7209                       DAG.getIntPtrConstant(0));
7210  }
7211
7212  if (VT.getSizeInBits() == 64) {
7213    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7214    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7215    //        to match extract_elt for f64.
7216    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7217    if (Idx == 0)
7218      return Op;
7219
7220    // UNPCKHPD the element to the lowest double word, then movsd.
7221    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7222    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7223    int Mask[2] = { 1, -1 };
7224    MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7225    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7226                                       DAG.getUNDEF(VVT), Mask);
7227    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7228                       DAG.getIntPtrConstant(0));
7229  }
7230
7231  return SDValue();
7232}
7233
7234static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7235  MVT VT = Op.getValueType().getSimpleVT();
7236  MVT EltVT = VT.getVectorElementType();
7237  DebugLoc dl = Op.getDebugLoc();
7238
7239  SDValue N0 = Op.getOperand(0);
7240  SDValue N1 = Op.getOperand(1);
7241  SDValue N2 = Op.getOperand(2);
7242
7243  if (!VT.is128BitVector())
7244    return SDValue();
7245
7246  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7247      isa<ConstantSDNode>(N2)) {
7248    unsigned Opc;
7249    if (VT == MVT::v8i16)
7250      Opc = X86ISD::PINSRW;
7251    else if (VT == MVT::v16i8)
7252      Opc = X86ISD::PINSRB;
7253    else
7254      Opc = X86ISD::PINSRB;
7255
7256    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7257    // argument.
7258    if (N1.getValueType() != MVT::i32)
7259      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7260    if (N2.getValueType() != MVT::i32)
7261      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7262    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7263  }
7264
7265  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7266    // Bits [7:6] of the constant are the source select.  This will always be
7267    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7268    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7269    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7270    // Bits [5:4] of the constant are the destination select.  This is the
7271    //  value of the incoming immediate.
7272    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7273    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7274    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7275    // Create this as a scalar to vector..
7276    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7277    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7278  }
7279
7280  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7281    // PINSR* works with constant index.
7282    return Op;
7283  }
7284  return SDValue();
7285}
7286
7287SDValue
7288X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7289  MVT VT = Op.getValueType().getSimpleVT();
7290  MVT EltVT = VT.getVectorElementType();
7291
7292  DebugLoc dl = Op.getDebugLoc();
7293  SDValue N0 = Op.getOperand(0);
7294  SDValue N1 = Op.getOperand(1);
7295  SDValue N2 = Op.getOperand(2);
7296
7297  // If this is a 256-bit vector result, first extract the 128-bit vector,
7298  // insert the element into the extracted half and then place it back.
7299  if (VT.is256BitVector()) {
7300    if (!isa<ConstantSDNode>(N2))
7301      return SDValue();
7302
7303    // Get the desired 128-bit vector half.
7304    unsigned NumElems = VT.getVectorNumElements();
7305    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7306    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7307
7308    // Insert the element into the desired half.
7309    bool Upper = IdxVal >= NumElems/2;
7310    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7311                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7312
7313    // Insert the changed part back to the 256-bit vector
7314    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7315  }
7316
7317  if (Subtarget->hasSSE41())
7318    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7319
7320  if (EltVT == MVT::i8)
7321    return SDValue();
7322
7323  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7324    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7325    // as its second argument.
7326    if (N1.getValueType() != MVT::i32)
7327      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7328    if (N2.getValueType() != MVT::i32)
7329      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7330    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7331  }
7332  return SDValue();
7333}
7334
7335static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7336  LLVMContext *Context = DAG.getContext();
7337  DebugLoc dl = Op.getDebugLoc();
7338  MVT OpVT = Op.getValueType().getSimpleVT();
7339
7340  // If this is a 256-bit vector result, first insert into a 128-bit
7341  // vector and then insert into the 256-bit vector.
7342  if (!OpVT.is128BitVector()) {
7343    // Insert into a 128-bit vector.
7344    EVT VT128 = EVT::getVectorVT(*Context,
7345                                 OpVT.getVectorElementType(),
7346                                 OpVT.getVectorNumElements() / 2);
7347
7348    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7349
7350    // Insert the 128-bit vector.
7351    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7352  }
7353
7354  if (OpVT == MVT::v1i64 &&
7355      Op.getOperand(0).getValueType() == MVT::i64)
7356    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7357
7358  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7359  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7360  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7361                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7362}
7363
7364// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7365// a simple subregister reference or explicit instructions to grab
7366// upper bits of a vector.
7367static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7368                                      SelectionDAG &DAG) {
7369  if (Subtarget->hasFp256()) {
7370    DebugLoc dl = Op.getNode()->getDebugLoc();
7371    SDValue Vec = Op.getNode()->getOperand(0);
7372    SDValue Idx = Op.getNode()->getOperand(1);
7373
7374    if (Op.getNode()->getValueType(0).is128BitVector() &&
7375        Vec.getNode()->getValueType(0).is256BitVector() &&
7376        isa<ConstantSDNode>(Idx)) {
7377      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7378      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7379    }
7380  }
7381  return SDValue();
7382}
7383
7384// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7385// simple superregister reference or explicit instructions to insert
7386// the upper bits of a vector.
7387static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7388                                     SelectionDAG &DAG) {
7389  if (Subtarget->hasFp256()) {
7390    DebugLoc dl = Op.getNode()->getDebugLoc();
7391    SDValue Vec = Op.getNode()->getOperand(0);
7392    SDValue SubVec = Op.getNode()->getOperand(1);
7393    SDValue Idx = Op.getNode()->getOperand(2);
7394
7395    if (Op.getNode()->getValueType(0).is256BitVector() &&
7396        SubVec.getNode()->getValueType(0).is128BitVector() &&
7397        isa<ConstantSDNode>(Idx)) {
7398      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7399      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7400    }
7401  }
7402  return SDValue();
7403}
7404
7405// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7406// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7407// one of the above mentioned nodes. It has to be wrapped because otherwise
7408// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7409// be used to form addressing mode. These wrapped nodes will be selected
7410// into MOV32ri.
7411SDValue
7412X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7413  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7414
7415  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7416  // global base reg.
7417  unsigned char OpFlag = 0;
7418  unsigned WrapperKind = X86ISD::Wrapper;
7419  CodeModel::Model M = getTargetMachine().getCodeModel();
7420
7421  if (Subtarget->isPICStyleRIPRel() &&
7422      (M == CodeModel::Small || M == CodeModel::Kernel))
7423    WrapperKind = X86ISD::WrapperRIP;
7424  else if (Subtarget->isPICStyleGOT())
7425    OpFlag = X86II::MO_GOTOFF;
7426  else if (Subtarget->isPICStyleStubPIC())
7427    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7428
7429  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7430                                             CP->getAlignment(),
7431                                             CP->getOffset(), OpFlag);
7432  DebugLoc DL = CP->getDebugLoc();
7433  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7434  // With PIC, the address is actually $g + Offset.
7435  if (OpFlag) {
7436    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7437                         DAG.getNode(X86ISD::GlobalBaseReg,
7438                                     DebugLoc(), getPointerTy()),
7439                         Result);
7440  }
7441
7442  return Result;
7443}
7444
7445SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7446  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7447
7448  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7449  // global base reg.
7450  unsigned char OpFlag = 0;
7451  unsigned WrapperKind = X86ISD::Wrapper;
7452  CodeModel::Model M = getTargetMachine().getCodeModel();
7453
7454  if (Subtarget->isPICStyleRIPRel() &&
7455      (M == CodeModel::Small || M == CodeModel::Kernel))
7456    WrapperKind = X86ISD::WrapperRIP;
7457  else if (Subtarget->isPICStyleGOT())
7458    OpFlag = X86II::MO_GOTOFF;
7459  else if (Subtarget->isPICStyleStubPIC())
7460    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7461
7462  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7463                                          OpFlag);
7464  DebugLoc DL = JT->getDebugLoc();
7465  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7466
7467  // With PIC, the address is actually $g + Offset.
7468  if (OpFlag)
7469    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7470                         DAG.getNode(X86ISD::GlobalBaseReg,
7471                                     DebugLoc(), getPointerTy()),
7472                         Result);
7473
7474  return Result;
7475}
7476
7477SDValue
7478X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7479  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7480
7481  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7482  // global base reg.
7483  unsigned char OpFlag = 0;
7484  unsigned WrapperKind = X86ISD::Wrapper;
7485  CodeModel::Model M = getTargetMachine().getCodeModel();
7486
7487  if (Subtarget->isPICStyleRIPRel() &&
7488      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7489    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7490      OpFlag = X86II::MO_GOTPCREL;
7491    WrapperKind = X86ISD::WrapperRIP;
7492  } else if (Subtarget->isPICStyleGOT()) {
7493    OpFlag = X86II::MO_GOT;
7494  } else if (Subtarget->isPICStyleStubPIC()) {
7495    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7496  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7497    OpFlag = X86II::MO_DARWIN_NONLAZY;
7498  }
7499
7500  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7501
7502  DebugLoc DL = Op.getDebugLoc();
7503  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7504
7505  // With PIC, the address is actually $g + Offset.
7506  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7507      !Subtarget->is64Bit()) {
7508    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7509                         DAG.getNode(X86ISD::GlobalBaseReg,
7510                                     DebugLoc(), getPointerTy()),
7511                         Result);
7512  }
7513
7514  // For symbols that require a load from a stub to get the address, emit the
7515  // load.
7516  if (isGlobalStubReference(OpFlag))
7517    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7518                         MachinePointerInfo::getGOT(), false, false, false, 0);
7519
7520  return Result;
7521}
7522
7523SDValue
7524X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7525  // Create the TargetBlockAddressAddress node.
7526  unsigned char OpFlags =
7527    Subtarget->ClassifyBlockAddressReference();
7528  CodeModel::Model M = getTargetMachine().getCodeModel();
7529  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7530  int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7531  DebugLoc dl = Op.getDebugLoc();
7532  SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7533                                             OpFlags);
7534
7535  if (Subtarget->isPICStyleRIPRel() &&
7536      (M == CodeModel::Small || M == CodeModel::Kernel))
7537    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7538  else
7539    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7540
7541  // With PIC, the address is actually $g + Offset.
7542  if (isGlobalRelativeToPICBase(OpFlags)) {
7543    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7544                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7545                         Result);
7546  }
7547
7548  return Result;
7549}
7550
7551SDValue
7552X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7553                                      int64_t Offset, SelectionDAG &DAG) const {
7554  // Create the TargetGlobalAddress node, folding in the constant
7555  // offset if it is legal.
7556  unsigned char OpFlags =
7557    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7558  CodeModel::Model M = getTargetMachine().getCodeModel();
7559  SDValue Result;
7560  if (OpFlags == X86II::MO_NO_FLAG &&
7561      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7562    // A direct static reference to a global.
7563    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7564    Offset = 0;
7565  } else {
7566    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7567  }
7568
7569  if (Subtarget->isPICStyleRIPRel() &&
7570      (M == CodeModel::Small || M == CodeModel::Kernel))
7571    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7572  else
7573    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7574
7575  // With PIC, the address is actually $g + Offset.
7576  if (isGlobalRelativeToPICBase(OpFlags)) {
7577    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7578                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7579                         Result);
7580  }
7581
7582  // For globals that require a load from a stub to get the address, emit the
7583  // load.
7584  if (isGlobalStubReference(OpFlags))
7585    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7586                         MachinePointerInfo::getGOT(), false, false, false, 0);
7587
7588  // If there was a non-zero offset that we didn't fold, create an explicit
7589  // addition for it.
7590  if (Offset != 0)
7591    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7592                         DAG.getConstant(Offset, getPointerTy()));
7593
7594  return Result;
7595}
7596
7597SDValue
7598X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7599  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7600  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7601  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7602}
7603
7604static SDValue
7605GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7606           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7607           unsigned char OperandFlags, bool LocalDynamic = false) {
7608  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7609  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7610  DebugLoc dl = GA->getDebugLoc();
7611  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7612                                           GA->getValueType(0),
7613                                           GA->getOffset(),
7614                                           OperandFlags);
7615
7616  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7617                                           : X86ISD::TLSADDR;
7618
7619  if (InFlag) {
7620    SDValue Ops[] = { Chain,  TGA, *InFlag };
7621    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7622  } else {
7623    SDValue Ops[]  = { Chain, TGA };
7624    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7625  }
7626
7627  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7628  MFI->setAdjustsStack(true);
7629
7630  SDValue Flag = Chain.getValue(1);
7631  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7632}
7633
7634// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7635static SDValue
7636LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7637                                const EVT PtrVT) {
7638  SDValue InFlag;
7639  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7640  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7641                                   DAG.getNode(X86ISD::GlobalBaseReg,
7642                                               DebugLoc(), PtrVT), InFlag);
7643  InFlag = Chain.getValue(1);
7644
7645  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7646}
7647
7648// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7649static SDValue
7650LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7651                                const EVT PtrVT) {
7652  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7653                    X86::RAX, X86II::MO_TLSGD);
7654}
7655
7656static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7657                                           SelectionDAG &DAG,
7658                                           const EVT PtrVT,
7659                                           bool is64Bit) {
7660  DebugLoc dl = GA->getDebugLoc();
7661
7662  // Get the start address of the TLS block for this module.
7663  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7664      .getInfo<X86MachineFunctionInfo>();
7665  MFI->incNumLocalDynamicTLSAccesses();
7666
7667  SDValue Base;
7668  if (is64Bit) {
7669    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7670                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7671  } else {
7672    SDValue InFlag;
7673    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7674        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7675    InFlag = Chain.getValue(1);
7676    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7677                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7678  }
7679
7680  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7681  // of Base.
7682
7683  // Build x@dtpoff.
7684  unsigned char OperandFlags = X86II::MO_DTPOFF;
7685  unsigned WrapperKind = X86ISD::Wrapper;
7686  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7687                                           GA->getValueType(0),
7688                                           GA->getOffset(), OperandFlags);
7689  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7690
7691  // Add x@dtpoff with the base.
7692  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7693}
7694
7695// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7696static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7697                                   const EVT PtrVT, TLSModel::Model model,
7698                                   bool is64Bit, bool isPIC) {
7699  DebugLoc dl = GA->getDebugLoc();
7700
7701  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7702  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7703                                                         is64Bit ? 257 : 256));
7704
7705  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7706                                      DAG.getIntPtrConstant(0),
7707                                      MachinePointerInfo(Ptr),
7708                                      false, false, false, 0);
7709
7710  unsigned char OperandFlags = 0;
7711  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7712  // initialexec.
7713  unsigned WrapperKind = X86ISD::Wrapper;
7714  if (model == TLSModel::LocalExec) {
7715    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7716  } else if (model == TLSModel::InitialExec) {
7717    if (is64Bit) {
7718      OperandFlags = X86II::MO_GOTTPOFF;
7719      WrapperKind = X86ISD::WrapperRIP;
7720    } else {
7721      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7722    }
7723  } else {
7724    llvm_unreachable("Unexpected model");
7725  }
7726
7727  // emit "addl x@ntpoff,%eax" (local exec)
7728  // or "addl x@indntpoff,%eax" (initial exec)
7729  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7730  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7731                                           GA->getValueType(0),
7732                                           GA->getOffset(), OperandFlags);
7733  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7734
7735  if (model == TLSModel::InitialExec) {
7736    if (isPIC && !is64Bit) {
7737      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7738                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7739                           Offset);
7740    }
7741
7742    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7743                         MachinePointerInfo::getGOT(), false, false, false,
7744                         0);
7745  }
7746
7747  // The address of the thread local variable is the add of the thread
7748  // pointer with the offset of the variable.
7749  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7750}
7751
7752SDValue
7753X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7754
7755  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7756  const GlobalValue *GV = GA->getGlobal();
7757
7758  if (Subtarget->isTargetELF()) {
7759    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7760
7761    switch (model) {
7762      case TLSModel::GeneralDynamic:
7763        if (Subtarget->is64Bit())
7764          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7765        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7766      case TLSModel::LocalDynamic:
7767        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7768                                           Subtarget->is64Bit());
7769      case TLSModel::InitialExec:
7770      case TLSModel::LocalExec:
7771        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7772                                   Subtarget->is64Bit(),
7773                        getTargetMachine().getRelocationModel() == Reloc::PIC_);
7774    }
7775    llvm_unreachable("Unknown TLS model.");
7776  }
7777
7778  if (Subtarget->isTargetDarwin()) {
7779    // Darwin only has one model of TLS.  Lower to that.
7780    unsigned char OpFlag = 0;
7781    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7782                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7783
7784    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7785    // global base reg.
7786    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7787                  !Subtarget->is64Bit();
7788    if (PIC32)
7789      OpFlag = X86II::MO_TLVP_PIC_BASE;
7790    else
7791      OpFlag = X86II::MO_TLVP;
7792    DebugLoc DL = Op.getDebugLoc();
7793    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7794                                                GA->getValueType(0),
7795                                                GA->getOffset(), OpFlag);
7796    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7797
7798    // With PIC32, the address is actually $g + Offset.
7799    if (PIC32)
7800      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7801                           DAG.getNode(X86ISD::GlobalBaseReg,
7802                                       DebugLoc(), getPointerTy()),
7803                           Offset);
7804
7805    // Lowering the machine isd will make sure everything is in the right
7806    // location.
7807    SDValue Chain = DAG.getEntryNode();
7808    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7809    SDValue Args[] = { Chain, Offset };
7810    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7811
7812    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7813    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7814    MFI->setAdjustsStack(true);
7815
7816    // And our return value (tls address) is in the standard call return value
7817    // location.
7818    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7819    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7820                              Chain.getValue(1));
7821  }
7822
7823  if (Subtarget->isTargetWindows()) {
7824    // Just use the implicit TLS architecture
7825    // Need to generate someting similar to:
7826    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7827    //                                  ; from TEB
7828    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7829    //   mov     rcx, qword [rdx+rcx*8]
7830    //   mov     eax, .tls$:tlsvar
7831    //   [rax+rcx] contains the address
7832    // Windows 64bit: gs:0x58
7833    // Windows 32bit: fs:__tls_array
7834
7835    // If GV is an alias then use the aliasee for determining
7836    // thread-localness.
7837    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7838      GV = GA->resolveAliasedGlobal(false);
7839    DebugLoc dl = GA->getDebugLoc();
7840    SDValue Chain = DAG.getEntryNode();
7841
7842    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7843    // %gs:0x58 (64-bit).
7844    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7845                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7846                                                             256)
7847                                        : Type::getInt32PtrTy(*DAG.getContext(),
7848                                                              257));
7849
7850    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7851                                        Subtarget->is64Bit()
7852                                        ? DAG.getIntPtrConstant(0x58)
7853                                        : DAG.getExternalSymbol("_tls_array",
7854                                                                getPointerTy()),
7855                                        MachinePointerInfo(Ptr),
7856                                        false, false, false, 0);
7857
7858    // Load the _tls_index variable
7859    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7860    if (Subtarget->is64Bit())
7861      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7862                           IDX, MachinePointerInfo(), MVT::i32,
7863                           false, false, 0);
7864    else
7865      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7866                        false, false, false, 0);
7867
7868    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7869                                    getPointerTy());
7870    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7871
7872    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7873    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7874                      false, false, false, 0);
7875
7876    // Get the offset of start of .tls section
7877    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7878                                             GA->getValueType(0),
7879                                             GA->getOffset(), X86II::MO_SECREL);
7880    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7881
7882    // The address of the thread local variable is the add of the thread
7883    // pointer with the offset of the variable.
7884    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7885  }
7886
7887  llvm_unreachable("TLS not implemented for this target.");
7888}
7889
7890/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7891/// and take a 2 x i32 value to shift plus a shift amount.
7892SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7893  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7894  EVT VT = Op.getValueType();
7895  unsigned VTBits = VT.getSizeInBits();
7896  DebugLoc dl = Op.getDebugLoc();
7897  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7898  SDValue ShOpLo = Op.getOperand(0);
7899  SDValue ShOpHi = Op.getOperand(1);
7900  SDValue ShAmt  = Op.getOperand(2);
7901  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7902                                     DAG.getConstant(VTBits - 1, MVT::i8))
7903                       : DAG.getConstant(0, VT);
7904
7905  SDValue Tmp2, Tmp3;
7906  if (Op.getOpcode() == ISD::SHL_PARTS) {
7907    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7908    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7909  } else {
7910    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7911    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7912  }
7913
7914  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7915                                DAG.getConstant(VTBits, MVT::i8));
7916  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7917                             AndNode, DAG.getConstant(0, MVT::i8));
7918
7919  SDValue Hi, Lo;
7920  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7921  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7922  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7923
7924  if (Op.getOpcode() == ISD::SHL_PARTS) {
7925    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7926    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7927  } else {
7928    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7929    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7930  }
7931
7932  SDValue Ops[2] = { Lo, Hi };
7933  return DAG.getMergeValues(Ops, 2, dl);
7934}
7935
7936SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7937                                           SelectionDAG &DAG) const {
7938  EVT SrcVT = Op.getOperand(0).getValueType();
7939
7940  if (SrcVT.isVector())
7941    return SDValue();
7942
7943  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7944         "Unknown SINT_TO_FP to lower!");
7945
7946  // These are really Legal; return the operand so the caller accepts it as
7947  // Legal.
7948  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7949    return Op;
7950  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7951      Subtarget->is64Bit()) {
7952    return Op;
7953  }
7954
7955  DebugLoc dl = Op.getDebugLoc();
7956  unsigned Size = SrcVT.getSizeInBits()/8;
7957  MachineFunction &MF = DAG.getMachineFunction();
7958  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7959  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7960  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7961                               StackSlot,
7962                               MachinePointerInfo::getFixedStack(SSFI),
7963                               false, false, 0);
7964  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7965}
7966
7967SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7968                                     SDValue StackSlot,
7969                                     SelectionDAG &DAG) const {
7970  // Build the FILD
7971  DebugLoc DL = Op.getDebugLoc();
7972  SDVTList Tys;
7973  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7974  if (useSSE)
7975    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7976  else
7977    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7978
7979  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7980
7981  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7982  MachineMemOperand *MMO;
7983  if (FI) {
7984    int SSFI = FI->getIndex();
7985    MMO =
7986      DAG.getMachineFunction()
7987      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7988                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7989  } else {
7990    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7991    StackSlot = StackSlot.getOperand(1);
7992  }
7993  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7994  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7995                                           X86ISD::FILD, DL,
7996                                           Tys, Ops, array_lengthof(Ops),
7997                                           SrcVT, MMO);
7998
7999  if (useSSE) {
8000    Chain = Result.getValue(1);
8001    SDValue InFlag = Result.getValue(2);
8002
8003    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8004    // shouldn't be necessary except that RFP cannot be live across
8005    // multiple blocks. When stackifier is fixed, they can be uncoupled.
8006    MachineFunction &MF = DAG.getMachineFunction();
8007    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8008    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8009    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8010    Tys = DAG.getVTList(MVT::Other);
8011    SDValue Ops[] = {
8012      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8013    };
8014    MachineMemOperand *MMO =
8015      DAG.getMachineFunction()
8016      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8017                            MachineMemOperand::MOStore, SSFISize, SSFISize);
8018
8019    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8020                                    Ops, array_lengthof(Ops),
8021                                    Op.getValueType(), MMO);
8022    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8023                         MachinePointerInfo::getFixedStack(SSFI),
8024                         false, false, false, 0);
8025  }
8026
8027  return Result;
8028}
8029
8030// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8031SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8032                                               SelectionDAG &DAG) const {
8033  // This algorithm is not obvious. Here it is what we're trying to output:
8034  /*
8035     movq       %rax,  %xmm0
8036     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8037     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8038     #ifdef __SSE3__
8039       haddpd   %xmm0, %xmm0
8040     #else
8041       pshufd   $0x4e, %xmm0, %xmm1
8042       addpd    %xmm1, %xmm0
8043     #endif
8044  */
8045
8046  DebugLoc dl = Op.getDebugLoc();
8047  LLVMContext *Context = DAG.getContext();
8048
8049  // Build some magic constants.
8050  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8051  Constant *C0 = ConstantDataVector::get(*Context, CV0);
8052  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8053
8054  SmallVector<Constant*,2> CV1;
8055  CV1.push_back(
8056    ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8057                                      APInt(64, 0x4330000000000000ULL))));
8058  CV1.push_back(
8059    ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8060                                      APInt(64, 0x4530000000000000ULL))));
8061  Constant *C1 = ConstantVector::get(CV1);
8062  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8063
8064  // Load the 64-bit value into an XMM register.
8065  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8066                            Op.getOperand(0));
8067  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8068                              MachinePointerInfo::getConstantPool(),
8069                              false, false, false, 16);
8070  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8071                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8072                              CLod0);
8073
8074  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8075                              MachinePointerInfo::getConstantPool(),
8076                              false, false, false, 16);
8077  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8078  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8079  SDValue Result;
8080
8081  if (Subtarget->hasSSE3()) {
8082    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8083    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8084  } else {
8085    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8086    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8087                                           S2F, 0x4E, DAG);
8088    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8089                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8090                         Sub);
8091  }
8092
8093  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8094                     DAG.getIntPtrConstant(0));
8095}
8096
8097// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8098SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8099                                               SelectionDAG &DAG) const {
8100  DebugLoc dl = Op.getDebugLoc();
8101  // FP constant to bias correct the final result.
8102  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8103                                   MVT::f64);
8104
8105  // Load the 32-bit value into an XMM register.
8106  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8107                             Op.getOperand(0));
8108
8109  // Zero out the upper parts of the register.
8110  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8111
8112  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8113                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8114                     DAG.getIntPtrConstant(0));
8115
8116  // Or the load with the bias.
8117  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8118                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8119                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8120                                                   MVT::v2f64, Load)),
8121                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8122                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8123                                                   MVT::v2f64, Bias)));
8124  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8125                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8126                   DAG.getIntPtrConstant(0));
8127
8128  // Subtract the bias.
8129  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8130
8131  // Handle final rounding.
8132  EVT DestVT = Op.getValueType();
8133
8134  if (DestVT.bitsLT(MVT::f64))
8135    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8136                       DAG.getIntPtrConstant(0));
8137  if (DestVT.bitsGT(MVT::f64))
8138    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8139
8140  // Handle final rounding.
8141  return Sub;
8142}
8143
8144SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8145                                               SelectionDAG &DAG) const {
8146  SDValue N0 = Op.getOperand(0);
8147  EVT SVT = N0.getValueType();
8148  DebugLoc dl = Op.getDebugLoc();
8149
8150  assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8151          SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8152         "Custom UINT_TO_FP is not supported!");
8153
8154  EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8155                             SVT.getVectorNumElements());
8156  return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8157                     DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8158}
8159
8160SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8161                                           SelectionDAG &DAG) const {
8162  SDValue N0 = Op.getOperand(0);
8163  DebugLoc dl = Op.getDebugLoc();
8164
8165  if (Op.getValueType().isVector())
8166    return lowerUINT_TO_FP_vec(Op, DAG);
8167
8168  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8169  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8170  // the optimization here.
8171  if (DAG.SignBitIsZero(N0))
8172    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8173
8174  EVT SrcVT = N0.getValueType();
8175  EVT DstVT = Op.getValueType();
8176  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8177    return LowerUINT_TO_FP_i64(Op, DAG);
8178  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8179    return LowerUINT_TO_FP_i32(Op, DAG);
8180  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8181    return SDValue();
8182
8183  // Make a 64-bit buffer, and use it to build an FILD.
8184  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8185  if (SrcVT == MVT::i32) {
8186    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8187    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8188                                     getPointerTy(), StackSlot, WordOff);
8189    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8190                                  StackSlot, MachinePointerInfo(),
8191                                  false, false, 0);
8192    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8193                                  OffsetSlot, MachinePointerInfo(),
8194                                  false, false, 0);
8195    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8196    return Fild;
8197  }
8198
8199  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8200  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8201                               StackSlot, MachinePointerInfo(),
8202                               false, false, 0);
8203  // For i64 source, we need to add the appropriate power of 2 if the input
8204  // was negative.  This is the same as the optimization in
8205  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8206  // we must be careful to do the computation in x87 extended precision, not
8207  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8208  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8209  MachineMemOperand *MMO =
8210    DAG.getMachineFunction()
8211    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8212                          MachineMemOperand::MOLoad, 8, 8);
8213
8214  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8215  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8216  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8217                                         MVT::i64, MMO);
8218
8219  APInt FF(32, 0x5F800000ULL);
8220
8221  // Check whether the sign bit is set.
8222  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8223                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8224                                 ISD::SETLT);
8225
8226  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8227  SDValue FudgePtr = DAG.getConstantPool(
8228                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8229                                         getPointerTy());
8230
8231  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8232  SDValue Zero = DAG.getIntPtrConstant(0);
8233  SDValue Four = DAG.getIntPtrConstant(4);
8234  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8235                               Zero, Four);
8236  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8237
8238  // Load the value out, extending it from f32 to f80.
8239  // FIXME: Avoid the extend by constructing the right constant pool?
8240  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8241                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8242                                 MVT::f32, false, false, 4);
8243  // Extend everything to 80 bits to force it to be done on x87.
8244  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8245  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8246}
8247
8248std::pair<SDValue,SDValue>
8249X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8250                                    bool IsSigned, bool IsReplace) const {
8251  DebugLoc DL = Op.getDebugLoc();
8252
8253  EVT DstTy = Op.getValueType();
8254
8255  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8256    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8257    DstTy = MVT::i64;
8258  }
8259
8260  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8261         DstTy.getSimpleVT() >= MVT::i16 &&
8262         "Unknown FP_TO_INT to lower!");
8263
8264  // These are really Legal.
8265  if (DstTy == MVT::i32 &&
8266      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8267    return std::make_pair(SDValue(), SDValue());
8268  if (Subtarget->is64Bit() &&
8269      DstTy == MVT::i64 &&
8270      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8271    return std::make_pair(SDValue(), SDValue());
8272
8273  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8274  // stack slot, or into the FTOL runtime function.
8275  MachineFunction &MF = DAG.getMachineFunction();
8276  unsigned MemSize = DstTy.getSizeInBits()/8;
8277  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8278  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8279
8280  unsigned Opc;
8281  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8282    Opc = X86ISD::WIN_FTOL;
8283  else
8284    switch (DstTy.getSimpleVT().SimpleTy) {
8285    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8286    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8287    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8288    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8289    }
8290
8291  SDValue Chain = DAG.getEntryNode();
8292  SDValue Value = Op.getOperand(0);
8293  EVT TheVT = Op.getOperand(0).getValueType();
8294  // FIXME This causes a redundant load/store if the SSE-class value is already
8295  // in memory, such as if it is on the callstack.
8296  if (isScalarFPTypeInSSEReg(TheVT)) {
8297    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8298    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8299                         MachinePointerInfo::getFixedStack(SSFI),
8300                         false, false, 0);
8301    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8302    SDValue Ops[] = {
8303      Chain, StackSlot, DAG.getValueType(TheVT)
8304    };
8305
8306    MachineMemOperand *MMO =
8307      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8308                              MachineMemOperand::MOLoad, MemSize, MemSize);
8309    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8310                                    DstTy, MMO);
8311    Chain = Value.getValue(1);
8312    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8313    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8314  }
8315
8316  MachineMemOperand *MMO =
8317    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8318                            MachineMemOperand::MOStore, MemSize, MemSize);
8319
8320  if (Opc != X86ISD::WIN_FTOL) {
8321    // Build the FP_TO_INT*_IN_MEM
8322    SDValue Ops[] = { Chain, Value, StackSlot };
8323    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8324                                           Ops, 3, DstTy, MMO);
8325    return std::make_pair(FIST, StackSlot);
8326  } else {
8327    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8328      DAG.getVTList(MVT::Other, MVT::Glue),
8329      Chain, Value);
8330    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8331      MVT::i32, ftol.getValue(1));
8332    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8333      MVT::i32, eax.getValue(2));
8334    SDValue Ops[] = { eax, edx };
8335    SDValue pair = IsReplace
8336      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8337      : DAG.getMergeValues(Ops, 2, DL);
8338    return std::make_pair(pair, SDValue());
8339  }
8340}
8341
8342static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8343                              const X86Subtarget *Subtarget) {
8344  MVT VT = Op->getValueType(0).getSimpleVT();
8345  SDValue In = Op->getOperand(0);
8346  MVT InVT = In.getValueType().getSimpleVT();
8347  DebugLoc dl = Op->getDebugLoc();
8348
8349  // Optimize vectors in AVX mode:
8350  //
8351  //   v8i16 -> v8i32
8352  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8353  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8354  //   Concat upper and lower parts.
8355  //
8356  //   v4i32 -> v4i64
8357  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8358  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8359  //   Concat upper and lower parts.
8360  //
8361
8362  if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8363      ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8364    return SDValue();
8365
8366  if (Subtarget->hasInt256())
8367    return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8368
8369  SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8370  SDValue Undef = DAG.getUNDEF(InVT);
8371  bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8372  SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8373  SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8374
8375  MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8376                             VT.getVectorNumElements()/2);
8377
8378  OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8379  OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8380
8381  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8382}
8383
8384SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8385                                           SelectionDAG &DAG) const {
8386  if (Subtarget->hasFp256()) {
8387    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8388    if (Res.getNode())
8389      return Res;
8390  }
8391
8392  return SDValue();
8393}
8394SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8395                                            SelectionDAG &DAG) const {
8396  DebugLoc DL = Op.getDebugLoc();
8397  MVT VT = Op.getValueType().getSimpleVT();
8398  SDValue In = Op.getOperand(0);
8399  MVT SVT = In.getValueType().getSimpleVT();
8400
8401  if (Subtarget->hasFp256()) {
8402    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8403    if (Res.getNode())
8404      return Res;
8405  }
8406
8407  if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8408      VT.getVectorNumElements() != SVT.getVectorNumElements())
8409    return SDValue();
8410
8411  assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8412
8413  // AVX2 has better support of integer extending.
8414  if (Subtarget->hasInt256())
8415    return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8416
8417  SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8418  static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8419  SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8420                           DAG.getVectorShuffle(MVT::v8i16, DL, In,
8421                                                DAG.getUNDEF(MVT::v8i16),
8422                                                &Mask[0]));
8423
8424  return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8425}
8426
8427SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8428  DebugLoc DL = Op.getDebugLoc();
8429  MVT VT = Op.getValueType().getSimpleVT();
8430  SDValue In = Op.getOperand(0);
8431  MVT SVT = In.getValueType().getSimpleVT();
8432
8433  if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8434    // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8435    if (Subtarget->hasInt256()) {
8436      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8437      In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8438      In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8439                                ShufMask);
8440      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8441                         DAG.getIntPtrConstant(0));
8442    }
8443
8444    // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8445    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8446                               DAG.getIntPtrConstant(0));
8447    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8448                               DAG.getIntPtrConstant(2));
8449
8450    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8451    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8452
8453    // The PSHUFD mask:
8454    static const int ShufMask1[] = {0, 2, 0, 0};
8455    SDValue Undef = DAG.getUNDEF(VT);
8456    OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8457    OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8458
8459    // The MOVLHPS mask:
8460    static const int ShufMask2[] = {0, 1, 4, 5};
8461    return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8462  }
8463
8464  if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8465    // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8466    if (Subtarget->hasInt256()) {
8467      In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8468
8469      SmallVector<SDValue,32> pshufbMask;
8470      for (unsigned i = 0; i < 2; ++i) {
8471        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8472        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8473        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8474        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8475        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8476        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8477        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8478        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8479        for (unsigned j = 0; j < 8; ++j)
8480          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8481      }
8482      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8483                               &pshufbMask[0], 32);
8484      In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8485      In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8486
8487      static const int ShufMask[] = {0,  2,  -1,  -1};
8488      In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8489                                &ShufMask[0]);
8490      In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8491                       DAG.getIntPtrConstant(0));
8492      return DAG.getNode(ISD::BITCAST, DL, VT, In);
8493    }
8494
8495    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8496                               DAG.getIntPtrConstant(0));
8497
8498    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8499                               DAG.getIntPtrConstant(4));
8500
8501    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8502    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8503
8504    // The PSHUFB mask:
8505    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8506                                   -1, -1, -1, -1, -1, -1, -1, -1};
8507
8508    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8509    OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8510    OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8511
8512    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8513    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8514
8515    // The MOVLHPS Mask:
8516    static const int ShufMask2[] = {0, 1, 4, 5};
8517    SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8518    return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8519  }
8520
8521  // Handle truncation of V256 to V128 using shuffles.
8522  if (!VT.is128BitVector() || !SVT.is256BitVector())
8523    return SDValue();
8524
8525  assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8526         "Invalid op");
8527  assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8528
8529  unsigned NumElems = VT.getVectorNumElements();
8530  EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8531                             NumElems * 2);
8532
8533  SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8534  // Prepare truncation shuffle mask
8535  for (unsigned i = 0; i != NumElems; ++i)
8536    MaskVec[i] = i * 2;
8537  SDValue V = DAG.getVectorShuffle(NVT, DL,
8538                                   DAG.getNode(ISD::BITCAST, DL, NVT, In),
8539                                   DAG.getUNDEF(NVT), &MaskVec[0]);
8540  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8541                     DAG.getIntPtrConstant(0));
8542}
8543
8544SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8545                                           SelectionDAG &DAG) const {
8546  MVT VT = Op.getValueType().getSimpleVT();
8547  if (VT.isVector()) {
8548    if (VT == MVT::v8i16)
8549      return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8550                         DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8551                                     MVT::v8i32, Op.getOperand(0)));
8552    return SDValue();
8553  }
8554
8555  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8556    /*IsSigned=*/ true, /*IsReplace=*/ false);
8557  SDValue FIST = Vals.first, StackSlot = Vals.second;
8558  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8559  if (FIST.getNode() == 0) return Op;
8560
8561  if (StackSlot.getNode())
8562    // Load the result.
8563    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8564                       FIST, StackSlot, MachinePointerInfo(),
8565                       false, false, false, 0);
8566
8567  // The node is the result.
8568  return FIST;
8569}
8570
8571SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8572                                           SelectionDAG &DAG) const {
8573  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8574    /*IsSigned=*/ false, /*IsReplace=*/ false);
8575  SDValue FIST = Vals.first, StackSlot = Vals.second;
8576  assert(FIST.getNode() && "Unexpected failure");
8577
8578  if (StackSlot.getNode())
8579    // Load the result.
8580    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8581                       FIST, StackSlot, MachinePointerInfo(),
8582                       false, false, false, 0);
8583
8584  // The node is the result.
8585  return FIST;
8586}
8587
8588static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8589  DebugLoc DL = Op.getDebugLoc();
8590  MVT VT = Op.getValueType().getSimpleVT();
8591  SDValue In = Op.getOperand(0);
8592  MVT SVT = In.getValueType().getSimpleVT();
8593
8594  assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8595
8596  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8597                     DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8598                                 In, DAG.getUNDEF(SVT)));
8599}
8600
8601SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8602  LLVMContext *Context = DAG.getContext();
8603  DebugLoc dl = Op.getDebugLoc();
8604  MVT VT = Op.getValueType().getSimpleVT();
8605  MVT EltVT = VT;
8606  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8607  if (VT.isVector()) {
8608    EltVT = VT.getVectorElementType();
8609    NumElts = VT.getVectorNumElements();
8610  }
8611  Constant *C;
8612  if (EltVT == MVT::f64)
8613    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8614                                          APInt(64, ~(1ULL << 63))));
8615  else
8616    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8617                                          APInt(32, ~(1U << 31))));
8618  C = ConstantVector::getSplat(NumElts, C);
8619  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8620  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8621  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8622                             MachinePointerInfo::getConstantPool(),
8623                             false, false, false, Alignment);
8624  if (VT.isVector()) {
8625    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8626    return DAG.getNode(ISD::BITCAST, dl, VT,
8627                       DAG.getNode(ISD::AND, dl, ANDVT,
8628                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8629                                               Op.getOperand(0)),
8630                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8631  }
8632  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8633}
8634
8635SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8636  LLVMContext *Context = DAG.getContext();
8637  DebugLoc dl = Op.getDebugLoc();
8638  MVT VT = Op.getValueType().getSimpleVT();
8639  MVT EltVT = VT;
8640  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8641  if (VT.isVector()) {
8642    EltVT = VT.getVectorElementType();
8643    NumElts = VT.getVectorNumElements();
8644  }
8645  Constant *C;
8646  if (EltVT == MVT::f64)
8647    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8648                                          APInt(64, 1ULL << 63)));
8649  else
8650    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8651                                          APInt(32, 1U << 31)));
8652  C = ConstantVector::getSplat(NumElts, C);
8653  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8654  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8655  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8656                             MachinePointerInfo::getConstantPool(),
8657                             false, false, false, Alignment);
8658  if (VT.isVector()) {
8659    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8660    return DAG.getNode(ISD::BITCAST, dl, VT,
8661                       DAG.getNode(ISD::XOR, dl, XORVT,
8662                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8663                                               Op.getOperand(0)),
8664                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8665  }
8666
8667  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8668}
8669
8670SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8671  LLVMContext *Context = DAG.getContext();
8672  SDValue Op0 = Op.getOperand(0);
8673  SDValue Op1 = Op.getOperand(1);
8674  DebugLoc dl = Op.getDebugLoc();
8675  MVT VT = Op.getValueType().getSimpleVT();
8676  MVT SrcVT = Op1.getValueType().getSimpleVT();
8677
8678  // If second operand is smaller, extend it first.
8679  if (SrcVT.bitsLT(VT)) {
8680    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8681    SrcVT = VT;
8682  }
8683  // And if it is bigger, shrink it first.
8684  if (SrcVT.bitsGT(VT)) {
8685    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8686    SrcVT = VT;
8687  }
8688
8689  // At this point the operands and the result should have the same
8690  // type, and that won't be f80 since that is not custom lowered.
8691
8692  // First get the sign bit of second operand.
8693  SmallVector<Constant*,4> CV;
8694  if (SrcVT == MVT::f64) {
8695    const fltSemantics &Sem = APFloat::IEEEdouble;
8696    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8697    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8698  } else {
8699    const fltSemantics &Sem = APFloat::IEEEsingle;
8700    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8701    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8702    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8703    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8704  }
8705  Constant *C = ConstantVector::get(CV);
8706  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8707  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8708                              MachinePointerInfo::getConstantPool(),
8709                              false, false, false, 16);
8710  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8711
8712  // Shift sign bit right or left if the two operands have different types.
8713  if (SrcVT.bitsGT(VT)) {
8714    // Op0 is MVT::f32, Op1 is MVT::f64.
8715    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8716    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8717                          DAG.getConstant(32, MVT::i32));
8718    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8719    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8720                          DAG.getIntPtrConstant(0));
8721  }
8722
8723  // Clear first operand sign bit.
8724  CV.clear();
8725  if (VT == MVT::f64) {
8726    const fltSemantics &Sem = APFloat::IEEEdouble;
8727    CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8728                                                   APInt(64, ~(1ULL << 63)))));
8729    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8730  } else {
8731    const fltSemantics &Sem = APFloat::IEEEsingle;
8732    CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8733                                                   APInt(32, ~(1U << 31)))));
8734    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8735    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8736    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8737  }
8738  C = ConstantVector::get(CV);
8739  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8740  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8741                              MachinePointerInfo::getConstantPool(),
8742                              false, false, false, 16);
8743  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8744
8745  // Or the value with the sign bit.
8746  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8747}
8748
8749static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8750  SDValue N0 = Op.getOperand(0);
8751  DebugLoc dl = Op.getDebugLoc();
8752  MVT VT = Op.getValueType().getSimpleVT();
8753
8754  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8755  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8756                                  DAG.getConstant(1, VT));
8757  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8758}
8759
8760// LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8761//
8762SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8763                                                  SelectionDAG &DAG) const {
8764  assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8765
8766  if (!Subtarget->hasSSE41())
8767    return SDValue();
8768
8769  if (!Op->hasOneUse())
8770    return SDValue();
8771
8772  SDNode *N = Op.getNode();
8773  DebugLoc DL = N->getDebugLoc();
8774
8775  SmallVector<SDValue, 8> Opnds;
8776  DenseMap<SDValue, unsigned> VecInMap;
8777  EVT VT = MVT::Other;
8778
8779  // Recognize a special case where a vector is casted into wide integer to
8780  // test all 0s.
8781  Opnds.push_back(N->getOperand(0));
8782  Opnds.push_back(N->getOperand(1));
8783
8784  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8785    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8786    // BFS traverse all OR'd operands.
8787    if (I->getOpcode() == ISD::OR) {
8788      Opnds.push_back(I->getOperand(0));
8789      Opnds.push_back(I->getOperand(1));
8790      // Re-evaluate the number of nodes to be traversed.
8791      e += 2; // 2 more nodes (LHS and RHS) are pushed.
8792      continue;
8793    }
8794
8795    // Quit if a non-EXTRACT_VECTOR_ELT
8796    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8797      return SDValue();
8798
8799    // Quit if without a constant index.
8800    SDValue Idx = I->getOperand(1);
8801    if (!isa<ConstantSDNode>(Idx))
8802      return SDValue();
8803
8804    SDValue ExtractedFromVec = I->getOperand(0);
8805    DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8806    if (M == VecInMap.end()) {
8807      VT = ExtractedFromVec.getValueType();
8808      // Quit if not 128/256-bit vector.
8809      if (!VT.is128BitVector() && !VT.is256BitVector())
8810        return SDValue();
8811      // Quit if not the same type.
8812      if (VecInMap.begin() != VecInMap.end() &&
8813          VT != VecInMap.begin()->first.getValueType())
8814        return SDValue();
8815      M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8816    }
8817    M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8818  }
8819
8820  assert((VT.is128BitVector() || VT.is256BitVector()) &&
8821         "Not extracted from 128-/256-bit vector.");
8822
8823  unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8824  SmallVector<SDValue, 8> VecIns;
8825
8826  for (DenseMap<SDValue, unsigned>::const_iterator
8827        I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8828    // Quit if not all elements are used.
8829    if (I->second != FullMask)
8830      return SDValue();
8831    VecIns.push_back(I->first);
8832  }
8833
8834  EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8835
8836  // Cast all vectors into TestVT for PTEST.
8837  for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8838    VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8839
8840  // If more than one full vectors are evaluated, OR them first before PTEST.
8841  for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8842    // Each iteration will OR 2 nodes and append the result until there is only
8843    // 1 node left, i.e. the final OR'd value of all vectors.
8844    SDValue LHS = VecIns[Slot];
8845    SDValue RHS = VecIns[Slot + 1];
8846    VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8847  }
8848
8849  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8850                     VecIns.back(), VecIns.back());
8851}
8852
8853/// Emit nodes that will be selected as "test Op0,Op0", or something
8854/// equivalent.
8855SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8856                                    SelectionDAG &DAG) const {
8857  DebugLoc dl = Op.getDebugLoc();
8858
8859  // CF and OF aren't always set the way we want. Determine which
8860  // of these we need.
8861  bool NeedCF = false;
8862  bool NeedOF = false;
8863  switch (X86CC) {
8864  default: break;
8865  case X86::COND_A: case X86::COND_AE:
8866  case X86::COND_B: case X86::COND_BE:
8867    NeedCF = true;
8868    break;
8869  case X86::COND_G: case X86::COND_GE:
8870  case X86::COND_L: case X86::COND_LE:
8871  case X86::COND_O: case X86::COND_NO:
8872    NeedOF = true;
8873    break;
8874  }
8875
8876  // See if we can use the EFLAGS value from the operand instead of
8877  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8878  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8879  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8880    // Emit a CMP with 0, which is the TEST pattern.
8881    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8882                       DAG.getConstant(0, Op.getValueType()));
8883
8884  unsigned Opcode = 0;
8885  unsigned NumOperands = 0;
8886
8887  // Truncate operations may prevent the merge of the SETCC instruction
8888  // and the arithmetic intruction before it. Attempt to truncate the operands
8889  // of the arithmetic instruction and use a reduced bit-width instruction.
8890  bool NeedTruncation = false;
8891  SDValue ArithOp = Op;
8892  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8893    SDValue Arith = Op->getOperand(0);
8894    // Both the trunc and the arithmetic op need to have one user each.
8895    if (Arith->hasOneUse())
8896      switch (Arith.getOpcode()) {
8897        default: break;
8898        case ISD::ADD:
8899        case ISD::SUB:
8900        case ISD::AND:
8901        case ISD::OR:
8902        case ISD::XOR: {
8903          NeedTruncation = true;
8904          ArithOp = Arith;
8905        }
8906      }
8907  }
8908
8909  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8910  // which may be the result of a CAST.  We use the variable 'Op', which is the
8911  // non-casted variable when we check for possible users.
8912  switch (ArithOp.getOpcode()) {
8913  case ISD::ADD:
8914    // Due to an isel shortcoming, be conservative if this add is likely to be
8915    // selected as part of a load-modify-store instruction. When the root node
8916    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8917    // uses of other nodes in the match, such as the ADD in this case. This
8918    // leads to the ADD being left around and reselected, with the result being
8919    // two adds in the output.  Alas, even if none our users are stores, that
8920    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8921    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8922    // climbing the DAG back to the root, and it doesn't seem to be worth the
8923    // effort.
8924    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8925         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8926      if (UI->getOpcode() != ISD::CopyToReg &&
8927          UI->getOpcode() != ISD::SETCC &&
8928          UI->getOpcode() != ISD::STORE)
8929        goto default_case;
8930
8931    if (ConstantSDNode *C =
8932        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8933      // An add of one will be selected as an INC.
8934      if (C->getAPIntValue() == 1) {
8935        Opcode = X86ISD::INC;
8936        NumOperands = 1;
8937        break;
8938      }
8939
8940      // An add of negative one (subtract of one) will be selected as a DEC.
8941      if (C->getAPIntValue().isAllOnesValue()) {
8942        Opcode = X86ISD::DEC;
8943        NumOperands = 1;
8944        break;
8945      }
8946    }
8947
8948    // Otherwise use a regular EFLAGS-setting add.
8949    Opcode = X86ISD::ADD;
8950    NumOperands = 2;
8951    break;
8952  case ISD::AND: {
8953    // If the primary and result isn't used, don't bother using X86ISD::AND,
8954    // because a TEST instruction will be better.
8955    bool NonFlagUse = false;
8956    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8957           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8958      SDNode *User = *UI;
8959      unsigned UOpNo = UI.getOperandNo();
8960      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8961        // Look pass truncate.
8962        UOpNo = User->use_begin().getOperandNo();
8963        User = *User->use_begin();
8964      }
8965
8966      if (User->getOpcode() != ISD::BRCOND &&
8967          User->getOpcode() != ISD::SETCC &&
8968          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8969        NonFlagUse = true;
8970        break;
8971      }
8972    }
8973
8974    if (!NonFlagUse)
8975      break;
8976  }
8977    // FALL THROUGH
8978  case ISD::SUB:
8979  case ISD::OR:
8980  case ISD::XOR:
8981    // Due to the ISEL shortcoming noted above, be conservative if this op is
8982    // likely to be selected as part of a load-modify-store instruction.
8983    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8984           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8985      if (UI->getOpcode() == ISD::STORE)
8986        goto default_case;
8987
8988    // Otherwise use a regular EFLAGS-setting instruction.
8989    switch (ArithOp.getOpcode()) {
8990    default: llvm_unreachable("unexpected operator!");
8991    case ISD::SUB: Opcode = X86ISD::SUB; break;
8992    case ISD::XOR: Opcode = X86ISD::XOR; break;
8993    case ISD::AND: Opcode = X86ISD::AND; break;
8994    case ISD::OR: {
8995      if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8996        SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8997        if (EFLAGS.getNode())
8998          return EFLAGS;
8999      }
9000      Opcode = X86ISD::OR;
9001      break;
9002    }
9003    }
9004
9005    NumOperands = 2;
9006    break;
9007  case X86ISD::ADD:
9008  case X86ISD::SUB:
9009  case X86ISD::INC:
9010  case X86ISD::DEC:
9011  case X86ISD::OR:
9012  case X86ISD::XOR:
9013  case X86ISD::AND:
9014    return SDValue(Op.getNode(), 1);
9015  default:
9016  default_case:
9017    break;
9018  }
9019
9020  // If we found that truncation is beneficial, perform the truncation and
9021  // update 'Op'.
9022  if (NeedTruncation) {
9023    EVT VT = Op.getValueType();
9024    SDValue WideVal = Op->getOperand(0);
9025    EVT WideVT = WideVal.getValueType();
9026    unsigned ConvertedOp = 0;
9027    // Use a target machine opcode to prevent further DAGCombine
9028    // optimizations that may separate the arithmetic operations
9029    // from the setcc node.
9030    switch (WideVal.getOpcode()) {
9031      default: break;
9032      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9033      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9034      case ISD::AND: ConvertedOp = X86ISD::AND; break;
9035      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9036      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9037    }
9038
9039    if (ConvertedOp) {
9040      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9041      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9042        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9043        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9044        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9045      }
9046    }
9047  }
9048
9049  if (Opcode == 0)
9050    // Emit a CMP with 0, which is the TEST pattern.
9051    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9052                       DAG.getConstant(0, Op.getValueType()));
9053
9054  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9055  SmallVector<SDValue, 4> Ops;
9056  for (unsigned i = 0; i != NumOperands; ++i)
9057    Ops.push_back(Op.getOperand(i));
9058
9059  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9060  DAG.ReplaceAllUsesWith(Op, New);
9061  return SDValue(New.getNode(), 1);
9062}
9063
9064/// Emit nodes that will be selected as "cmp Op0,Op1", or something
9065/// equivalent.
9066SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9067                                   SelectionDAG &DAG) const {
9068  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9069    if (C->getAPIntValue() == 0)
9070      return EmitTest(Op0, X86CC, DAG);
9071
9072  DebugLoc dl = Op0.getDebugLoc();
9073  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9074       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9075    // Use SUB instead of CMP to enable CSE between SUB and CMP.
9076    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9077    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9078                              Op0, Op1);
9079    return SDValue(Sub.getNode(), 1);
9080  }
9081  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9082}
9083
9084/// Convert a comparison if required by the subtarget.
9085SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9086                                                 SelectionDAG &DAG) const {
9087  // If the subtarget does not support the FUCOMI instruction, floating-point
9088  // comparisons have to be converted.
9089  if (Subtarget->hasCMov() ||
9090      Cmp.getOpcode() != X86ISD::CMP ||
9091      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9092      !Cmp.getOperand(1).getValueType().isFloatingPoint())
9093    return Cmp;
9094
9095  // The instruction selector will select an FUCOM instruction instead of
9096  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9097  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9098  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9099  DebugLoc dl = Cmp.getDebugLoc();
9100  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9101  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9102  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9103                            DAG.getConstant(8, MVT::i8));
9104  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9105  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9106}
9107
9108static bool isAllOnes(SDValue V) {
9109  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9110  return C && C->isAllOnesValue();
9111}
9112
9113/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9114/// if it's possible.
9115SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9116                                     DebugLoc dl, SelectionDAG &DAG) const {
9117  SDValue Op0 = And.getOperand(0);
9118  SDValue Op1 = And.getOperand(1);
9119  if (Op0.getOpcode() == ISD::TRUNCATE)
9120    Op0 = Op0.getOperand(0);
9121  if (Op1.getOpcode() == ISD::TRUNCATE)
9122    Op1 = Op1.getOperand(0);
9123
9124  SDValue LHS, RHS;
9125  if (Op1.getOpcode() == ISD::SHL)
9126    std::swap(Op0, Op1);
9127  if (Op0.getOpcode() == ISD::SHL) {
9128    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9129      if (And00C->getZExtValue() == 1) {
9130        // If we looked past a truncate, check that it's only truncating away
9131        // known zeros.
9132        unsigned BitWidth = Op0.getValueSizeInBits();
9133        unsigned AndBitWidth = And.getValueSizeInBits();
9134        if (BitWidth > AndBitWidth) {
9135          APInt Zeros, Ones;
9136          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9137          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9138            return SDValue();
9139        }
9140        LHS = Op1;
9141        RHS = Op0.getOperand(1);
9142      }
9143  } else if (Op1.getOpcode() == ISD::Constant) {
9144    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9145    uint64_t AndRHSVal = AndRHS->getZExtValue();
9146    SDValue AndLHS = Op0;
9147
9148    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9149      LHS = AndLHS.getOperand(0);
9150      RHS = AndLHS.getOperand(1);
9151    }
9152
9153    // Use BT if the immediate can't be encoded in a TEST instruction.
9154    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9155      LHS = AndLHS;
9156      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9157    }
9158  }
9159
9160  if (LHS.getNode()) {
9161    // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9162    // the condition code later.
9163    bool Invert = false;
9164    if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9165      Invert = true;
9166      LHS = LHS.getOperand(0);
9167    }
9168
9169    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9170    // instruction.  Since the shift amount is in-range-or-undefined, we know
9171    // that doing a bittest on the i32 value is ok.  We extend to i32 because
9172    // the encoding for the i16 version is larger than the i32 version.
9173    // Also promote i16 to i32 for performance / code size reason.
9174    if (LHS.getValueType() == MVT::i8 ||
9175        LHS.getValueType() == MVT::i16)
9176      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9177
9178    // If the operand types disagree, extend the shift amount to match.  Since
9179    // BT ignores high bits (like shifts) we can use anyextend.
9180    if (LHS.getValueType() != RHS.getValueType())
9181      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9182
9183    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9184    X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9185    // Flip the condition if the LHS was a not instruction
9186    if (Invert)
9187      Cond = X86::GetOppositeBranchCondition(Cond);
9188    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9189                       DAG.getConstant(Cond, MVT::i8), BT);
9190  }
9191
9192  return SDValue();
9193}
9194
9195// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9196// ones, and then concatenate the result back.
9197static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9198  MVT VT = Op.getValueType().getSimpleVT();
9199
9200  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9201         "Unsupported value type for operation");
9202
9203  unsigned NumElems = VT.getVectorNumElements();
9204  DebugLoc dl = Op.getDebugLoc();
9205  SDValue CC = Op.getOperand(2);
9206
9207  // Extract the LHS vectors
9208  SDValue LHS = Op.getOperand(0);
9209  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9210  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9211
9212  // Extract the RHS vectors
9213  SDValue RHS = Op.getOperand(1);
9214  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9215  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9216
9217  // Issue the operation on the smaller types and concatenate the result back
9218  MVT EltVT = VT.getVectorElementType();
9219  MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9220  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9221                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9222                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9223}
9224
9225static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9226                           SelectionDAG &DAG) {
9227  SDValue Cond;
9228  SDValue Op0 = Op.getOperand(0);
9229  SDValue Op1 = Op.getOperand(1);
9230  SDValue CC = Op.getOperand(2);
9231  MVT VT = Op.getValueType().getSimpleVT();
9232  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9233  bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9234  DebugLoc dl = Op.getDebugLoc();
9235
9236  if (isFP) {
9237#ifndef NDEBUG
9238    MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9239    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9240#endif
9241
9242    unsigned SSECC;
9243    bool Swap = false;
9244
9245    // SSE Condition code mapping:
9246    //  0 - EQ
9247    //  1 - LT
9248    //  2 - LE
9249    //  3 - UNORD
9250    //  4 - NEQ
9251    //  5 - NLT
9252    //  6 - NLE
9253    //  7 - ORD
9254    switch (SetCCOpcode) {
9255    default: llvm_unreachable("Unexpected SETCC condition");
9256    case ISD::SETOEQ:
9257    case ISD::SETEQ:  SSECC = 0; break;
9258    case ISD::SETOGT:
9259    case ISD::SETGT: Swap = true; // Fallthrough
9260    case ISD::SETLT:
9261    case ISD::SETOLT: SSECC = 1; break;
9262    case ISD::SETOGE:
9263    case ISD::SETGE: Swap = true; // Fallthrough
9264    case ISD::SETLE:
9265    case ISD::SETOLE: SSECC = 2; break;
9266    case ISD::SETUO:  SSECC = 3; break;
9267    case ISD::SETUNE:
9268    case ISD::SETNE:  SSECC = 4; break;
9269    case ISD::SETULE: Swap = true; // Fallthrough
9270    case ISD::SETUGE: SSECC = 5; break;
9271    case ISD::SETULT: Swap = true; // Fallthrough
9272    case ISD::SETUGT: SSECC = 6; break;
9273    case ISD::SETO:   SSECC = 7; break;
9274    case ISD::SETUEQ:
9275    case ISD::SETONE: SSECC = 8; break;
9276    }
9277    if (Swap)
9278      std::swap(Op0, Op1);
9279
9280    // In the two special cases we can't handle, emit two comparisons.
9281    if (SSECC == 8) {
9282      unsigned CC0, CC1;
9283      unsigned CombineOpc;
9284      if (SetCCOpcode == ISD::SETUEQ) {
9285        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9286      } else {
9287        assert(SetCCOpcode == ISD::SETONE);
9288        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9289      }
9290
9291      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9292                                 DAG.getConstant(CC0, MVT::i8));
9293      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9294                                 DAG.getConstant(CC1, MVT::i8));
9295      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9296    }
9297    // Handle all other FP comparisons here.
9298    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9299                       DAG.getConstant(SSECC, MVT::i8));
9300  }
9301
9302  // Break 256-bit integer vector compare into smaller ones.
9303  if (VT.is256BitVector() && !Subtarget->hasInt256())
9304    return Lower256IntVSETCC(Op, DAG);
9305
9306  // We are handling one of the integer comparisons here.  Since SSE only has
9307  // GT and EQ comparisons for integer, swapping operands and multiple
9308  // operations may be required for some comparisons.
9309  unsigned Opc;
9310  bool Swap = false, Invert = false, FlipSigns = false;
9311
9312  switch (SetCCOpcode) {
9313  default: llvm_unreachable("Unexpected SETCC condition");
9314  case ISD::SETNE:  Invert = true;
9315  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9316  case ISD::SETLT:  Swap = true;
9317  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9318  case ISD::SETGE:  Swap = true;
9319  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9320  case ISD::SETULT: Swap = true;
9321  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9322  case ISD::SETUGE: Swap = true;
9323  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9324  }
9325  if (Swap)
9326    std::swap(Op0, Op1);
9327
9328  // Check that the operation in question is available (most are plain SSE2,
9329  // but PCMPGTQ and PCMPEQQ have different requirements).
9330  if (VT == MVT::v2i64) {
9331    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9332      return SDValue();
9333    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9334      // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9335      // pcmpeqd + pshufd + pand.
9336      assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9337
9338      // First cast everything to the right type,
9339      Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9340      Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9341
9342      // Do the compare.
9343      SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9344
9345      // Make sure the lower and upper halves are both all-ones.
9346      const int Mask[] = { 1, 0, 3, 2 };
9347      SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9348      Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9349
9350      if (Invert)
9351        Result = DAG.getNOT(dl, Result, MVT::v4i32);
9352
9353      return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9354    }
9355  }
9356
9357  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9358  // bits of the inputs before performing those operations.
9359  if (FlipSigns) {
9360    EVT EltVT = VT.getVectorElementType();
9361    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9362                                      EltVT);
9363    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9364    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9365                                    SignBits.size());
9366    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9367    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9368  }
9369
9370  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9371
9372  // If the logical-not of the result is required, perform that now.
9373  if (Invert)
9374    Result = DAG.getNOT(dl, Result, VT);
9375
9376  return Result;
9377}
9378
9379SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9380
9381  MVT VT = Op.getValueType().getSimpleVT();
9382
9383  if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9384
9385  assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9386  SDValue Op0 = Op.getOperand(0);
9387  SDValue Op1 = Op.getOperand(1);
9388  DebugLoc dl = Op.getDebugLoc();
9389  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9390
9391  // Optimize to BT if possible.
9392  // Lower (X & (1 << N)) == 0 to BT(X, N).
9393  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9394  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9395  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9396      Op1.getOpcode() == ISD::Constant &&
9397      cast<ConstantSDNode>(Op1)->isNullValue() &&
9398      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9399    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9400    if (NewSetCC.getNode())
9401      return NewSetCC;
9402  }
9403
9404  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9405  // these.
9406  if (Op1.getOpcode() == ISD::Constant &&
9407      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9408       cast<ConstantSDNode>(Op1)->isNullValue()) &&
9409      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9410
9411    // If the input is a setcc, then reuse the input setcc or use a new one with
9412    // the inverted condition.
9413    if (Op0.getOpcode() == X86ISD::SETCC) {
9414      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9415      bool Invert = (CC == ISD::SETNE) ^
9416        cast<ConstantSDNode>(Op1)->isNullValue();
9417      if (!Invert) return Op0;
9418
9419      CCode = X86::GetOppositeBranchCondition(CCode);
9420      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9421                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9422    }
9423  }
9424
9425  bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9426  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9427  if (X86CC == X86::COND_INVALID)
9428    return SDValue();
9429
9430  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9431  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9432  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9433                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9434}
9435
9436// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9437static bool isX86LogicalCmp(SDValue Op) {
9438  unsigned Opc = Op.getNode()->getOpcode();
9439  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9440      Opc == X86ISD::SAHF)
9441    return true;
9442  if (Op.getResNo() == 1 &&
9443      (Opc == X86ISD::ADD ||
9444       Opc == X86ISD::SUB ||
9445       Opc == X86ISD::ADC ||
9446       Opc == X86ISD::SBB ||
9447       Opc == X86ISD::SMUL ||
9448       Opc == X86ISD::UMUL ||
9449       Opc == X86ISD::INC ||
9450       Opc == X86ISD::DEC ||
9451       Opc == X86ISD::OR ||
9452       Opc == X86ISD::XOR ||
9453       Opc == X86ISD::AND))
9454    return true;
9455
9456  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9457    return true;
9458
9459  return false;
9460}
9461
9462static bool isZero(SDValue V) {
9463  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9464  return C && C->isNullValue();
9465}
9466
9467static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9468  if (V.getOpcode() != ISD::TRUNCATE)
9469    return false;
9470
9471  SDValue VOp0 = V.getOperand(0);
9472  unsigned InBits = VOp0.getValueSizeInBits();
9473  unsigned Bits = V.getValueSizeInBits();
9474  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9475}
9476
9477SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9478  bool addTest = true;
9479  SDValue Cond  = Op.getOperand(0);
9480  SDValue Op1 = Op.getOperand(1);
9481  SDValue Op2 = Op.getOperand(2);
9482  DebugLoc DL = Op.getDebugLoc();
9483  SDValue CC;
9484
9485  if (Cond.getOpcode() == ISD::SETCC) {
9486    SDValue NewCond = LowerSETCC(Cond, DAG);
9487    if (NewCond.getNode())
9488      Cond = NewCond;
9489  }
9490
9491  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9492  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9493  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9494  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9495  if (Cond.getOpcode() == X86ISD::SETCC &&
9496      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9497      isZero(Cond.getOperand(1).getOperand(1))) {
9498    SDValue Cmp = Cond.getOperand(1);
9499
9500    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9501
9502    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9503        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9504      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9505
9506      SDValue CmpOp0 = Cmp.getOperand(0);
9507      // Apply further optimizations for special cases
9508      // (select (x != 0), -1, 0) -> neg & sbb
9509      // (select (x == 0), 0, -1) -> neg & sbb
9510      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9511        if (YC->isNullValue() &&
9512            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9513          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9514          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9515                                    DAG.getConstant(0, CmpOp0.getValueType()),
9516                                    CmpOp0);
9517          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9518                                    DAG.getConstant(X86::COND_B, MVT::i8),
9519                                    SDValue(Neg.getNode(), 1));
9520          return Res;
9521        }
9522
9523      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9524                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9525      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9526
9527      SDValue Res =   // Res = 0 or -1.
9528        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9529                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9530
9531      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9532        Res = DAG.getNOT(DL, Res, Res.getValueType());
9533
9534      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9535      if (N2C == 0 || !N2C->isNullValue())
9536        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9537      return Res;
9538    }
9539  }
9540
9541  // Look past (and (setcc_carry (cmp ...)), 1).
9542  if (Cond.getOpcode() == ISD::AND &&
9543      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9544    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9545    if (C && C->getAPIntValue() == 1)
9546      Cond = Cond.getOperand(0);
9547  }
9548
9549  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9550  // setting operand in place of the X86ISD::SETCC.
9551  unsigned CondOpcode = Cond.getOpcode();
9552  if (CondOpcode == X86ISD::SETCC ||
9553      CondOpcode == X86ISD::SETCC_CARRY) {
9554    CC = Cond.getOperand(0);
9555
9556    SDValue Cmp = Cond.getOperand(1);
9557    unsigned Opc = Cmp.getOpcode();
9558    MVT VT = Op.getValueType().getSimpleVT();
9559
9560    bool IllegalFPCMov = false;
9561    if (VT.isFloatingPoint() && !VT.isVector() &&
9562        !isScalarFPTypeInSSEReg(VT))  // FPStack?
9563      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9564
9565    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9566        Opc == X86ISD::BT) { // FIXME
9567      Cond = Cmp;
9568      addTest = false;
9569    }
9570  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9571             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9572             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9573              Cond.getOperand(0).getValueType() != MVT::i8)) {
9574    SDValue LHS = Cond.getOperand(0);
9575    SDValue RHS = Cond.getOperand(1);
9576    unsigned X86Opcode;
9577    unsigned X86Cond;
9578    SDVTList VTs;
9579    switch (CondOpcode) {
9580    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9581    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9582    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9583    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9584    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9585    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9586    default: llvm_unreachable("unexpected overflowing operator");
9587    }
9588    if (CondOpcode == ISD::UMULO)
9589      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9590                          MVT::i32);
9591    else
9592      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9593
9594    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9595
9596    if (CondOpcode == ISD::UMULO)
9597      Cond = X86Op.getValue(2);
9598    else
9599      Cond = X86Op.getValue(1);
9600
9601    CC = DAG.getConstant(X86Cond, MVT::i8);
9602    addTest = false;
9603  }
9604
9605  if (addTest) {
9606    // Look pass the truncate if the high bits are known zero.
9607    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9608        Cond = Cond.getOperand(0);
9609
9610    // We know the result of AND is compared against zero. Try to match
9611    // it to BT.
9612    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9613      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9614      if (NewSetCC.getNode()) {
9615        CC = NewSetCC.getOperand(0);
9616        Cond = NewSetCC.getOperand(1);
9617        addTest = false;
9618      }
9619    }
9620  }
9621
9622  if (addTest) {
9623    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9624    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9625  }
9626
9627  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9628  // a <  b ?  0 : -1 -> RES = setcc_carry
9629  // a >= b ? -1 :  0 -> RES = setcc_carry
9630  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9631  if (Cond.getOpcode() == X86ISD::SUB) {
9632    Cond = ConvertCmpIfNecessary(Cond, DAG);
9633    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9634
9635    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9636        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9637      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9638                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9639      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9640        return DAG.getNOT(DL, Res, Res.getValueType());
9641      return Res;
9642    }
9643  }
9644
9645  // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9646  // widen the cmov and push the truncate through. This avoids introducing a new
9647  // branch during isel and doesn't add any extensions.
9648  if (Op.getValueType() == MVT::i8 &&
9649      Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9650    SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9651    if (T1.getValueType() == T2.getValueType() &&
9652        // Blacklist CopyFromReg to avoid partial register stalls.
9653        T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9654      SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9655      SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9656      return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9657    }
9658  }
9659
9660  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9661  // condition is true.
9662  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9663  SDValue Ops[] = { Op2, Op1, CC, Cond };
9664  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9665}
9666
9667SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9668                                            SelectionDAG &DAG) const {
9669  MVT VT = Op->getValueType(0).getSimpleVT();
9670  SDValue In = Op->getOperand(0);
9671  MVT InVT = In.getValueType().getSimpleVT();
9672  DebugLoc dl = Op->getDebugLoc();
9673
9674  if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9675      (VT != MVT::v8i32 || InVT != MVT::v8i16))
9676    return SDValue();
9677
9678  if (Subtarget->hasInt256())
9679    return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9680
9681  // Optimize vectors in AVX mode
9682  // Sign extend  v8i16 to v8i32 and
9683  //              v4i32 to v4i64
9684  //
9685  // Divide input vector into two parts
9686  // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9687  // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9688  // concat the vectors to original VT
9689
9690  unsigned NumElems = InVT.getVectorNumElements();
9691  SDValue Undef = DAG.getUNDEF(InVT);
9692
9693  SmallVector<int,8> ShufMask1(NumElems, -1);
9694  for (unsigned i = 0; i != NumElems/2; ++i)
9695    ShufMask1[i] = i;
9696
9697  SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9698
9699  SmallVector<int,8> ShufMask2(NumElems, -1);
9700  for (unsigned i = 0; i != NumElems/2; ++i)
9701    ShufMask2[i] = i + NumElems/2;
9702
9703  SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9704
9705  MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9706                                VT.getVectorNumElements()/2);
9707
9708  OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9709  OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9710
9711  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9712}
9713
9714// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9715// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9716// from the AND / OR.
9717static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9718  Opc = Op.getOpcode();
9719  if (Opc != ISD::OR && Opc != ISD::AND)
9720    return false;
9721  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9722          Op.getOperand(0).hasOneUse() &&
9723          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9724          Op.getOperand(1).hasOneUse());
9725}
9726
9727// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9728// 1 and that the SETCC node has a single use.
9729static bool isXor1OfSetCC(SDValue Op) {
9730  if (Op.getOpcode() != ISD::XOR)
9731    return false;
9732  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9733  if (N1C && N1C->getAPIntValue() == 1) {
9734    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9735      Op.getOperand(0).hasOneUse();
9736  }
9737  return false;
9738}
9739
9740SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9741  bool addTest = true;
9742  SDValue Chain = Op.getOperand(0);
9743  SDValue Cond  = Op.getOperand(1);
9744  SDValue Dest  = Op.getOperand(2);
9745  DebugLoc dl = Op.getDebugLoc();
9746  SDValue CC;
9747  bool Inverted = false;
9748
9749  if (Cond.getOpcode() == ISD::SETCC) {
9750    // Check for setcc([su]{add,sub,mul}o == 0).
9751    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9752        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9753        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9754        Cond.getOperand(0).getResNo() == 1 &&
9755        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9756         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9757         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9758         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9759         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9760         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9761      Inverted = true;
9762      Cond = Cond.getOperand(0);
9763    } else {
9764      SDValue NewCond = LowerSETCC(Cond, DAG);
9765      if (NewCond.getNode())
9766        Cond = NewCond;
9767    }
9768  }
9769#if 0
9770  // FIXME: LowerXALUO doesn't handle these!!
9771  else if (Cond.getOpcode() == X86ISD::ADD  ||
9772           Cond.getOpcode() == X86ISD::SUB  ||
9773           Cond.getOpcode() == X86ISD::SMUL ||
9774           Cond.getOpcode() == X86ISD::UMUL)
9775    Cond = LowerXALUO(Cond, DAG);
9776#endif
9777
9778  // Look pass (and (setcc_carry (cmp ...)), 1).
9779  if (Cond.getOpcode() == ISD::AND &&
9780      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9781    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9782    if (C && C->getAPIntValue() == 1)
9783      Cond = Cond.getOperand(0);
9784  }
9785
9786  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9787  // setting operand in place of the X86ISD::SETCC.
9788  unsigned CondOpcode = Cond.getOpcode();
9789  if (CondOpcode == X86ISD::SETCC ||
9790      CondOpcode == X86ISD::SETCC_CARRY) {
9791    CC = Cond.getOperand(0);
9792
9793    SDValue Cmp = Cond.getOperand(1);
9794    unsigned Opc = Cmp.getOpcode();
9795    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9796    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9797      Cond = Cmp;
9798      addTest = false;
9799    } else {
9800      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9801      default: break;
9802      case X86::COND_O:
9803      case X86::COND_B:
9804        // These can only come from an arithmetic instruction with overflow,
9805        // e.g. SADDO, UADDO.
9806        Cond = Cond.getNode()->getOperand(1);
9807        addTest = false;
9808        break;
9809      }
9810    }
9811  }
9812  CondOpcode = Cond.getOpcode();
9813  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9814      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9815      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9816       Cond.getOperand(0).getValueType() != MVT::i8)) {
9817    SDValue LHS = Cond.getOperand(0);
9818    SDValue RHS = Cond.getOperand(1);
9819    unsigned X86Opcode;
9820    unsigned X86Cond;
9821    SDVTList VTs;
9822    switch (CondOpcode) {
9823    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9824    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9825    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9826    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9827    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9828    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9829    default: llvm_unreachable("unexpected overflowing operator");
9830    }
9831    if (Inverted)
9832      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9833    if (CondOpcode == ISD::UMULO)
9834      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9835                          MVT::i32);
9836    else
9837      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9838
9839    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9840
9841    if (CondOpcode == ISD::UMULO)
9842      Cond = X86Op.getValue(2);
9843    else
9844      Cond = X86Op.getValue(1);
9845
9846    CC = DAG.getConstant(X86Cond, MVT::i8);
9847    addTest = false;
9848  } else {
9849    unsigned CondOpc;
9850    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9851      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9852      if (CondOpc == ISD::OR) {
9853        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9854        // two branches instead of an explicit OR instruction with a
9855        // separate test.
9856        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9857            isX86LogicalCmp(Cmp)) {
9858          CC = Cond.getOperand(0).getOperand(0);
9859          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9860                              Chain, Dest, CC, Cmp);
9861          CC = Cond.getOperand(1).getOperand(0);
9862          Cond = Cmp;
9863          addTest = false;
9864        }
9865      } else { // ISD::AND
9866        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9867        // two branches instead of an explicit AND instruction with a
9868        // separate test. However, we only do this if this block doesn't
9869        // have a fall-through edge, because this requires an explicit
9870        // jmp when the condition is false.
9871        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9872            isX86LogicalCmp(Cmp) &&
9873            Op.getNode()->hasOneUse()) {
9874          X86::CondCode CCode =
9875            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9876          CCode = X86::GetOppositeBranchCondition(CCode);
9877          CC = DAG.getConstant(CCode, MVT::i8);
9878          SDNode *User = *Op.getNode()->use_begin();
9879          // Look for an unconditional branch following this conditional branch.
9880          // We need this because we need to reverse the successors in order
9881          // to implement FCMP_OEQ.
9882          if (User->getOpcode() == ISD::BR) {
9883            SDValue FalseBB = User->getOperand(1);
9884            SDNode *NewBR =
9885              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9886            assert(NewBR == User);
9887            (void)NewBR;
9888            Dest = FalseBB;
9889
9890            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9891                                Chain, Dest, CC, Cmp);
9892            X86::CondCode CCode =
9893              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9894            CCode = X86::GetOppositeBranchCondition(CCode);
9895            CC = DAG.getConstant(CCode, MVT::i8);
9896            Cond = Cmp;
9897            addTest = false;
9898          }
9899        }
9900      }
9901    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9902      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9903      // It should be transformed during dag combiner except when the condition
9904      // is set by a arithmetics with overflow node.
9905      X86::CondCode CCode =
9906        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9907      CCode = X86::GetOppositeBranchCondition(CCode);
9908      CC = DAG.getConstant(CCode, MVT::i8);
9909      Cond = Cond.getOperand(0).getOperand(1);
9910      addTest = false;
9911    } else if (Cond.getOpcode() == ISD::SETCC &&
9912               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9913      // For FCMP_OEQ, we can emit
9914      // two branches instead of an explicit AND instruction with a
9915      // separate test. However, we only do this if this block doesn't
9916      // have a fall-through edge, because this requires an explicit
9917      // jmp when the condition is false.
9918      if (Op.getNode()->hasOneUse()) {
9919        SDNode *User = *Op.getNode()->use_begin();
9920        // Look for an unconditional branch following this conditional branch.
9921        // We need this because we need to reverse the successors in order
9922        // to implement FCMP_OEQ.
9923        if (User->getOpcode() == ISD::BR) {
9924          SDValue FalseBB = User->getOperand(1);
9925          SDNode *NewBR =
9926            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9927          assert(NewBR == User);
9928          (void)NewBR;
9929          Dest = FalseBB;
9930
9931          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9932                                    Cond.getOperand(0), Cond.getOperand(1));
9933          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9934          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9935          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9936                              Chain, Dest, CC, Cmp);
9937          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9938          Cond = Cmp;
9939          addTest = false;
9940        }
9941      }
9942    } else if (Cond.getOpcode() == ISD::SETCC &&
9943               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9944      // For FCMP_UNE, we can emit
9945      // two branches instead of an explicit AND instruction with a
9946      // separate test. However, we only do this if this block doesn't
9947      // have a fall-through edge, because this requires an explicit
9948      // jmp when the condition is false.
9949      if (Op.getNode()->hasOneUse()) {
9950        SDNode *User = *Op.getNode()->use_begin();
9951        // Look for an unconditional branch following this conditional branch.
9952        // We need this because we need to reverse the successors in order
9953        // to implement FCMP_UNE.
9954        if (User->getOpcode() == ISD::BR) {
9955          SDValue FalseBB = User->getOperand(1);
9956          SDNode *NewBR =
9957            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9958          assert(NewBR == User);
9959          (void)NewBR;
9960
9961          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9962                                    Cond.getOperand(0), Cond.getOperand(1));
9963          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9964          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9965          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9966                              Chain, Dest, CC, Cmp);
9967          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9968          Cond = Cmp;
9969          addTest = false;
9970          Dest = FalseBB;
9971        }
9972      }
9973    }
9974  }
9975
9976  if (addTest) {
9977    // Look pass the truncate if the high bits are known zero.
9978    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9979        Cond = Cond.getOperand(0);
9980
9981    // We know the result of AND is compared against zero. Try to match
9982    // it to BT.
9983    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9984      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9985      if (NewSetCC.getNode()) {
9986        CC = NewSetCC.getOperand(0);
9987        Cond = NewSetCC.getOperand(1);
9988        addTest = false;
9989      }
9990    }
9991  }
9992
9993  if (addTest) {
9994    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9995    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9996  }
9997  Cond = ConvertCmpIfNecessary(Cond, DAG);
9998  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9999                     Chain, Dest, CC, Cond);
10000}
10001
10002// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10003// Calls to _alloca is needed to probe the stack when allocating more than 4k
10004// bytes in one go. Touching the stack at 4K increments is necessary to ensure
10005// that the guard pages used by the OS virtual memory manager are allocated in
10006// correct sequence.
10007SDValue
10008X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10009                                           SelectionDAG &DAG) const {
10010  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10011          getTargetMachine().Options.EnableSegmentedStacks) &&
10012         "This should be used only on Windows targets or when segmented stacks "
10013         "are being used");
10014  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10015  DebugLoc dl = Op.getDebugLoc();
10016
10017  // Get the inputs.
10018  SDValue Chain = Op.getOperand(0);
10019  SDValue Size  = Op.getOperand(1);
10020  // FIXME: Ensure alignment here
10021
10022  bool Is64Bit = Subtarget->is64Bit();
10023  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10024
10025  if (getTargetMachine().Options.EnableSegmentedStacks) {
10026    MachineFunction &MF = DAG.getMachineFunction();
10027    MachineRegisterInfo &MRI = MF.getRegInfo();
10028
10029    if (Is64Bit) {
10030      // The 64 bit implementation of segmented stacks needs to clobber both r10
10031      // r11. This makes it impossible to use it along with nested parameters.
10032      const Function *F = MF.getFunction();
10033
10034      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10035           I != E; ++I)
10036        if (I->hasNestAttr())
10037          report_fatal_error("Cannot use segmented stacks with functions that "
10038                             "have nested arguments.");
10039    }
10040
10041    const TargetRegisterClass *AddrRegClass =
10042      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10043    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10044    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10045    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10046                                DAG.getRegister(Vreg, SPTy));
10047    SDValue Ops1[2] = { Value, Chain };
10048    return DAG.getMergeValues(Ops1, 2, dl);
10049  } else {
10050    SDValue Flag;
10051    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10052
10053    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10054    Flag = Chain.getValue(1);
10055    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10056
10057    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10058    Flag = Chain.getValue(1);
10059
10060    Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10061                               SPTy).getValue(1);
10062
10063    SDValue Ops1[2] = { Chain.getValue(0), Chain };
10064    return DAG.getMergeValues(Ops1, 2, dl);
10065  }
10066}
10067
10068SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10069  MachineFunction &MF = DAG.getMachineFunction();
10070  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10071
10072  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10073  DebugLoc DL = Op.getDebugLoc();
10074
10075  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10076    // vastart just stores the address of the VarArgsFrameIndex slot into the
10077    // memory location argument.
10078    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10079                                   getPointerTy());
10080    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10081                        MachinePointerInfo(SV), false, false, 0);
10082  }
10083
10084  // __va_list_tag:
10085  //   gp_offset         (0 - 6 * 8)
10086  //   fp_offset         (48 - 48 + 8 * 16)
10087  //   overflow_arg_area (point to parameters coming in memory).
10088  //   reg_save_area
10089  SmallVector<SDValue, 8> MemOps;
10090  SDValue FIN = Op.getOperand(1);
10091  // Store gp_offset
10092  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10093                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10094                                               MVT::i32),
10095                               FIN, MachinePointerInfo(SV), false, false, 0);
10096  MemOps.push_back(Store);
10097
10098  // Store fp_offset
10099  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10100                    FIN, DAG.getIntPtrConstant(4));
10101  Store = DAG.getStore(Op.getOperand(0), DL,
10102                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10103                                       MVT::i32),
10104                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
10105  MemOps.push_back(Store);
10106
10107  // Store ptr to overflow_arg_area
10108  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10109                    FIN, DAG.getIntPtrConstant(4));
10110  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10111                                    getPointerTy());
10112  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10113                       MachinePointerInfo(SV, 8),
10114                       false, false, 0);
10115  MemOps.push_back(Store);
10116
10117  // Store ptr to reg_save_area.
10118  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10119                    FIN, DAG.getIntPtrConstant(8));
10120  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10121                                    getPointerTy());
10122  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10123                       MachinePointerInfo(SV, 16), false, false, 0);
10124  MemOps.push_back(Store);
10125  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10126                     &MemOps[0], MemOps.size());
10127}
10128
10129SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10130  assert(Subtarget->is64Bit() &&
10131         "LowerVAARG only handles 64-bit va_arg!");
10132  assert((Subtarget->isTargetLinux() ||
10133          Subtarget->isTargetDarwin()) &&
10134          "Unhandled target in LowerVAARG");
10135  assert(Op.getNode()->getNumOperands() == 4);
10136  SDValue Chain = Op.getOperand(0);
10137  SDValue SrcPtr = Op.getOperand(1);
10138  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10139  unsigned Align = Op.getConstantOperandVal(3);
10140  DebugLoc dl = Op.getDebugLoc();
10141
10142  EVT ArgVT = Op.getNode()->getValueType(0);
10143  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10144  uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10145  uint8_t ArgMode;
10146
10147  // Decide which area this value should be read from.
10148  // TODO: Implement the AMD64 ABI in its entirety. This simple
10149  // selection mechanism works only for the basic types.
10150  if (ArgVT == MVT::f80) {
10151    llvm_unreachable("va_arg for f80 not yet implemented");
10152  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10153    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10154  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10155    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10156  } else {
10157    llvm_unreachable("Unhandled argument type in LowerVAARG");
10158  }
10159
10160  if (ArgMode == 2) {
10161    // Sanity Check: Make sure using fp_offset makes sense.
10162    assert(!getTargetMachine().Options.UseSoftFloat &&
10163           !(DAG.getMachineFunction()
10164                .getFunction()->getAttributes()
10165                .hasAttribute(AttributeSet::FunctionIndex,
10166                              Attribute::NoImplicitFloat)) &&
10167           Subtarget->hasSSE1());
10168  }
10169
10170  // Insert VAARG_64 node into the DAG
10171  // VAARG_64 returns two values: Variable Argument Address, Chain
10172  SmallVector<SDValue, 11> InstOps;
10173  InstOps.push_back(Chain);
10174  InstOps.push_back(SrcPtr);
10175  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10176  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10177  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10178  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10179  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10180                                          VTs, &InstOps[0], InstOps.size(),
10181                                          MVT::i64,
10182                                          MachinePointerInfo(SV),
10183                                          /*Align=*/0,
10184                                          /*Volatile=*/false,
10185                                          /*ReadMem=*/true,
10186                                          /*WriteMem=*/true);
10187  Chain = VAARG.getValue(1);
10188
10189  // Load the next argument and return it
10190  return DAG.getLoad(ArgVT, dl,
10191                     Chain,
10192                     VAARG,
10193                     MachinePointerInfo(),
10194                     false, false, false, 0);
10195}
10196
10197static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10198                           SelectionDAG &DAG) {
10199  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10200  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10201  SDValue Chain = Op.getOperand(0);
10202  SDValue DstPtr = Op.getOperand(1);
10203  SDValue SrcPtr = Op.getOperand(2);
10204  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10205  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10206  DebugLoc DL = Op.getDebugLoc();
10207
10208  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10209                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10210                       false,
10211                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10212}
10213
10214// getTargetVShiftNode - Handle vector element shifts where the shift amount
10215// may or may not be a constant. Takes immediate version of shift as input.
10216static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10217                                   SDValue SrcOp, SDValue ShAmt,
10218                                   SelectionDAG &DAG) {
10219  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10220
10221  if (isa<ConstantSDNode>(ShAmt)) {
10222    // Constant may be a TargetConstant. Use a regular constant.
10223    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10224    switch (Opc) {
10225      default: llvm_unreachable("Unknown target vector shift node");
10226      case X86ISD::VSHLI:
10227      case X86ISD::VSRLI:
10228      case X86ISD::VSRAI:
10229        return DAG.getNode(Opc, dl, VT, SrcOp,
10230                           DAG.getConstant(ShiftAmt, MVT::i32));
10231    }
10232  }
10233
10234  // Change opcode to non-immediate version
10235  switch (Opc) {
10236    default: llvm_unreachable("Unknown target vector shift node");
10237    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10238    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10239    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10240  }
10241
10242  // Need to build a vector containing shift amount
10243  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10244  SDValue ShOps[4];
10245  ShOps[0] = ShAmt;
10246  ShOps[1] = DAG.getConstant(0, MVT::i32);
10247  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10248  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10249
10250  // The return type has to be a 128-bit type with the same element
10251  // type as the input type.
10252  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10253  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10254
10255  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10256  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10257}
10258
10259static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10260  DebugLoc dl = Op.getDebugLoc();
10261  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10262  switch (IntNo) {
10263  default: return SDValue();    // Don't custom lower most intrinsics.
10264  // Comparison intrinsics.
10265  case Intrinsic::x86_sse_comieq_ss:
10266  case Intrinsic::x86_sse_comilt_ss:
10267  case Intrinsic::x86_sse_comile_ss:
10268  case Intrinsic::x86_sse_comigt_ss:
10269  case Intrinsic::x86_sse_comige_ss:
10270  case Intrinsic::x86_sse_comineq_ss:
10271  case Intrinsic::x86_sse_ucomieq_ss:
10272  case Intrinsic::x86_sse_ucomilt_ss:
10273  case Intrinsic::x86_sse_ucomile_ss:
10274  case Intrinsic::x86_sse_ucomigt_ss:
10275  case Intrinsic::x86_sse_ucomige_ss:
10276  case Intrinsic::x86_sse_ucomineq_ss:
10277  case Intrinsic::x86_sse2_comieq_sd:
10278  case Intrinsic::x86_sse2_comilt_sd:
10279  case Intrinsic::x86_sse2_comile_sd:
10280  case Intrinsic::x86_sse2_comigt_sd:
10281  case Intrinsic::x86_sse2_comige_sd:
10282  case Intrinsic::x86_sse2_comineq_sd:
10283  case Intrinsic::x86_sse2_ucomieq_sd:
10284  case Intrinsic::x86_sse2_ucomilt_sd:
10285  case Intrinsic::x86_sse2_ucomile_sd:
10286  case Intrinsic::x86_sse2_ucomigt_sd:
10287  case Intrinsic::x86_sse2_ucomige_sd:
10288  case Intrinsic::x86_sse2_ucomineq_sd: {
10289    unsigned Opc;
10290    ISD::CondCode CC;
10291    switch (IntNo) {
10292    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10293    case Intrinsic::x86_sse_comieq_ss:
10294    case Intrinsic::x86_sse2_comieq_sd:
10295      Opc = X86ISD::COMI;
10296      CC = ISD::SETEQ;
10297      break;
10298    case Intrinsic::x86_sse_comilt_ss:
10299    case Intrinsic::x86_sse2_comilt_sd:
10300      Opc = X86ISD::COMI;
10301      CC = ISD::SETLT;
10302      break;
10303    case Intrinsic::x86_sse_comile_ss:
10304    case Intrinsic::x86_sse2_comile_sd:
10305      Opc = X86ISD::COMI;
10306      CC = ISD::SETLE;
10307      break;
10308    case Intrinsic::x86_sse_comigt_ss:
10309    case Intrinsic::x86_sse2_comigt_sd:
10310      Opc = X86ISD::COMI;
10311      CC = ISD::SETGT;
10312      break;
10313    case Intrinsic::x86_sse_comige_ss:
10314    case Intrinsic::x86_sse2_comige_sd:
10315      Opc = X86ISD::COMI;
10316      CC = ISD::SETGE;
10317      break;
10318    case Intrinsic::x86_sse_comineq_ss:
10319    case Intrinsic::x86_sse2_comineq_sd:
10320      Opc = X86ISD::COMI;
10321      CC = ISD::SETNE;
10322      break;
10323    case Intrinsic::x86_sse_ucomieq_ss:
10324    case Intrinsic::x86_sse2_ucomieq_sd:
10325      Opc = X86ISD::UCOMI;
10326      CC = ISD::SETEQ;
10327      break;
10328    case Intrinsic::x86_sse_ucomilt_ss:
10329    case Intrinsic::x86_sse2_ucomilt_sd:
10330      Opc = X86ISD::UCOMI;
10331      CC = ISD::SETLT;
10332      break;
10333    case Intrinsic::x86_sse_ucomile_ss:
10334    case Intrinsic::x86_sse2_ucomile_sd:
10335      Opc = X86ISD::UCOMI;
10336      CC = ISD::SETLE;
10337      break;
10338    case Intrinsic::x86_sse_ucomigt_ss:
10339    case Intrinsic::x86_sse2_ucomigt_sd:
10340      Opc = X86ISD::UCOMI;
10341      CC = ISD::SETGT;
10342      break;
10343    case Intrinsic::x86_sse_ucomige_ss:
10344    case Intrinsic::x86_sse2_ucomige_sd:
10345      Opc = X86ISD::UCOMI;
10346      CC = ISD::SETGE;
10347      break;
10348    case Intrinsic::x86_sse_ucomineq_ss:
10349    case Intrinsic::x86_sse2_ucomineq_sd:
10350      Opc = X86ISD::UCOMI;
10351      CC = ISD::SETNE;
10352      break;
10353    }
10354
10355    SDValue LHS = Op.getOperand(1);
10356    SDValue RHS = Op.getOperand(2);
10357    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10358    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10359    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10360    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10361                                DAG.getConstant(X86CC, MVT::i8), Cond);
10362    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10363  }
10364
10365  // Arithmetic intrinsics.
10366  case Intrinsic::x86_sse2_pmulu_dq:
10367  case Intrinsic::x86_avx2_pmulu_dq:
10368    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10369                       Op.getOperand(1), Op.getOperand(2));
10370
10371  // SSE2/AVX2 sub with unsigned saturation intrinsics
10372  case Intrinsic::x86_sse2_psubus_b:
10373  case Intrinsic::x86_sse2_psubus_w:
10374  case Intrinsic::x86_avx2_psubus_b:
10375  case Intrinsic::x86_avx2_psubus_w:
10376    return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10377                       Op.getOperand(1), Op.getOperand(2));
10378
10379  // SSE3/AVX horizontal add/sub intrinsics
10380  case Intrinsic::x86_sse3_hadd_ps:
10381  case Intrinsic::x86_sse3_hadd_pd:
10382  case Intrinsic::x86_avx_hadd_ps_256:
10383  case Intrinsic::x86_avx_hadd_pd_256:
10384  case Intrinsic::x86_sse3_hsub_ps:
10385  case Intrinsic::x86_sse3_hsub_pd:
10386  case Intrinsic::x86_avx_hsub_ps_256:
10387  case Intrinsic::x86_avx_hsub_pd_256:
10388  case Intrinsic::x86_ssse3_phadd_w_128:
10389  case Intrinsic::x86_ssse3_phadd_d_128:
10390  case Intrinsic::x86_avx2_phadd_w:
10391  case Intrinsic::x86_avx2_phadd_d:
10392  case Intrinsic::x86_ssse3_phsub_w_128:
10393  case Intrinsic::x86_ssse3_phsub_d_128:
10394  case Intrinsic::x86_avx2_phsub_w:
10395  case Intrinsic::x86_avx2_phsub_d: {
10396    unsigned Opcode;
10397    switch (IntNo) {
10398    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10399    case Intrinsic::x86_sse3_hadd_ps:
10400    case Intrinsic::x86_sse3_hadd_pd:
10401    case Intrinsic::x86_avx_hadd_ps_256:
10402    case Intrinsic::x86_avx_hadd_pd_256:
10403      Opcode = X86ISD::FHADD;
10404      break;
10405    case Intrinsic::x86_sse3_hsub_ps:
10406    case Intrinsic::x86_sse3_hsub_pd:
10407    case Intrinsic::x86_avx_hsub_ps_256:
10408    case Intrinsic::x86_avx_hsub_pd_256:
10409      Opcode = X86ISD::FHSUB;
10410      break;
10411    case Intrinsic::x86_ssse3_phadd_w_128:
10412    case Intrinsic::x86_ssse3_phadd_d_128:
10413    case Intrinsic::x86_avx2_phadd_w:
10414    case Intrinsic::x86_avx2_phadd_d:
10415      Opcode = X86ISD::HADD;
10416      break;
10417    case Intrinsic::x86_ssse3_phsub_w_128:
10418    case Intrinsic::x86_ssse3_phsub_d_128:
10419    case Intrinsic::x86_avx2_phsub_w:
10420    case Intrinsic::x86_avx2_phsub_d:
10421      Opcode = X86ISD::HSUB;
10422      break;
10423    }
10424    return DAG.getNode(Opcode, dl, Op.getValueType(),
10425                       Op.getOperand(1), Op.getOperand(2));
10426  }
10427
10428  // SSE2/SSE41/AVX2 integer max/min intrinsics.
10429  case Intrinsic::x86_sse2_pmaxu_b:
10430  case Intrinsic::x86_sse41_pmaxuw:
10431  case Intrinsic::x86_sse41_pmaxud:
10432  case Intrinsic::x86_avx2_pmaxu_b:
10433  case Intrinsic::x86_avx2_pmaxu_w:
10434  case Intrinsic::x86_avx2_pmaxu_d:
10435  case Intrinsic::x86_sse2_pminu_b:
10436  case Intrinsic::x86_sse41_pminuw:
10437  case Intrinsic::x86_sse41_pminud:
10438  case Intrinsic::x86_avx2_pminu_b:
10439  case Intrinsic::x86_avx2_pminu_w:
10440  case Intrinsic::x86_avx2_pminu_d:
10441  case Intrinsic::x86_sse41_pmaxsb:
10442  case Intrinsic::x86_sse2_pmaxs_w:
10443  case Intrinsic::x86_sse41_pmaxsd:
10444  case Intrinsic::x86_avx2_pmaxs_b:
10445  case Intrinsic::x86_avx2_pmaxs_w:
10446  case Intrinsic::x86_avx2_pmaxs_d:
10447  case Intrinsic::x86_sse41_pminsb:
10448  case Intrinsic::x86_sse2_pmins_w:
10449  case Intrinsic::x86_sse41_pminsd:
10450  case Intrinsic::x86_avx2_pmins_b:
10451  case Intrinsic::x86_avx2_pmins_w:
10452  case Intrinsic::x86_avx2_pmins_d: {
10453    unsigned Opcode;
10454    switch (IntNo) {
10455    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10456    case Intrinsic::x86_sse2_pmaxu_b:
10457    case Intrinsic::x86_sse41_pmaxuw:
10458    case Intrinsic::x86_sse41_pmaxud:
10459    case Intrinsic::x86_avx2_pmaxu_b:
10460    case Intrinsic::x86_avx2_pmaxu_w:
10461    case Intrinsic::x86_avx2_pmaxu_d:
10462      Opcode = X86ISD::UMAX;
10463      break;
10464    case Intrinsic::x86_sse2_pminu_b:
10465    case Intrinsic::x86_sse41_pminuw:
10466    case Intrinsic::x86_sse41_pminud:
10467    case Intrinsic::x86_avx2_pminu_b:
10468    case Intrinsic::x86_avx2_pminu_w:
10469    case Intrinsic::x86_avx2_pminu_d:
10470      Opcode = X86ISD::UMIN;
10471      break;
10472    case Intrinsic::x86_sse41_pmaxsb:
10473    case Intrinsic::x86_sse2_pmaxs_w:
10474    case Intrinsic::x86_sse41_pmaxsd:
10475    case Intrinsic::x86_avx2_pmaxs_b:
10476    case Intrinsic::x86_avx2_pmaxs_w:
10477    case Intrinsic::x86_avx2_pmaxs_d:
10478      Opcode = X86ISD::SMAX;
10479      break;
10480    case Intrinsic::x86_sse41_pminsb:
10481    case Intrinsic::x86_sse2_pmins_w:
10482    case Intrinsic::x86_sse41_pminsd:
10483    case Intrinsic::x86_avx2_pmins_b:
10484    case Intrinsic::x86_avx2_pmins_w:
10485    case Intrinsic::x86_avx2_pmins_d:
10486      Opcode = X86ISD::SMIN;
10487      break;
10488    }
10489    return DAG.getNode(Opcode, dl, Op.getValueType(),
10490                       Op.getOperand(1), Op.getOperand(2));
10491  }
10492
10493  // SSE/SSE2/AVX floating point max/min intrinsics.
10494  case Intrinsic::x86_sse_max_ps:
10495  case Intrinsic::x86_sse2_max_pd:
10496  case Intrinsic::x86_avx_max_ps_256:
10497  case Intrinsic::x86_avx_max_pd_256:
10498  case Intrinsic::x86_sse_min_ps:
10499  case Intrinsic::x86_sse2_min_pd:
10500  case Intrinsic::x86_avx_min_ps_256:
10501  case Intrinsic::x86_avx_min_pd_256: {
10502    unsigned Opcode;
10503    switch (IntNo) {
10504    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10505    case Intrinsic::x86_sse_max_ps:
10506    case Intrinsic::x86_sse2_max_pd:
10507    case Intrinsic::x86_avx_max_ps_256:
10508    case Intrinsic::x86_avx_max_pd_256:
10509      Opcode = X86ISD::FMAX;
10510      break;
10511    case Intrinsic::x86_sse_min_ps:
10512    case Intrinsic::x86_sse2_min_pd:
10513    case Intrinsic::x86_avx_min_ps_256:
10514    case Intrinsic::x86_avx_min_pd_256:
10515      Opcode = X86ISD::FMIN;
10516      break;
10517    }
10518    return DAG.getNode(Opcode, dl, Op.getValueType(),
10519                       Op.getOperand(1), Op.getOperand(2));
10520  }
10521
10522  // AVX2 variable shift intrinsics
10523  case Intrinsic::x86_avx2_psllv_d:
10524  case Intrinsic::x86_avx2_psllv_q:
10525  case Intrinsic::x86_avx2_psllv_d_256:
10526  case Intrinsic::x86_avx2_psllv_q_256:
10527  case Intrinsic::x86_avx2_psrlv_d:
10528  case Intrinsic::x86_avx2_psrlv_q:
10529  case Intrinsic::x86_avx2_psrlv_d_256:
10530  case Intrinsic::x86_avx2_psrlv_q_256:
10531  case Intrinsic::x86_avx2_psrav_d:
10532  case Intrinsic::x86_avx2_psrav_d_256: {
10533    unsigned Opcode;
10534    switch (IntNo) {
10535    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10536    case Intrinsic::x86_avx2_psllv_d:
10537    case Intrinsic::x86_avx2_psllv_q:
10538    case Intrinsic::x86_avx2_psllv_d_256:
10539    case Intrinsic::x86_avx2_psllv_q_256:
10540      Opcode = ISD::SHL;
10541      break;
10542    case Intrinsic::x86_avx2_psrlv_d:
10543    case Intrinsic::x86_avx2_psrlv_q:
10544    case Intrinsic::x86_avx2_psrlv_d_256:
10545    case Intrinsic::x86_avx2_psrlv_q_256:
10546      Opcode = ISD::SRL;
10547      break;
10548    case Intrinsic::x86_avx2_psrav_d:
10549    case Intrinsic::x86_avx2_psrav_d_256:
10550      Opcode = ISD::SRA;
10551      break;
10552    }
10553    return DAG.getNode(Opcode, dl, Op.getValueType(),
10554                       Op.getOperand(1), Op.getOperand(2));
10555  }
10556
10557  case Intrinsic::x86_ssse3_pshuf_b_128:
10558  case Intrinsic::x86_avx2_pshuf_b:
10559    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10560                       Op.getOperand(1), Op.getOperand(2));
10561
10562  case Intrinsic::x86_ssse3_psign_b_128:
10563  case Intrinsic::x86_ssse3_psign_w_128:
10564  case Intrinsic::x86_ssse3_psign_d_128:
10565  case Intrinsic::x86_avx2_psign_b:
10566  case Intrinsic::x86_avx2_psign_w:
10567  case Intrinsic::x86_avx2_psign_d:
10568    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10569                       Op.getOperand(1), Op.getOperand(2));
10570
10571  case Intrinsic::x86_sse41_insertps:
10572    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10573                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10574
10575  case Intrinsic::x86_avx_vperm2f128_ps_256:
10576  case Intrinsic::x86_avx_vperm2f128_pd_256:
10577  case Intrinsic::x86_avx_vperm2f128_si_256:
10578  case Intrinsic::x86_avx2_vperm2i128:
10579    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10580                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10581
10582  case Intrinsic::x86_avx2_permd:
10583  case Intrinsic::x86_avx2_permps:
10584    // Operands intentionally swapped. Mask is last operand to intrinsic,
10585    // but second operand for node/intruction.
10586    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10587                       Op.getOperand(2), Op.getOperand(1));
10588
10589  case Intrinsic::x86_sse_sqrt_ps:
10590  case Intrinsic::x86_sse2_sqrt_pd:
10591  case Intrinsic::x86_avx_sqrt_ps_256:
10592  case Intrinsic::x86_avx_sqrt_pd_256:
10593    return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10594
10595  // ptest and testp intrinsics. The intrinsic these come from are designed to
10596  // return an integer value, not just an instruction so lower it to the ptest
10597  // or testp pattern and a setcc for the result.
10598  case Intrinsic::x86_sse41_ptestz:
10599  case Intrinsic::x86_sse41_ptestc:
10600  case Intrinsic::x86_sse41_ptestnzc:
10601  case Intrinsic::x86_avx_ptestz_256:
10602  case Intrinsic::x86_avx_ptestc_256:
10603  case Intrinsic::x86_avx_ptestnzc_256:
10604  case Intrinsic::x86_avx_vtestz_ps:
10605  case Intrinsic::x86_avx_vtestc_ps:
10606  case Intrinsic::x86_avx_vtestnzc_ps:
10607  case Intrinsic::x86_avx_vtestz_pd:
10608  case Intrinsic::x86_avx_vtestc_pd:
10609  case Intrinsic::x86_avx_vtestnzc_pd:
10610  case Intrinsic::x86_avx_vtestz_ps_256:
10611  case Intrinsic::x86_avx_vtestc_ps_256:
10612  case Intrinsic::x86_avx_vtestnzc_ps_256:
10613  case Intrinsic::x86_avx_vtestz_pd_256:
10614  case Intrinsic::x86_avx_vtestc_pd_256:
10615  case Intrinsic::x86_avx_vtestnzc_pd_256: {
10616    bool IsTestPacked = false;
10617    unsigned X86CC;
10618    switch (IntNo) {
10619    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10620    case Intrinsic::x86_avx_vtestz_ps:
10621    case Intrinsic::x86_avx_vtestz_pd:
10622    case Intrinsic::x86_avx_vtestz_ps_256:
10623    case Intrinsic::x86_avx_vtestz_pd_256:
10624      IsTestPacked = true; // Fallthrough
10625    case Intrinsic::x86_sse41_ptestz:
10626    case Intrinsic::x86_avx_ptestz_256:
10627      // ZF = 1
10628      X86CC = X86::COND_E;
10629      break;
10630    case Intrinsic::x86_avx_vtestc_ps:
10631    case Intrinsic::x86_avx_vtestc_pd:
10632    case Intrinsic::x86_avx_vtestc_ps_256:
10633    case Intrinsic::x86_avx_vtestc_pd_256:
10634      IsTestPacked = true; // Fallthrough
10635    case Intrinsic::x86_sse41_ptestc:
10636    case Intrinsic::x86_avx_ptestc_256:
10637      // CF = 1
10638      X86CC = X86::COND_B;
10639      break;
10640    case Intrinsic::x86_avx_vtestnzc_ps:
10641    case Intrinsic::x86_avx_vtestnzc_pd:
10642    case Intrinsic::x86_avx_vtestnzc_ps_256:
10643    case Intrinsic::x86_avx_vtestnzc_pd_256:
10644      IsTestPacked = true; // Fallthrough
10645    case Intrinsic::x86_sse41_ptestnzc:
10646    case Intrinsic::x86_avx_ptestnzc_256:
10647      // ZF and CF = 0
10648      X86CC = X86::COND_A;
10649      break;
10650    }
10651
10652    SDValue LHS = Op.getOperand(1);
10653    SDValue RHS = Op.getOperand(2);
10654    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10655    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10656    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10657    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10658    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10659  }
10660
10661  // SSE/AVX shift intrinsics
10662  case Intrinsic::x86_sse2_psll_w:
10663  case Intrinsic::x86_sse2_psll_d:
10664  case Intrinsic::x86_sse2_psll_q:
10665  case Intrinsic::x86_avx2_psll_w:
10666  case Intrinsic::x86_avx2_psll_d:
10667  case Intrinsic::x86_avx2_psll_q:
10668  case Intrinsic::x86_sse2_psrl_w:
10669  case Intrinsic::x86_sse2_psrl_d:
10670  case Intrinsic::x86_sse2_psrl_q:
10671  case Intrinsic::x86_avx2_psrl_w:
10672  case Intrinsic::x86_avx2_psrl_d:
10673  case Intrinsic::x86_avx2_psrl_q:
10674  case Intrinsic::x86_sse2_psra_w:
10675  case Intrinsic::x86_sse2_psra_d:
10676  case Intrinsic::x86_avx2_psra_w:
10677  case Intrinsic::x86_avx2_psra_d: {
10678    unsigned Opcode;
10679    switch (IntNo) {
10680    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10681    case Intrinsic::x86_sse2_psll_w:
10682    case Intrinsic::x86_sse2_psll_d:
10683    case Intrinsic::x86_sse2_psll_q:
10684    case Intrinsic::x86_avx2_psll_w:
10685    case Intrinsic::x86_avx2_psll_d:
10686    case Intrinsic::x86_avx2_psll_q:
10687      Opcode = X86ISD::VSHL;
10688      break;
10689    case Intrinsic::x86_sse2_psrl_w:
10690    case Intrinsic::x86_sse2_psrl_d:
10691    case Intrinsic::x86_sse2_psrl_q:
10692    case Intrinsic::x86_avx2_psrl_w:
10693    case Intrinsic::x86_avx2_psrl_d:
10694    case Intrinsic::x86_avx2_psrl_q:
10695      Opcode = X86ISD::VSRL;
10696      break;
10697    case Intrinsic::x86_sse2_psra_w:
10698    case Intrinsic::x86_sse2_psra_d:
10699    case Intrinsic::x86_avx2_psra_w:
10700    case Intrinsic::x86_avx2_psra_d:
10701      Opcode = X86ISD::VSRA;
10702      break;
10703    }
10704    return DAG.getNode(Opcode, dl, Op.getValueType(),
10705                       Op.getOperand(1), Op.getOperand(2));
10706  }
10707
10708  // SSE/AVX immediate shift intrinsics
10709  case Intrinsic::x86_sse2_pslli_w:
10710  case Intrinsic::x86_sse2_pslli_d:
10711  case Intrinsic::x86_sse2_pslli_q:
10712  case Intrinsic::x86_avx2_pslli_w:
10713  case Intrinsic::x86_avx2_pslli_d:
10714  case Intrinsic::x86_avx2_pslli_q:
10715  case Intrinsic::x86_sse2_psrli_w:
10716  case Intrinsic::x86_sse2_psrli_d:
10717  case Intrinsic::x86_sse2_psrli_q:
10718  case Intrinsic::x86_avx2_psrli_w:
10719  case Intrinsic::x86_avx2_psrli_d:
10720  case Intrinsic::x86_avx2_psrli_q:
10721  case Intrinsic::x86_sse2_psrai_w:
10722  case Intrinsic::x86_sse2_psrai_d:
10723  case Intrinsic::x86_avx2_psrai_w:
10724  case Intrinsic::x86_avx2_psrai_d: {
10725    unsigned Opcode;
10726    switch (IntNo) {
10727    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10728    case Intrinsic::x86_sse2_pslli_w:
10729    case Intrinsic::x86_sse2_pslli_d:
10730    case Intrinsic::x86_sse2_pslli_q:
10731    case Intrinsic::x86_avx2_pslli_w:
10732    case Intrinsic::x86_avx2_pslli_d:
10733    case Intrinsic::x86_avx2_pslli_q:
10734      Opcode = X86ISD::VSHLI;
10735      break;
10736    case Intrinsic::x86_sse2_psrli_w:
10737    case Intrinsic::x86_sse2_psrli_d:
10738    case Intrinsic::x86_sse2_psrli_q:
10739    case Intrinsic::x86_avx2_psrli_w:
10740    case Intrinsic::x86_avx2_psrli_d:
10741    case Intrinsic::x86_avx2_psrli_q:
10742      Opcode = X86ISD::VSRLI;
10743      break;
10744    case Intrinsic::x86_sse2_psrai_w:
10745    case Intrinsic::x86_sse2_psrai_d:
10746    case Intrinsic::x86_avx2_psrai_w:
10747    case Intrinsic::x86_avx2_psrai_d:
10748      Opcode = X86ISD::VSRAI;
10749      break;
10750    }
10751    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10752                               Op.getOperand(1), Op.getOperand(2), DAG);
10753  }
10754
10755  case Intrinsic::x86_sse42_pcmpistria128:
10756  case Intrinsic::x86_sse42_pcmpestria128:
10757  case Intrinsic::x86_sse42_pcmpistric128:
10758  case Intrinsic::x86_sse42_pcmpestric128:
10759  case Intrinsic::x86_sse42_pcmpistrio128:
10760  case Intrinsic::x86_sse42_pcmpestrio128:
10761  case Intrinsic::x86_sse42_pcmpistris128:
10762  case Intrinsic::x86_sse42_pcmpestris128:
10763  case Intrinsic::x86_sse42_pcmpistriz128:
10764  case Intrinsic::x86_sse42_pcmpestriz128: {
10765    unsigned Opcode;
10766    unsigned X86CC;
10767    switch (IntNo) {
10768    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10769    case Intrinsic::x86_sse42_pcmpistria128:
10770      Opcode = X86ISD::PCMPISTRI;
10771      X86CC = X86::COND_A;
10772      break;
10773    case Intrinsic::x86_sse42_pcmpestria128:
10774      Opcode = X86ISD::PCMPESTRI;
10775      X86CC = X86::COND_A;
10776      break;
10777    case Intrinsic::x86_sse42_pcmpistric128:
10778      Opcode = X86ISD::PCMPISTRI;
10779      X86CC = X86::COND_B;
10780      break;
10781    case Intrinsic::x86_sse42_pcmpestric128:
10782      Opcode = X86ISD::PCMPESTRI;
10783      X86CC = X86::COND_B;
10784      break;
10785    case Intrinsic::x86_sse42_pcmpistrio128:
10786      Opcode = X86ISD::PCMPISTRI;
10787      X86CC = X86::COND_O;
10788      break;
10789    case Intrinsic::x86_sse42_pcmpestrio128:
10790      Opcode = X86ISD::PCMPESTRI;
10791      X86CC = X86::COND_O;
10792      break;
10793    case Intrinsic::x86_sse42_pcmpistris128:
10794      Opcode = X86ISD::PCMPISTRI;
10795      X86CC = X86::COND_S;
10796      break;
10797    case Intrinsic::x86_sse42_pcmpestris128:
10798      Opcode = X86ISD::PCMPESTRI;
10799      X86CC = X86::COND_S;
10800      break;
10801    case Intrinsic::x86_sse42_pcmpistriz128:
10802      Opcode = X86ISD::PCMPISTRI;
10803      X86CC = X86::COND_E;
10804      break;
10805    case Intrinsic::x86_sse42_pcmpestriz128:
10806      Opcode = X86ISD::PCMPESTRI;
10807      X86CC = X86::COND_E;
10808      break;
10809    }
10810    SmallVector<SDValue, 5> NewOps;
10811    NewOps.append(Op->op_begin()+1, Op->op_end());
10812    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10813    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10814    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10815                                DAG.getConstant(X86CC, MVT::i8),
10816                                SDValue(PCMP.getNode(), 1));
10817    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10818  }
10819
10820  case Intrinsic::x86_sse42_pcmpistri128:
10821  case Intrinsic::x86_sse42_pcmpestri128: {
10822    unsigned Opcode;
10823    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10824      Opcode = X86ISD::PCMPISTRI;
10825    else
10826      Opcode = X86ISD::PCMPESTRI;
10827
10828    SmallVector<SDValue, 5> NewOps;
10829    NewOps.append(Op->op_begin()+1, Op->op_end());
10830    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10831    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10832  }
10833  case Intrinsic::x86_fma_vfmadd_ps:
10834  case Intrinsic::x86_fma_vfmadd_pd:
10835  case Intrinsic::x86_fma_vfmsub_ps:
10836  case Intrinsic::x86_fma_vfmsub_pd:
10837  case Intrinsic::x86_fma_vfnmadd_ps:
10838  case Intrinsic::x86_fma_vfnmadd_pd:
10839  case Intrinsic::x86_fma_vfnmsub_ps:
10840  case Intrinsic::x86_fma_vfnmsub_pd:
10841  case Intrinsic::x86_fma_vfmaddsub_ps:
10842  case Intrinsic::x86_fma_vfmaddsub_pd:
10843  case Intrinsic::x86_fma_vfmsubadd_ps:
10844  case Intrinsic::x86_fma_vfmsubadd_pd:
10845  case Intrinsic::x86_fma_vfmadd_ps_256:
10846  case Intrinsic::x86_fma_vfmadd_pd_256:
10847  case Intrinsic::x86_fma_vfmsub_ps_256:
10848  case Intrinsic::x86_fma_vfmsub_pd_256:
10849  case Intrinsic::x86_fma_vfnmadd_ps_256:
10850  case Intrinsic::x86_fma_vfnmadd_pd_256:
10851  case Intrinsic::x86_fma_vfnmsub_ps_256:
10852  case Intrinsic::x86_fma_vfnmsub_pd_256:
10853  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10854  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10855  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10856  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10857    unsigned Opc;
10858    switch (IntNo) {
10859    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10860    case Intrinsic::x86_fma_vfmadd_ps:
10861    case Intrinsic::x86_fma_vfmadd_pd:
10862    case Intrinsic::x86_fma_vfmadd_ps_256:
10863    case Intrinsic::x86_fma_vfmadd_pd_256:
10864      Opc = X86ISD::FMADD;
10865      break;
10866    case Intrinsic::x86_fma_vfmsub_ps:
10867    case Intrinsic::x86_fma_vfmsub_pd:
10868    case Intrinsic::x86_fma_vfmsub_ps_256:
10869    case Intrinsic::x86_fma_vfmsub_pd_256:
10870      Opc = X86ISD::FMSUB;
10871      break;
10872    case Intrinsic::x86_fma_vfnmadd_ps:
10873    case Intrinsic::x86_fma_vfnmadd_pd:
10874    case Intrinsic::x86_fma_vfnmadd_ps_256:
10875    case Intrinsic::x86_fma_vfnmadd_pd_256:
10876      Opc = X86ISD::FNMADD;
10877      break;
10878    case Intrinsic::x86_fma_vfnmsub_ps:
10879    case Intrinsic::x86_fma_vfnmsub_pd:
10880    case Intrinsic::x86_fma_vfnmsub_ps_256:
10881    case Intrinsic::x86_fma_vfnmsub_pd_256:
10882      Opc = X86ISD::FNMSUB;
10883      break;
10884    case Intrinsic::x86_fma_vfmaddsub_ps:
10885    case Intrinsic::x86_fma_vfmaddsub_pd:
10886    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10887    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10888      Opc = X86ISD::FMADDSUB;
10889      break;
10890    case Intrinsic::x86_fma_vfmsubadd_ps:
10891    case Intrinsic::x86_fma_vfmsubadd_pd:
10892    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10893    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10894      Opc = X86ISD::FMSUBADD;
10895      break;
10896    }
10897
10898    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10899                       Op.getOperand(2), Op.getOperand(3));
10900  }
10901  }
10902}
10903
10904static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10905  DebugLoc dl = Op.getDebugLoc();
10906  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10907  switch (IntNo) {
10908  default: return SDValue();    // Don't custom lower most intrinsics.
10909
10910  // RDRAND intrinsics.
10911  case Intrinsic::x86_rdrand_16:
10912  case Intrinsic::x86_rdrand_32:
10913  case Intrinsic::x86_rdrand_64: {
10914    // Emit the node with the right value type.
10915    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10916    SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10917
10918    // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10919    // return the value from Rand, which is always 0, casted to i32.
10920    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10921                      DAG.getConstant(1, Op->getValueType(1)),
10922                      DAG.getConstant(X86::COND_B, MVT::i32),
10923                      SDValue(Result.getNode(), 1) };
10924    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10925                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10926                                  Ops, 4);
10927
10928    // Return { result, isValid, chain }.
10929    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10930                       SDValue(Result.getNode(), 2));
10931  }
10932  }
10933}
10934
10935SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10936                                           SelectionDAG &DAG) const {
10937  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10938  MFI->setReturnAddressIsTaken(true);
10939
10940  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10941  DebugLoc dl = Op.getDebugLoc();
10942  EVT PtrVT = getPointerTy();
10943
10944  if (Depth > 0) {
10945    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10946    SDValue Offset =
10947      DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10948    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10949                       DAG.getNode(ISD::ADD, dl, PtrVT,
10950                                   FrameAddr, Offset),
10951                       MachinePointerInfo(), false, false, false, 0);
10952  }
10953
10954  // Just load the return address.
10955  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10956  return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10957                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10958}
10959
10960SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10961  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10962  MFI->setFrameAddressIsTaken(true);
10963
10964  EVT VT = Op.getValueType();
10965  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10966  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10967  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10968  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10969  while (Depth--)
10970    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10971                            MachinePointerInfo(),
10972                            false, false, false, 0);
10973  return FrameAddr;
10974}
10975
10976SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10977                                                     SelectionDAG &DAG) const {
10978  return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10979}
10980
10981SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10982  SDValue Chain     = Op.getOperand(0);
10983  SDValue Offset    = Op.getOperand(1);
10984  SDValue Handler   = Op.getOperand(2);
10985  DebugLoc dl       = Op.getDebugLoc();
10986
10987  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10988                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10989                                     getPointerTy());
10990  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10991
10992  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10993                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10994  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10995  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10996                       false, false, 0);
10997  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10998
10999  return DAG.getNode(X86ISD::EH_RETURN, dl,
11000                     MVT::Other,
11001                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11002}
11003
11004SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11005                                               SelectionDAG &DAG) const {
11006  DebugLoc DL = Op.getDebugLoc();
11007  return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11008                     DAG.getVTList(MVT::i32, MVT::Other),
11009                     Op.getOperand(0), Op.getOperand(1));
11010}
11011
11012SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11013                                                SelectionDAG &DAG) const {
11014  DebugLoc DL = Op.getDebugLoc();
11015  return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11016                     Op.getOperand(0), Op.getOperand(1));
11017}
11018
11019static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11020  return Op.getOperand(0);
11021}
11022
11023SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11024                                                SelectionDAG &DAG) const {
11025  SDValue Root = Op.getOperand(0);
11026  SDValue Trmp = Op.getOperand(1); // trampoline
11027  SDValue FPtr = Op.getOperand(2); // nested function
11028  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11029  DebugLoc dl  = Op.getDebugLoc();
11030
11031  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11032  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11033
11034  if (Subtarget->is64Bit()) {
11035    SDValue OutChains[6];
11036
11037    // Large code-model.
11038    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11039    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11040
11041    const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11042    const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11043
11044    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11045
11046    // Load the pointer to the nested function into R11.
11047    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11048    SDValue Addr = Trmp;
11049    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11050                                Addr, MachinePointerInfo(TrmpAddr),
11051                                false, false, 0);
11052
11053    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11054                       DAG.getConstant(2, MVT::i64));
11055    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11056                                MachinePointerInfo(TrmpAddr, 2),
11057                                false, false, 2);
11058
11059    // Load the 'nest' parameter value into R10.
11060    // R10 is specified in X86CallingConv.td
11061    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11062    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11063                       DAG.getConstant(10, MVT::i64));
11064    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11065                                Addr, MachinePointerInfo(TrmpAddr, 10),
11066                                false, false, 0);
11067
11068    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11069                       DAG.getConstant(12, MVT::i64));
11070    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11071                                MachinePointerInfo(TrmpAddr, 12),
11072                                false, false, 2);
11073
11074    // Jump to the nested function.
11075    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11076    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11077                       DAG.getConstant(20, MVT::i64));
11078    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11079                                Addr, MachinePointerInfo(TrmpAddr, 20),
11080                                false, false, 0);
11081
11082    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11083    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11084                       DAG.getConstant(22, MVT::i64));
11085    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11086                                MachinePointerInfo(TrmpAddr, 22),
11087                                false, false, 0);
11088
11089    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11090  } else {
11091    const Function *Func =
11092      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11093    CallingConv::ID CC = Func->getCallingConv();
11094    unsigned NestReg;
11095
11096    switch (CC) {
11097    default:
11098      llvm_unreachable("Unsupported calling convention");
11099    case CallingConv::C:
11100    case CallingConv::X86_StdCall: {
11101      // Pass 'nest' parameter in ECX.
11102      // Must be kept in sync with X86CallingConv.td
11103      NestReg = X86::ECX;
11104
11105      // Check that ECX wasn't needed by an 'inreg' parameter.
11106      FunctionType *FTy = Func->getFunctionType();
11107      const AttributeSet &Attrs = Func->getAttributes();
11108
11109      if (!Attrs.isEmpty() && !Func->isVarArg()) {
11110        unsigned InRegCount = 0;
11111        unsigned Idx = 1;
11112
11113        for (FunctionType::param_iterator I = FTy->param_begin(),
11114             E = FTy->param_end(); I != E; ++I, ++Idx)
11115          if (Attrs.hasAttribute(Idx, Attribute::InReg))
11116            // FIXME: should only count parameters that are lowered to integers.
11117            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11118
11119        if (InRegCount > 2) {
11120          report_fatal_error("Nest register in use - reduce number of inreg"
11121                             " parameters!");
11122        }
11123      }
11124      break;
11125    }
11126    case CallingConv::X86_FastCall:
11127    case CallingConv::X86_ThisCall:
11128    case CallingConv::Fast:
11129      // Pass 'nest' parameter in EAX.
11130      // Must be kept in sync with X86CallingConv.td
11131      NestReg = X86::EAX;
11132      break;
11133    }
11134
11135    SDValue OutChains[4];
11136    SDValue Addr, Disp;
11137
11138    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11139                       DAG.getConstant(10, MVT::i32));
11140    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11141
11142    // This is storing the opcode for MOV32ri.
11143    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11144    const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11145    OutChains[0] = DAG.getStore(Root, dl,
11146                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11147                                Trmp, MachinePointerInfo(TrmpAddr),
11148                                false, false, 0);
11149
11150    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11151                       DAG.getConstant(1, MVT::i32));
11152    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11153                                MachinePointerInfo(TrmpAddr, 1),
11154                                false, false, 1);
11155
11156    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11157    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11158                       DAG.getConstant(5, MVT::i32));
11159    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11160                                MachinePointerInfo(TrmpAddr, 5),
11161                                false, false, 1);
11162
11163    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11164                       DAG.getConstant(6, MVT::i32));
11165    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11166                                MachinePointerInfo(TrmpAddr, 6),
11167                                false, false, 1);
11168
11169    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11170  }
11171}
11172
11173SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11174                                            SelectionDAG &DAG) const {
11175  /*
11176   The rounding mode is in bits 11:10 of FPSR, and has the following
11177   settings:
11178     00 Round to nearest
11179     01 Round to -inf
11180     10 Round to +inf
11181     11 Round to 0
11182
11183  FLT_ROUNDS, on the other hand, expects the following:
11184    -1 Undefined
11185     0 Round to 0
11186     1 Round to nearest
11187     2 Round to +inf
11188     3 Round to -inf
11189
11190  To perform the conversion, we do:
11191    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11192  */
11193
11194  MachineFunction &MF = DAG.getMachineFunction();
11195  const TargetMachine &TM = MF.getTarget();
11196  const TargetFrameLowering &TFI = *TM.getFrameLowering();
11197  unsigned StackAlignment = TFI.getStackAlignment();
11198  EVT VT = Op.getValueType();
11199  DebugLoc DL = Op.getDebugLoc();
11200
11201  // Save FP Control Word to stack slot
11202  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11203  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11204
11205  MachineMemOperand *MMO =
11206   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11207                           MachineMemOperand::MOStore, 2, 2);
11208
11209  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11210  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11211                                          DAG.getVTList(MVT::Other),
11212                                          Ops, 2, MVT::i16, MMO);
11213
11214  // Load FP Control Word from stack slot
11215  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11216                            MachinePointerInfo(), false, false, false, 0);
11217
11218  // Transform as necessary
11219  SDValue CWD1 =
11220    DAG.getNode(ISD::SRL, DL, MVT::i16,
11221                DAG.getNode(ISD::AND, DL, MVT::i16,
11222                            CWD, DAG.getConstant(0x800, MVT::i16)),
11223                DAG.getConstant(11, MVT::i8));
11224  SDValue CWD2 =
11225    DAG.getNode(ISD::SRL, DL, MVT::i16,
11226                DAG.getNode(ISD::AND, DL, MVT::i16,
11227                            CWD, DAG.getConstant(0x400, MVT::i16)),
11228                DAG.getConstant(9, MVT::i8));
11229
11230  SDValue RetVal =
11231    DAG.getNode(ISD::AND, DL, MVT::i16,
11232                DAG.getNode(ISD::ADD, DL, MVT::i16,
11233                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11234                            DAG.getConstant(1, MVT::i16)),
11235                DAG.getConstant(3, MVT::i16));
11236
11237  return DAG.getNode((VT.getSizeInBits() < 16 ?
11238                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11239}
11240
11241static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11242  EVT VT = Op.getValueType();
11243  EVT OpVT = VT;
11244  unsigned NumBits = VT.getSizeInBits();
11245  DebugLoc dl = Op.getDebugLoc();
11246
11247  Op = Op.getOperand(0);
11248  if (VT == MVT::i8) {
11249    // Zero extend to i32 since there is not an i8 bsr.
11250    OpVT = MVT::i32;
11251    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11252  }
11253
11254  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11255  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11256  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11257
11258  // If src is zero (i.e. bsr sets ZF), returns NumBits.
11259  SDValue Ops[] = {
11260    Op,
11261    DAG.getConstant(NumBits+NumBits-1, OpVT),
11262    DAG.getConstant(X86::COND_E, MVT::i8),
11263    Op.getValue(1)
11264  };
11265  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11266
11267  // Finally xor with NumBits-1.
11268  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11269
11270  if (VT == MVT::i8)
11271    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11272  return Op;
11273}
11274
11275static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11276  EVT VT = Op.getValueType();
11277  EVT OpVT = VT;
11278  unsigned NumBits = VT.getSizeInBits();
11279  DebugLoc dl = Op.getDebugLoc();
11280
11281  Op = Op.getOperand(0);
11282  if (VT == MVT::i8) {
11283    // Zero extend to i32 since there is not an i8 bsr.
11284    OpVT = MVT::i32;
11285    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11286  }
11287
11288  // Issue a bsr (scan bits in reverse).
11289  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11290  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11291
11292  // And xor with NumBits-1.
11293  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11294
11295  if (VT == MVT::i8)
11296    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11297  return Op;
11298}
11299
11300static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11301  EVT VT = Op.getValueType();
11302  unsigned NumBits = VT.getSizeInBits();
11303  DebugLoc dl = Op.getDebugLoc();
11304  Op = Op.getOperand(0);
11305
11306  // Issue a bsf (scan bits forward) which also sets EFLAGS.
11307  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11308  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11309
11310  // If src is zero (i.e. bsf sets ZF), returns NumBits.
11311  SDValue Ops[] = {
11312    Op,
11313    DAG.getConstant(NumBits, VT),
11314    DAG.getConstant(X86::COND_E, MVT::i8),
11315    Op.getValue(1)
11316  };
11317  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11318}
11319
11320// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11321// ones, and then concatenate the result back.
11322static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11323  EVT VT = Op.getValueType();
11324
11325  assert(VT.is256BitVector() && VT.isInteger() &&
11326         "Unsupported value type for operation");
11327
11328  unsigned NumElems = VT.getVectorNumElements();
11329  DebugLoc dl = Op.getDebugLoc();
11330
11331  // Extract the LHS vectors
11332  SDValue LHS = Op.getOperand(0);
11333  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11334  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11335
11336  // Extract the RHS vectors
11337  SDValue RHS = Op.getOperand(1);
11338  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11339  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11340
11341  MVT EltVT = VT.getVectorElementType().getSimpleVT();
11342  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11343
11344  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11345                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11346                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11347}
11348
11349static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11350  assert(Op.getValueType().is256BitVector() &&
11351         Op.getValueType().isInteger() &&
11352         "Only handle AVX 256-bit vector integer operation");
11353  return Lower256IntArith(Op, DAG);
11354}
11355
11356static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11357  assert(Op.getValueType().is256BitVector() &&
11358         Op.getValueType().isInteger() &&
11359         "Only handle AVX 256-bit vector integer operation");
11360  return Lower256IntArith(Op, DAG);
11361}
11362
11363static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11364                        SelectionDAG &DAG) {
11365  DebugLoc dl = Op.getDebugLoc();
11366  EVT VT = Op.getValueType();
11367
11368  // Decompose 256-bit ops into smaller 128-bit ops.
11369  if (VT.is256BitVector() && !Subtarget->hasInt256())
11370    return Lower256IntArith(Op, DAG);
11371
11372  SDValue A = Op.getOperand(0);
11373  SDValue B = Op.getOperand(1);
11374
11375  // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11376  if (VT == MVT::v4i32) {
11377    assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11378           "Should not custom lower when pmuldq is available!");
11379
11380    // Extract the odd parts.
11381    const int UnpackMask[] = { 1, -1, 3, -1 };
11382    SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11383    SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11384
11385    // Multiply the even parts.
11386    SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11387    // Now multiply odd parts.
11388    SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11389
11390    Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11391    Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11392
11393    // Merge the two vectors back together with a shuffle. This expands into 2
11394    // shuffles.
11395    const int ShufMask[] = { 0, 4, 2, 6 };
11396    return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11397  }
11398
11399  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11400         "Only know how to lower V2I64/V4I64 multiply");
11401
11402  //  Ahi = psrlqi(a, 32);
11403  //  Bhi = psrlqi(b, 32);
11404  //
11405  //  AloBlo = pmuludq(a, b);
11406  //  AloBhi = pmuludq(a, Bhi);
11407  //  AhiBlo = pmuludq(Ahi, b);
11408
11409  //  AloBhi = psllqi(AloBhi, 32);
11410  //  AhiBlo = psllqi(AhiBlo, 32);
11411  //  return AloBlo + AloBhi + AhiBlo;
11412
11413  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11414
11415  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11416  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11417
11418  // Bit cast to 32-bit vectors for MULUDQ
11419  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11420  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11421  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11422  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11423  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11424
11425  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11426  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11427  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11428
11429  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11430  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11431
11432  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11433  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11434}
11435
11436SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11437  EVT VT = Op.getValueType();
11438  EVT EltTy = VT.getVectorElementType();
11439  unsigned NumElts = VT.getVectorNumElements();
11440  SDValue N0 = Op.getOperand(0);
11441  DebugLoc dl = Op.getDebugLoc();
11442
11443  // Lower sdiv X, pow2-const.
11444  BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11445  if (!C)
11446    return SDValue();
11447
11448  APInt SplatValue, SplatUndef;
11449  unsigned MinSplatBits;
11450  bool HasAnyUndefs;
11451  if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11452    return SDValue();
11453
11454  if ((SplatValue != 0) &&
11455      (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11456    unsigned lg2 = SplatValue.countTrailingZeros();
11457    // Splat the sign bit.
11458    SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11459    SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11460    // Add (N0 < 0) ? abs2 - 1 : 0;
11461    SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11462    SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11463    SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11464    SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11465    SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11466
11467    // If we're dividing by a positive value, we're done.  Otherwise, we must
11468    // negate the result.
11469    if (SplatValue.isNonNegative())
11470      return SRA;
11471
11472    SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11473    SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11474    return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11475  }
11476  return SDValue();
11477}
11478
11479SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11480
11481  EVT VT = Op.getValueType();
11482  DebugLoc dl = Op.getDebugLoc();
11483  SDValue R = Op.getOperand(0);
11484  SDValue Amt = Op.getOperand(1);
11485
11486  if (!Subtarget->hasSSE2())
11487    return SDValue();
11488
11489  // Optimize shl/srl/sra with constant shift amount.
11490  if (isSplatVector(Amt.getNode())) {
11491    SDValue SclrAmt = Amt->getOperand(0);
11492    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11493      uint64_t ShiftAmt = C->getZExtValue();
11494
11495      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11496          (Subtarget->hasInt256() &&
11497           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11498        if (Op.getOpcode() == ISD::SHL)
11499          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11500                             DAG.getConstant(ShiftAmt, MVT::i32));
11501        if (Op.getOpcode() == ISD::SRL)
11502          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11503                             DAG.getConstant(ShiftAmt, MVT::i32));
11504        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11505          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11506                             DAG.getConstant(ShiftAmt, MVT::i32));
11507      }
11508
11509      if (VT == MVT::v16i8) {
11510        if (Op.getOpcode() == ISD::SHL) {
11511          // Make a large shift.
11512          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11513                                    DAG.getConstant(ShiftAmt, MVT::i32));
11514          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11515          // Zero out the rightmost bits.
11516          SmallVector<SDValue, 16> V(16,
11517                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11518                                                     MVT::i8));
11519          return DAG.getNode(ISD::AND, dl, VT, SHL,
11520                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11521        }
11522        if (Op.getOpcode() == ISD::SRL) {
11523          // Make a large shift.
11524          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11525                                    DAG.getConstant(ShiftAmt, MVT::i32));
11526          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11527          // Zero out the leftmost bits.
11528          SmallVector<SDValue, 16> V(16,
11529                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11530                                                     MVT::i8));
11531          return DAG.getNode(ISD::AND, dl, VT, SRL,
11532                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11533        }
11534        if (Op.getOpcode() == ISD::SRA) {
11535          if (ShiftAmt == 7) {
11536            // R s>> 7  ===  R s< 0
11537            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11538            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11539          }
11540
11541          // R s>> a === ((R u>> a) ^ m) - m
11542          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11543          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11544                                                         MVT::i8));
11545          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11546          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11547          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11548          return Res;
11549        }
11550        llvm_unreachable("Unknown shift opcode.");
11551      }
11552
11553      if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11554        if (Op.getOpcode() == ISD::SHL) {
11555          // Make a large shift.
11556          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11557                                    DAG.getConstant(ShiftAmt, MVT::i32));
11558          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11559          // Zero out the rightmost bits.
11560          SmallVector<SDValue, 32> V(32,
11561                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11562                                                     MVT::i8));
11563          return DAG.getNode(ISD::AND, dl, VT, SHL,
11564                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11565        }
11566        if (Op.getOpcode() == ISD::SRL) {
11567          // Make a large shift.
11568          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11569                                    DAG.getConstant(ShiftAmt, MVT::i32));
11570          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11571          // Zero out the leftmost bits.
11572          SmallVector<SDValue, 32> V(32,
11573                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11574                                                     MVT::i8));
11575          return DAG.getNode(ISD::AND, dl, VT, SRL,
11576                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11577        }
11578        if (Op.getOpcode() == ISD::SRA) {
11579          if (ShiftAmt == 7) {
11580            // R s>> 7  ===  R s< 0
11581            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11582            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11583          }
11584
11585          // R s>> a === ((R u>> a) ^ m) - m
11586          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11587          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11588                                                         MVT::i8));
11589          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11590          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11591          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11592          return Res;
11593        }
11594        llvm_unreachable("Unknown shift opcode.");
11595      }
11596    }
11597  }
11598
11599  // Lower SHL with variable shift amount.
11600  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11601    Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11602
11603    Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11604    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11605    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11606    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11607  }
11608  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11609    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11610
11611    // a = a << 5;
11612    Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11613    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11614
11615    // Turn 'a' into a mask suitable for VSELECT
11616    SDValue VSelM = DAG.getConstant(0x80, VT);
11617    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11618    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11619
11620    SDValue CM1 = DAG.getConstant(0x0f, VT);
11621    SDValue CM2 = DAG.getConstant(0x3f, VT);
11622
11623    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11624    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11625    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11626                            DAG.getConstant(4, MVT::i32), DAG);
11627    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11628    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11629
11630    // a += a
11631    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11632    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11633    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11634
11635    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11636    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11637    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11638                            DAG.getConstant(2, MVT::i32), DAG);
11639    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11640    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11641
11642    // a += a
11643    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11644    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11645    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11646
11647    // return VSELECT(r, r+r, a);
11648    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11649                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11650    return R;
11651  }
11652
11653  // Decompose 256-bit shifts into smaller 128-bit shifts.
11654  if (VT.is256BitVector()) {
11655    unsigned NumElems = VT.getVectorNumElements();
11656    MVT EltVT = VT.getVectorElementType().getSimpleVT();
11657    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11658
11659    // Extract the two vectors
11660    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11661    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11662
11663    // Recreate the shift amount vectors
11664    SDValue Amt1, Amt2;
11665    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11666      // Constant shift amount
11667      SmallVector<SDValue, 4> Amt1Csts;
11668      SmallVector<SDValue, 4> Amt2Csts;
11669      for (unsigned i = 0; i != NumElems/2; ++i)
11670        Amt1Csts.push_back(Amt->getOperand(i));
11671      for (unsigned i = NumElems/2; i != NumElems; ++i)
11672        Amt2Csts.push_back(Amt->getOperand(i));
11673
11674      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11675                                 &Amt1Csts[0], NumElems/2);
11676      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11677                                 &Amt2Csts[0], NumElems/2);
11678    } else {
11679      // Variable shift amount
11680      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11681      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11682    }
11683
11684    // Issue new vector shifts for the smaller types
11685    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11686    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11687
11688    // Concatenate the result back
11689    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11690  }
11691
11692  return SDValue();
11693}
11694
11695static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11696  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11697  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11698  // looks for this combo and may remove the "setcc" instruction if the "setcc"
11699  // has only one use.
11700  SDNode *N = Op.getNode();
11701  SDValue LHS = N->getOperand(0);
11702  SDValue RHS = N->getOperand(1);
11703  unsigned BaseOp = 0;
11704  unsigned Cond = 0;
11705  DebugLoc DL = Op.getDebugLoc();
11706  switch (Op.getOpcode()) {
11707  default: llvm_unreachable("Unknown ovf instruction!");
11708  case ISD::SADDO:
11709    // A subtract of one will be selected as a INC. Note that INC doesn't
11710    // set CF, so we can't do this for UADDO.
11711    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11712      if (C->isOne()) {
11713        BaseOp = X86ISD::INC;
11714        Cond = X86::COND_O;
11715        break;
11716      }
11717    BaseOp = X86ISD::ADD;
11718    Cond = X86::COND_O;
11719    break;
11720  case ISD::UADDO:
11721    BaseOp = X86ISD::ADD;
11722    Cond = X86::COND_B;
11723    break;
11724  case ISD::SSUBO:
11725    // A subtract of one will be selected as a DEC. Note that DEC doesn't
11726    // set CF, so we can't do this for USUBO.
11727    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11728      if (C->isOne()) {
11729        BaseOp = X86ISD::DEC;
11730        Cond = X86::COND_O;
11731        break;
11732      }
11733    BaseOp = X86ISD::SUB;
11734    Cond = X86::COND_O;
11735    break;
11736  case ISD::USUBO:
11737    BaseOp = X86ISD::SUB;
11738    Cond = X86::COND_B;
11739    break;
11740  case ISD::SMULO:
11741    BaseOp = X86ISD::SMUL;
11742    Cond = X86::COND_O;
11743    break;
11744  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11745    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11746                                 MVT::i32);
11747    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11748
11749    SDValue SetCC =
11750      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11751                  DAG.getConstant(X86::COND_O, MVT::i32),
11752                  SDValue(Sum.getNode(), 2));
11753
11754    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11755  }
11756  }
11757
11758  // Also sets EFLAGS.
11759  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11760  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11761
11762  SDValue SetCC =
11763    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11764                DAG.getConstant(Cond, MVT::i32),
11765                SDValue(Sum.getNode(), 1));
11766
11767  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11768}
11769
11770SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11771                                                  SelectionDAG &DAG) const {
11772  DebugLoc dl = Op.getDebugLoc();
11773  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11774  EVT VT = Op.getValueType();
11775
11776  if (!Subtarget->hasSSE2() || !VT.isVector())
11777    return SDValue();
11778
11779  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11780                      ExtraVT.getScalarType().getSizeInBits();
11781  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11782
11783  switch (VT.getSimpleVT().SimpleTy) {
11784    default: return SDValue();
11785    case MVT::v8i32:
11786    case MVT::v16i16:
11787      if (!Subtarget->hasFp256())
11788        return SDValue();
11789      if (!Subtarget->hasInt256()) {
11790        // needs to be split
11791        unsigned NumElems = VT.getVectorNumElements();
11792
11793        // Extract the LHS vectors
11794        SDValue LHS = Op.getOperand(0);
11795        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11796        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11797
11798        MVT EltVT = VT.getVectorElementType().getSimpleVT();
11799        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11800
11801        EVT ExtraEltVT = ExtraVT.getVectorElementType();
11802        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11803        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11804                                   ExtraNumElems/2);
11805        SDValue Extra = DAG.getValueType(ExtraVT);
11806
11807        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11808        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11809
11810        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11811      }
11812      // fall through
11813    case MVT::v4i32:
11814    case MVT::v8i16: {
11815      SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11816                                         Op.getOperand(0), ShAmt, DAG);
11817      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11818    }
11819  }
11820}
11821
11822static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11823                              SelectionDAG &DAG) {
11824  DebugLoc dl = Op.getDebugLoc();
11825
11826  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11827  // There isn't any reason to disable it if the target processor supports it.
11828  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11829    SDValue Chain = Op.getOperand(0);
11830    SDValue Zero = DAG.getConstant(0, MVT::i32);
11831    SDValue Ops[] = {
11832      DAG.getRegister(X86::ESP, MVT::i32), // Base
11833      DAG.getTargetConstant(1, MVT::i8),   // Scale
11834      DAG.getRegister(0, MVT::i32),        // Index
11835      DAG.getTargetConstant(0, MVT::i32),  // Disp
11836      DAG.getRegister(0, MVT::i32),        // Segment.
11837      Zero,
11838      Chain
11839    };
11840    SDNode *Res =
11841      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11842                          array_lengthof(Ops));
11843    return SDValue(Res, 0);
11844  }
11845
11846  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11847  if (!isDev)
11848    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11849
11850  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11851  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11852  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11853  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11854
11855  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11856  if (!Op1 && !Op2 && !Op3 && Op4)
11857    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11858
11859  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11860  if (Op1 && !Op2 && !Op3 && !Op4)
11861    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11862
11863  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11864  //           (MFENCE)>;
11865  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11866}
11867
11868static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11869                                 SelectionDAG &DAG) {
11870  DebugLoc dl = Op.getDebugLoc();
11871  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11872    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11873  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11874    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11875
11876  // The only fence that needs an instruction is a sequentially-consistent
11877  // cross-thread fence.
11878  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11879    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11880    // no-sse2). There isn't any reason to disable it if the target processor
11881    // supports it.
11882    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11883      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11884
11885    SDValue Chain = Op.getOperand(0);
11886    SDValue Zero = DAG.getConstant(0, MVT::i32);
11887    SDValue Ops[] = {
11888      DAG.getRegister(X86::ESP, MVT::i32), // Base
11889      DAG.getTargetConstant(1, MVT::i8),   // Scale
11890      DAG.getRegister(0, MVT::i32),        // Index
11891      DAG.getTargetConstant(0, MVT::i32),  // Disp
11892      DAG.getRegister(0, MVT::i32),        // Segment.
11893      Zero,
11894      Chain
11895    };
11896    SDNode *Res =
11897      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11898                         array_lengthof(Ops));
11899    return SDValue(Res, 0);
11900  }
11901
11902  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11903  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11904}
11905
11906static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11907                             SelectionDAG &DAG) {
11908  EVT T = Op.getValueType();
11909  DebugLoc DL = Op.getDebugLoc();
11910  unsigned Reg = 0;
11911  unsigned size = 0;
11912  switch(T.getSimpleVT().SimpleTy) {
11913  default: llvm_unreachable("Invalid value type!");
11914  case MVT::i8:  Reg = X86::AL;  size = 1; break;
11915  case MVT::i16: Reg = X86::AX;  size = 2; break;
11916  case MVT::i32: Reg = X86::EAX; size = 4; break;
11917  case MVT::i64:
11918    assert(Subtarget->is64Bit() && "Node not type legal!");
11919    Reg = X86::RAX; size = 8;
11920    break;
11921  }
11922  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11923                                    Op.getOperand(2), SDValue());
11924  SDValue Ops[] = { cpIn.getValue(0),
11925                    Op.getOperand(1),
11926                    Op.getOperand(3),
11927                    DAG.getTargetConstant(size, MVT::i8),
11928                    cpIn.getValue(1) };
11929  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11930  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11931  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11932                                           Ops, 5, T, MMO);
11933  SDValue cpOut =
11934    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11935  return cpOut;
11936}
11937
11938static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11939                                     SelectionDAG &DAG) {
11940  assert(Subtarget->is64Bit() && "Result not type legalized?");
11941  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11942  SDValue TheChain = Op.getOperand(0);
11943  DebugLoc dl = Op.getDebugLoc();
11944  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11945  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11946  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11947                                   rax.getValue(2));
11948  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11949                            DAG.getConstant(32, MVT::i8));
11950  SDValue Ops[] = {
11951    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11952    rdx.getValue(1)
11953  };
11954  return DAG.getMergeValues(Ops, 2, dl);
11955}
11956
11957SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11958  EVT SrcVT = Op.getOperand(0).getValueType();
11959  EVT DstVT = Op.getValueType();
11960  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11961         Subtarget->hasMMX() && "Unexpected custom BITCAST");
11962  assert((DstVT == MVT::i64 ||
11963          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11964         "Unexpected custom BITCAST");
11965  // i64 <=> MMX conversions are Legal.
11966  if (SrcVT==MVT::i64 && DstVT.isVector())
11967    return Op;
11968  if (DstVT==MVT::i64 && SrcVT.isVector())
11969    return Op;
11970  // MMX <=> MMX conversions are Legal.
11971  if (SrcVT.isVector() && DstVT.isVector())
11972    return Op;
11973  // All other conversions need to be expanded.
11974  return SDValue();
11975}
11976
11977static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11978  SDNode *Node = Op.getNode();
11979  DebugLoc dl = Node->getDebugLoc();
11980  EVT T = Node->getValueType(0);
11981  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11982                              DAG.getConstant(0, T), Node->getOperand(2));
11983  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11984                       cast<AtomicSDNode>(Node)->getMemoryVT(),
11985                       Node->getOperand(0),
11986                       Node->getOperand(1), negOp,
11987                       cast<AtomicSDNode>(Node)->getSrcValue(),
11988                       cast<AtomicSDNode>(Node)->getAlignment(),
11989                       cast<AtomicSDNode>(Node)->getOrdering(),
11990                       cast<AtomicSDNode>(Node)->getSynchScope());
11991}
11992
11993static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11994  SDNode *Node = Op.getNode();
11995  DebugLoc dl = Node->getDebugLoc();
11996  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11997
11998  // Convert seq_cst store -> xchg
11999  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12000  // FIXME: On 32-bit, store -> fist or movq would be more efficient
12001  //        (The only way to get a 16-byte store is cmpxchg16b)
12002  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12003  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12004      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12005    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12006                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
12007                                 Node->getOperand(0),
12008                                 Node->getOperand(1), Node->getOperand(2),
12009                                 cast<AtomicSDNode>(Node)->getMemOperand(),
12010                                 cast<AtomicSDNode>(Node)->getOrdering(),
12011                                 cast<AtomicSDNode>(Node)->getSynchScope());
12012    return Swap.getValue(1);
12013  }
12014  // Other atomic stores have a simple pattern.
12015  return Op;
12016}
12017
12018static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12019  EVT VT = Op.getNode()->getValueType(0);
12020
12021  // Let legalize expand this if it isn't a legal type yet.
12022  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12023    return SDValue();
12024
12025  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12026
12027  unsigned Opc;
12028  bool ExtraOp = false;
12029  switch (Op.getOpcode()) {
12030  default: llvm_unreachable("Invalid code");
12031  case ISD::ADDC: Opc = X86ISD::ADD; break;
12032  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12033  case ISD::SUBC: Opc = X86ISD::SUB; break;
12034  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12035  }
12036
12037  if (!ExtraOp)
12038    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12039                       Op.getOperand(1));
12040  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12041                     Op.getOperand(1), Op.getOperand(2));
12042}
12043
12044SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12045  assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12046
12047  // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12048  // which returns the values in two XMM registers.
12049  DebugLoc dl = Op.getDebugLoc();
12050  SDValue Arg = Op.getOperand(0);
12051  EVT ArgVT = Arg.getValueType();
12052  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12053
12054  ArgListTy Args;
12055  ArgListEntry Entry;
12056
12057  Entry.Node = Arg;
12058  Entry.Ty = ArgTy;
12059  Entry.isSExt = false;
12060  Entry.isZExt = false;
12061  Args.push_back(Entry);
12062
12063  // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12064  // the small struct {f32, f32} is returned in (eax, edx). For f64,
12065  // the results are returned via SRet in memory.
12066  const char *LibcallName = (ArgVT == MVT::f64)
12067    ? "__sincos_stret" : "__sincosf_stret";
12068  SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12069
12070  StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12071  TargetLowering::
12072    CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12073                         false, false, false, false, 0,
12074                         CallingConv::C, /*isTaillCall=*/false,
12075                         /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12076                         Callee, Args, DAG, dl);
12077  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12078  return CallResult.first;
12079}
12080
12081/// LowerOperation - Provide custom lowering hooks for some operations.
12082///
12083SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12084  switch (Op.getOpcode()) {
12085  default: llvm_unreachable("Should not custom lower this!");
12086  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12087  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12088  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12089  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12090  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12091  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12092  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12093  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12094  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12095  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12096  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12097  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12098  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12099  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12100  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12101  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12102  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12103  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12104  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12105  case ISD::SHL_PARTS:
12106  case ISD::SRA_PARTS:
12107  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12108  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12109  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12110  case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12111  case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12112  case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12113  case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12114  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12115  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12116  case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12117  case ISD::FABS:               return LowerFABS(Op, DAG);
12118  case ISD::FNEG:               return LowerFNEG(Op, DAG);
12119  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12120  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12121  case ISD::SETCC:              return LowerSETCC(Op, DAG);
12122  case ISD::SELECT:             return LowerSELECT(Op, DAG);
12123  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12124  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12125  case ISD::VASTART:            return LowerVASTART(Op, DAG);
12126  case ISD::VAARG:              return LowerVAARG(Op, DAG);
12127  case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12128  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12129  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12130  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12131  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12132  case ISD::FRAME_TO_ARGS_OFFSET:
12133                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12134  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12135  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12136  case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12137  case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12138  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12139  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12140  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12141  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12142  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12143  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12144  case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12145  case ISD::SRA:
12146  case ISD::SRL:
12147  case ISD::SHL:                return LowerShift(Op, DAG);
12148  case ISD::SADDO:
12149  case ISD::UADDO:
12150  case ISD::SSUBO:
12151  case ISD::USUBO:
12152  case ISD::SMULO:
12153  case ISD::UMULO:              return LowerXALUO(Op, DAG);
12154  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12155  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12156  case ISD::ADDC:
12157  case ISD::ADDE:
12158  case ISD::SUBC:
12159  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12160  case ISD::ADD:                return LowerADD(Op, DAG);
12161  case ISD::SUB:                return LowerSUB(Op, DAG);
12162  case ISD::SDIV:               return LowerSDIV(Op, DAG);
12163  case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12164  }
12165}
12166
12167static void ReplaceATOMIC_LOAD(SDNode *Node,
12168                                  SmallVectorImpl<SDValue> &Results,
12169                                  SelectionDAG &DAG) {
12170  DebugLoc dl = Node->getDebugLoc();
12171  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12172
12173  // Convert wide load -> cmpxchg8b/cmpxchg16b
12174  // FIXME: On 32-bit, load -> fild or movq would be more efficient
12175  //        (The only way to get a 16-byte load is cmpxchg16b)
12176  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12177  SDValue Zero = DAG.getConstant(0, VT);
12178  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12179                               Node->getOperand(0),
12180                               Node->getOperand(1), Zero, Zero,
12181                               cast<AtomicSDNode>(Node)->getMemOperand(),
12182                               cast<AtomicSDNode>(Node)->getOrdering(),
12183                               cast<AtomicSDNode>(Node)->getSynchScope());
12184  Results.push_back(Swap.getValue(0));
12185  Results.push_back(Swap.getValue(1));
12186}
12187
12188static void
12189ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12190                        SelectionDAG &DAG, unsigned NewOp) {
12191  DebugLoc dl = Node->getDebugLoc();
12192  assert (Node->getValueType(0) == MVT::i64 &&
12193          "Only know how to expand i64 atomics");
12194
12195  SDValue Chain = Node->getOperand(0);
12196  SDValue In1 = Node->getOperand(1);
12197  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12198                             Node->getOperand(2), DAG.getIntPtrConstant(0));
12199  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12200                             Node->getOperand(2), DAG.getIntPtrConstant(1));
12201  SDValue Ops[] = { Chain, In1, In2L, In2H };
12202  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12203  SDValue Result =
12204    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12205                            cast<MemSDNode>(Node)->getMemOperand());
12206  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12207  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12208  Results.push_back(Result.getValue(2));
12209}
12210
12211/// ReplaceNodeResults - Replace a node with an illegal result type
12212/// with a new node built out of custom code.
12213void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12214                                           SmallVectorImpl<SDValue>&Results,
12215                                           SelectionDAG &DAG) const {
12216  DebugLoc dl = N->getDebugLoc();
12217  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12218  switch (N->getOpcode()) {
12219  default:
12220    llvm_unreachable("Do not know how to custom type legalize this operation!");
12221  case ISD::SIGN_EXTEND_INREG:
12222  case ISD::ADDC:
12223  case ISD::ADDE:
12224  case ISD::SUBC:
12225  case ISD::SUBE:
12226    // We don't want to expand or promote these.
12227    return;
12228  case ISD::FP_TO_SINT:
12229  case ISD::FP_TO_UINT: {
12230    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12231
12232    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12233      return;
12234
12235    std::pair<SDValue,SDValue> Vals =
12236        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12237    SDValue FIST = Vals.first, StackSlot = Vals.second;
12238    if (FIST.getNode() != 0) {
12239      EVT VT = N->getValueType(0);
12240      // Return a load from the stack slot.
12241      if (StackSlot.getNode() != 0)
12242        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12243                                      MachinePointerInfo(),
12244                                      false, false, false, 0));
12245      else
12246        Results.push_back(FIST);
12247    }
12248    return;
12249  }
12250  case ISD::UINT_TO_FP: {
12251    if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12252        N->getValueType(0) != MVT::v2f32)
12253      return;
12254    SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12255                                 N->getOperand(0));
12256    SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12257                                     MVT::f64);
12258    SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12259    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12260                             DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12261    Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12262    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12263    Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12264    return;
12265  }
12266  case ISD::FP_ROUND: {
12267    if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12268        return;
12269    SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12270    Results.push_back(V);
12271    return;
12272  }
12273  case ISD::READCYCLECOUNTER: {
12274    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12275    SDValue TheChain = N->getOperand(0);
12276    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12277    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12278                                     rd.getValue(1));
12279    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12280                                     eax.getValue(2));
12281    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12282    SDValue Ops[] = { eax, edx };
12283    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12284    Results.push_back(edx.getValue(1));
12285    return;
12286  }
12287  case ISD::ATOMIC_CMP_SWAP: {
12288    EVT T = N->getValueType(0);
12289    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12290    bool Regs64bit = T == MVT::i128;
12291    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12292    SDValue cpInL, cpInH;
12293    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12294                        DAG.getConstant(0, HalfT));
12295    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12296                        DAG.getConstant(1, HalfT));
12297    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12298                             Regs64bit ? X86::RAX : X86::EAX,
12299                             cpInL, SDValue());
12300    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12301                             Regs64bit ? X86::RDX : X86::EDX,
12302                             cpInH, cpInL.getValue(1));
12303    SDValue swapInL, swapInH;
12304    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12305                          DAG.getConstant(0, HalfT));
12306    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12307                          DAG.getConstant(1, HalfT));
12308    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12309                               Regs64bit ? X86::RBX : X86::EBX,
12310                               swapInL, cpInH.getValue(1));
12311    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12312                               Regs64bit ? X86::RCX : X86::ECX,
12313                               swapInH, swapInL.getValue(1));
12314    SDValue Ops[] = { swapInH.getValue(0),
12315                      N->getOperand(1),
12316                      swapInH.getValue(1) };
12317    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12318    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12319    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12320                                  X86ISD::LCMPXCHG8_DAG;
12321    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12322                                             Ops, 3, T, MMO);
12323    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12324                                        Regs64bit ? X86::RAX : X86::EAX,
12325                                        HalfT, Result.getValue(1));
12326    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12327                                        Regs64bit ? X86::RDX : X86::EDX,
12328                                        HalfT, cpOutL.getValue(2));
12329    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12330    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12331    Results.push_back(cpOutH.getValue(1));
12332    return;
12333  }
12334  case ISD::ATOMIC_LOAD_ADD:
12335  case ISD::ATOMIC_LOAD_AND:
12336  case ISD::ATOMIC_LOAD_NAND:
12337  case ISD::ATOMIC_LOAD_OR:
12338  case ISD::ATOMIC_LOAD_SUB:
12339  case ISD::ATOMIC_LOAD_XOR:
12340  case ISD::ATOMIC_LOAD_MAX:
12341  case ISD::ATOMIC_LOAD_MIN:
12342  case ISD::ATOMIC_LOAD_UMAX:
12343  case ISD::ATOMIC_LOAD_UMIN:
12344  case ISD::ATOMIC_SWAP: {
12345    unsigned Opc;
12346    switch (N->getOpcode()) {
12347    default: llvm_unreachable("Unexpected opcode");
12348    case ISD::ATOMIC_LOAD_ADD:
12349      Opc = X86ISD::ATOMADD64_DAG;
12350      break;
12351    case ISD::ATOMIC_LOAD_AND:
12352      Opc = X86ISD::ATOMAND64_DAG;
12353      break;
12354    case ISD::ATOMIC_LOAD_NAND:
12355      Opc = X86ISD::ATOMNAND64_DAG;
12356      break;
12357    case ISD::ATOMIC_LOAD_OR:
12358      Opc = X86ISD::ATOMOR64_DAG;
12359      break;
12360    case ISD::ATOMIC_LOAD_SUB:
12361      Opc = X86ISD::ATOMSUB64_DAG;
12362      break;
12363    case ISD::ATOMIC_LOAD_XOR:
12364      Opc = X86ISD::ATOMXOR64_DAG;
12365      break;
12366    case ISD::ATOMIC_LOAD_MAX:
12367      Opc = X86ISD::ATOMMAX64_DAG;
12368      break;
12369    case ISD::ATOMIC_LOAD_MIN:
12370      Opc = X86ISD::ATOMMIN64_DAG;
12371      break;
12372    case ISD::ATOMIC_LOAD_UMAX:
12373      Opc = X86ISD::ATOMUMAX64_DAG;
12374      break;
12375    case ISD::ATOMIC_LOAD_UMIN:
12376      Opc = X86ISD::ATOMUMIN64_DAG;
12377      break;
12378    case ISD::ATOMIC_SWAP:
12379      Opc = X86ISD::ATOMSWAP64_DAG;
12380      break;
12381    }
12382    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12383    return;
12384  }
12385  case ISD::ATOMIC_LOAD:
12386    ReplaceATOMIC_LOAD(N, Results, DAG);
12387  }
12388}
12389
12390const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12391  switch (Opcode) {
12392  default: return NULL;
12393  case X86ISD::BSF:                return "X86ISD::BSF";
12394  case X86ISD::BSR:                return "X86ISD::BSR";
12395  case X86ISD::SHLD:               return "X86ISD::SHLD";
12396  case X86ISD::SHRD:               return "X86ISD::SHRD";
12397  case X86ISD::FAND:               return "X86ISD::FAND";
12398  case X86ISD::FOR:                return "X86ISD::FOR";
12399  case X86ISD::FXOR:               return "X86ISD::FXOR";
12400  case X86ISD::FSRL:               return "X86ISD::FSRL";
12401  case X86ISD::FILD:               return "X86ISD::FILD";
12402  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12403  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12404  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12405  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12406  case X86ISD::FLD:                return "X86ISD::FLD";
12407  case X86ISD::FST:                return "X86ISD::FST";
12408  case X86ISD::CALL:               return "X86ISD::CALL";
12409  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12410  case X86ISD::BT:                 return "X86ISD::BT";
12411  case X86ISD::CMP:                return "X86ISD::CMP";
12412  case X86ISD::COMI:               return "X86ISD::COMI";
12413  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12414  case X86ISD::SETCC:              return "X86ISD::SETCC";
12415  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12416  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12417  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12418  case X86ISD::CMOV:               return "X86ISD::CMOV";
12419  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12420  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12421  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12422  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12423  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12424  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12425  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12426  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12427  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12428  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12429  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12430  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12431  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12432  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12433  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12434  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12435  case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12436  case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12437  case X86ISD::HADD:               return "X86ISD::HADD";
12438  case X86ISD::HSUB:               return "X86ISD::HSUB";
12439  case X86ISD::FHADD:              return "X86ISD::FHADD";
12440  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12441  case X86ISD::UMAX:               return "X86ISD::UMAX";
12442  case X86ISD::UMIN:               return "X86ISD::UMIN";
12443  case X86ISD::SMAX:               return "X86ISD::SMAX";
12444  case X86ISD::SMIN:               return "X86ISD::SMIN";
12445  case X86ISD::FMAX:               return "X86ISD::FMAX";
12446  case X86ISD::FMIN:               return "X86ISD::FMIN";
12447  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12448  case X86ISD::FMINC:              return "X86ISD::FMINC";
12449  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12450  case X86ISD::FRCP:               return "X86ISD::FRCP";
12451  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12452  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12453  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12454  case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12455  case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12456  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12457  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12458  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12459  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12460  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12461  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12462  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12463  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12464  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12465  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12466  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12467  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12468  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12469  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12470  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12471  case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12472  case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12473  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12474  case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12475  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12476  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12477  case X86ISD::VSHL:               return "X86ISD::VSHL";
12478  case X86ISD::VSRL:               return "X86ISD::VSRL";
12479  case X86ISD::VSRA:               return "X86ISD::VSRA";
12480  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12481  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12482  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12483  case X86ISD::CMPP:               return "X86ISD::CMPP";
12484  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12485  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12486  case X86ISD::ADD:                return "X86ISD::ADD";
12487  case X86ISD::SUB:                return "X86ISD::SUB";
12488  case X86ISD::ADC:                return "X86ISD::ADC";
12489  case X86ISD::SBB:                return "X86ISD::SBB";
12490  case X86ISD::SMUL:               return "X86ISD::SMUL";
12491  case X86ISD::UMUL:               return "X86ISD::UMUL";
12492  case X86ISD::INC:                return "X86ISD::INC";
12493  case X86ISD::DEC:                return "X86ISD::DEC";
12494  case X86ISD::OR:                 return "X86ISD::OR";
12495  case X86ISD::XOR:                return "X86ISD::XOR";
12496  case X86ISD::AND:                return "X86ISD::AND";
12497  case X86ISD::BLSI:               return "X86ISD::BLSI";
12498  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12499  case X86ISD::BLSR:               return "X86ISD::BLSR";
12500  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12501  case X86ISD::PTEST:              return "X86ISD::PTEST";
12502  case X86ISD::TESTP:              return "X86ISD::TESTP";
12503  case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12504  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12505  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12506  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12507  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12508  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12509  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12510  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12511  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12512  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12513  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12514  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12515  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12516  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12517  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12518  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12519  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12520  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12521  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12522  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12523  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12524  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12525  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12526  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12527  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12528  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12529  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12530  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12531  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12532  case X86ISD::SAHF:               return "X86ISD::SAHF";
12533  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12534  case X86ISD::FMADD:              return "X86ISD::FMADD";
12535  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12536  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12537  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12538  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12539  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12540  case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12541  case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12542  }
12543}
12544
12545// isLegalAddressingMode - Return true if the addressing mode represented
12546// by AM is legal for this target, for a load/store of the specified type.
12547bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12548                                              Type *Ty) const {
12549  // X86 supports extremely general addressing modes.
12550  CodeModel::Model M = getTargetMachine().getCodeModel();
12551  Reloc::Model R = getTargetMachine().getRelocationModel();
12552
12553  // X86 allows a sign-extended 32-bit immediate field as a displacement.
12554  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12555    return false;
12556
12557  if (AM.BaseGV) {
12558    unsigned GVFlags =
12559      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12560
12561    // If a reference to this global requires an extra load, we can't fold it.
12562    if (isGlobalStubReference(GVFlags))
12563      return false;
12564
12565    // If BaseGV requires a register for the PIC base, we cannot also have a
12566    // BaseReg specified.
12567    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12568      return false;
12569
12570    // If lower 4G is not available, then we must use rip-relative addressing.
12571    if ((M != CodeModel::Small || R != Reloc::Static) &&
12572        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12573      return false;
12574  }
12575
12576  switch (AM.Scale) {
12577  case 0:
12578  case 1:
12579  case 2:
12580  case 4:
12581  case 8:
12582    // These scales always work.
12583    break;
12584  case 3:
12585  case 5:
12586  case 9:
12587    // These scales are formed with basereg+scalereg.  Only accept if there is
12588    // no basereg yet.
12589    if (AM.HasBaseReg)
12590      return false;
12591    break;
12592  default:  // Other stuff never works.
12593    return false;
12594  }
12595
12596  return true;
12597}
12598
12599bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12600  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12601    return false;
12602  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12603  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12604  return NumBits1 > NumBits2;
12605}
12606
12607bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12608  return isInt<32>(Imm);
12609}
12610
12611bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12612  // Can also use sub to handle negated immediates.
12613  return isInt<32>(Imm);
12614}
12615
12616bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12617  if (!VT1.isInteger() || !VT2.isInteger())
12618    return false;
12619  unsigned NumBits1 = VT1.getSizeInBits();
12620  unsigned NumBits2 = VT2.getSizeInBits();
12621  return NumBits1 > NumBits2;
12622}
12623
12624bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12625  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12626  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12627}
12628
12629bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12630  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12631  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12632}
12633
12634bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12635  EVT VT1 = Val.getValueType();
12636  if (isZExtFree(VT1, VT2))
12637    return true;
12638
12639  if (Val.getOpcode() != ISD::LOAD)
12640    return false;
12641
12642  if (!VT1.isSimple() || !VT1.isInteger() ||
12643      !VT2.isSimple() || !VT2.isInteger())
12644    return false;
12645
12646  switch (VT1.getSimpleVT().SimpleTy) {
12647  default: break;
12648  case MVT::i8:
12649  case MVT::i16:
12650  case MVT::i32:
12651    // X86 has 8, 16, and 32-bit zero-extending loads.
12652    return true;
12653  }
12654
12655  return false;
12656}
12657
12658bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12659  // i16 instructions are longer (0x66 prefix) and potentially slower.
12660  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12661}
12662
12663/// isShuffleMaskLegal - Targets can use this to indicate that they only
12664/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12665/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12666/// are assumed to be legal.
12667bool
12668X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12669                                      EVT VT) const {
12670  // Very little shuffling can be done for 64-bit vectors right now.
12671  if (VT.getSizeInBits() == 64)
12672    return false;
12673
12674  // FIXME: pshufb, blends, shifts.
12675  return (VT.getVectorNumElements() == 2 ||
12676          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12677          isMOVLMask(M, VT) ||
12678          isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12679          isPSHUFDMask(M, VT) ||
12680          isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12681          isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12682          isPALIGNRMask(M, VT, Subtarget) ||
12683          isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12684          isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12685          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12686          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12687}
12688
12689bool
12690X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12691                                          EVT VT) const {
12692  unsigned NumElts = VT.getVectorNumElements();
12693  // FIXME: This collection of masks seems suspect.
12694  if (NumElts == 2)
12695    return true;
12696  if (NumElts == 4 && VT.is128BitVector()) {
12697    return (isMOVLMask(Mask, VT)  ||
12698            isCommutedMOVLMask(Mask, VT, true) ||
12699            isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12700            isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12701  }
12702  return false;
12703}
12704
12705//===----------------------------------------------------------------------===//
12706//                           X86 Scheduler Hooks
12707//===----------------------------------------------------------------------===//
12708
12709/// Utility function to emit xbegin specifying the start of an RTM region.
12710static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12711                                     const TargetInstrInfo *TII) {
12712  DebugLoc DL = MI->getDebugLoc();
12713
12714  const BasicBlock *BB = MBB->getBasicBlock();
12715  MachineFunction::iterator I = MBB;
12716  ++I;
12717
12718  // For the v = xbegin(), we generate
12719  //
12720  // thisMBB:
12721  //  xbegin sinkMBB
12722  //
12723  // mainMBB:
12724  //  eax = -1
12725  //
12726  // sinkMBB:
12727  //  v = eax
12728
12729  MachineBasicBlock *thisMBB = MBB;
12730  MachineFunction *MF = MBB->getParent();
12731  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12732  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12733  MF->insert(I, mainMBB);
12734  MF->insert(I, sinkMBB);
12735
12736  // Transfer the remainder of BB and its successor edges to sinkMBB.
12737  sinkMBB->splice(sinkMBB->begin(), MBB,
12738                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12739  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12740
12741  // thisMBB:
12742  //  xbegin sinkMBB
12743  //  # fallthrough to mainMBB
12744  //  # abortion to sinkMBB
12745  BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12746  thisMBB->addSuccessor(mainMBB);
12747  thisMBB->addSuccessor(sinkMBB);
12748
12749  // mainMBB:
12750  //  EAX = -1
12751  BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12752  mainMBB->addSuccessor(sinkMBB);
12753
12754  // sinkMBB:
12755  // EAX is live into the sinkMBB
12756  sinkMBB->addLiveIn(X86::EAX);
12757  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12758          TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12759    .addReg(X86::EAX);
12760
12761  MI->eraseFromParent();
12762  return sinkMBB;
12763}
12764
12765// Get CMPXCHG opcode for the specified data type.
12766static unsigned getCmpXChgOpcode(EVT VT) {
12767  switch (VT.getSimpleVT().SimpleTy) {
12768  case MVT::i8:  return X86::LCMPXCHG8;
12769  case MVT::i16: return X86::LCMPXCHG16;
12770  case MVT::i32: return X86::LCMPXCHG32;
12771  case MVT::i64: return X86::LCMPXCHG64;
12772  default:
12773    break;
12774  }
12775  llvm_unreachable("Invalid operand size!");
12776}
12777
12778// Get LOAD opcode for the specified data type.
12779static unsigned getLoadOpcode(EVT VT) {
12780  switch (VT.getSimpleVT().SimpleTy) {
12781  case MVT::i8:  return X86::MOV8rm;
12782  case MVT::i16: return X86::MOV16rm;
12783  case MVT::i32: return X86::MOV32rm;
12784  case MVT::i64: return X86::MOV64rm;
12785  default:
12786    break;
12787  }
12788  llvm_unreachable("Invalid operand size!");
12789}
12790
12791// Get opcode of the non-atomic one from the specified atomic instruction.
12792static unsigned getNonAtomicOpcode(unsigned Opc) {
12793  switch (Opc) {
12794  case X86::ATOMAND8:  return X86::AND8rr;
12795  case X86::ATOMAND16: return X86::AND16rr;
12796  case X86::ATOMAND32: return X86::AND32rr;
12797  case X86::ATOMAND64: return X86::AND64rr;
12798  case X86::ATOMOR8:   return X86::OR8rr;
12799  case X86::ATOMOR16:  return X86::OR16rr;
12800  case X86::ATOMOR32:  return X86::OR32rr;
12801  case X86::ATOMOR64:  return X86::OR64rr;
12802  case X86::ATOMXOR8:  return X86::XOR8rr;
12803  case X86::ATOMXOR16: return X86::XOR16rr;
12804  case X86::ATOMXOR32: return X86::XOR32rr;
12805  case X86::ATOMXOR64: return X86::XOR64rr;
12806  }
12807  llvm_unreachable("Unhandled atomic-load-op opcode!");
12808}
12809
12810// Get opcode of the non-atomic one from the specified atomic instruction with
12811// extra opcode.
12812static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12813                                               unsigned &ExtraOpc) {
12814  switch (Opc) {
12815  case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12816  case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12817  case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12818  case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12819  case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12820  case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12821  case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12822  case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12823  case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12824  case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12825  case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12826  case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12827  case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12828  case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12829  case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12830  case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12831  case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12832  case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12833  case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12834  case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12835  }
12836  llvm_unreachable("Unhandled atomic-load-op opcode!");
12837}
12838
12839// Get opcode of the non-atomic one from the specified atomic instruction for
12840// 64-bit data type on 32-bit target.
12841static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12842  switch (Opc) {
12843  case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12844  case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12845  case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12846  case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12847  case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12848  case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12849  case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12850  case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12851  case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12852  case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12853  }
12854  llvm_unreachable("Unhandled atomic-load-op opcode!");
12855}
12856
12857// Get opcode of the non-atomic one from the specified atomic instruction for
12858// 64-bit data type on 32-bit target with extra opcode.
12859static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12860                                                   unsigned &HiOpc,
12861                                                   unsigned &ExtraOpc) {
12862  switch (Opc) {
12863  case X86::ATOMNAND6432:
12864    ExtraOpc = X86::NOT32r;
12865    HiOpc = X86::AND32rr;
12866    return X86::AND32rr;
12867  }
12868  llvm_unreachable("Unhandled atomic-load-op opcode!");
12869}
12870
12871// Get pseudo CMOV opcode from the specified data type.
12872static unsigned getPseudoCMOVOpc(EVT VT) {
12873  switch (VT.getSimpleVT().SimpleTy) {
12874  case MVT::i8:  return X86::CMOV_GR8;
12875  case MVT::i16: return X86::CMOV_GR16;
12876  case MVT::i32: return X86::CMOV_GR32;
12877  default:
12878    break;
12879  }
12880  llvm_unreachable("Unknown CMOV opcode!");
12881}
12882
12883// EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12884// They will be translated into a spin-loop or compare-exchange loop from
12885//
12886//    ...
12887//    dst = atomic-fetch-op MI.addr, MI.val
12888//    ...
12889//
12890// to
12891//
12892//    ...
12893//    EAX = LOAD MI.addr
12894// loop:
12895//    t1 = OP MI.val, EAX
12896//    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12897//    JNE loop
12898// sink:
12899//    dst = EAX
12900//    ...
12901MachineBasicBlock *
12902X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12903                                       MachineBasicBlock *MBB) const {
12904  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12905  DebugLoc DL = MI->getDebugLoc();
12906
12907  MachineFunction *MF = MBB->getParent();
12908  MachineRegisterInfo &MRI = MF->getRegInfo();
12909
12910  const BasicBlock *BB = MBB->getBasicBlock();
12911  MachineFunction::iterator I = MBB;
12912  ++I;
12913
12914  assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12915         "Unexpected number of operands");
12916
12917  assert(MI->hasOneMemOperand() &&
12918         "Expected atomic-load-op to have one memoperand");
12919
12920  // Memory Reference
12921  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12922  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12923
12924  unsigned DstReg, SrcReg;
12925  unsigned MemOpndSlot;
12926
12927  unsigned CurOp = 0;
12928
12929  DstReg = MI->getOperand(CurOp++).getReg();
12930  MemOpndSlot = CurOp;
12931  CurOp += X86::AddrNumOperands;
12932  SrcReg = MI->getOperand(CurOp++).getReg();
12933
12934  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12935  MVT::SimpleValueType VT = *RC->vt_begin();
12936  unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12937
12938  unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12939  unsigned LOADOpc = getLoadOpcode(VT);
12940
12941  // For the atomic load-arith operator, we generate
12942  //
12943  //  thisMBB:
12944  //    EAX = LOAD [MI.addr]
12945  //  mainMBB:
12946  //    t1 = OP MI.val, EAX
12947  //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12948  //    JNE mainMBB
12949  //  sinkMBB:
12950
12951  MachineBasicBlock *thisMBB = MBB;
12952  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12953  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12954  MF->insert(I, mainMBB);
12955  MF->insert(I, sinkMBB);
12956
12957  MachineInstrBuilder MIB;
12958
12959  // Transfer the remainder of BB and its successor edges to sinkMBB.
12960  sinkMBB->splice(sinkMBB->begin(), MBB,
12961                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12962  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12963
12964  // thisMBB:
12965  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12966  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12967    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12968  MIB.setMemRefs(MMOBegin, MMOEnd);
12969
12970  thisMBB->addSuccessor(mainMBB);
12971
12972  // mainMBB:
12973  MachineBasicBlock *origMainMBB = mainMBB;
12974  mainMBB->addLiveIn(AccPhyReg);
12975
12976  // Copy AccPhyReg as it is used more than once.
12977  unsigned AccReg = MRI.createVirtualRegister(RC);
12978  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12979    .addReg(AccPhyReg);
12980
12981  unsigned t1 = MRI.createVirtualRegister(RC);
12982  unsigned Opc = MI->getOpcode();
12983  switch (Opc) {
12984  default:
12985    llvm_unreachable("Unhandled atomic-load-op opcode!");
12986  case X86::ATOMAND8:
12987  case X86::ATOMAND16:
12988  case X86::ATOMAND32:
12989  case X86::ATOMAND64:
12990  case X86::ATOMOR8:
12991  case X86::ATOMOR16:
12992  case X86::ATOMOR32:
12993  case X86::ATOMOR64:
12994  case X86::ATOMXOR8:
12995  case X86::ATOMXOR16:
12996  case X86::ATOMXOR32:
12997  case X86::ATOMXOR64: {
12998    unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12999    BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
13000      .addReg(AccReg);
13001    break;
13002  }
13003  case X86::ATOMNAND8:
13004  case X86::ATOMNAND16:
13005  case X86::ATOMNAND32:
13006  case X86::ATOMNAND64: {
13007    unsigned t2 = MRI.createVirtualRegister(RC);
13008    unsigned NOTOpc;
13009    unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13010    BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
13011      .addReg(AccReg);
13012    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
13013    break;
13014  }
13015  case X86::ATOMMAX8:
13016  case X86::ATOMMAX16:
13017  case X86::ATOMMAX32:
13018  case X86::ATOMMAX64:
13019  case X86::ATOMMIN8:
13020  case X86::ATOMMIN16:
13021  case X86::ATOMMIN32:
13022  case X86::ATOMMIN64:
13023  case X86::ATOMUMAX8:
13024  case X86::ATOMUMAX16:
13025  case X86::ATOMUMAX32:
13026  case X86::ATOMUMAX64:
13027  case X86::ATOMUMIN8:
13028  case X86::ATOMUMIN16:
13029  case X86::ATOMUMIN32:
13030  case X86::ATOMUMIN64: {
13031    unsigned CMPOpc;
13032    unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13033
13034    BuildMI(mainMBB, DL, TII->get(CMPOpc))
13035      .addReg(SrcReg)
13036      .addReg(AccReg);
13037
13038    if (Subtarget->hasCMov()) {
13039      if (VT != MVT::i8) {
13040        // Native support
13041        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
13042          .addReg(SrcReg)
13043          .addReg(AccReg);
13044      } else {
13045        // Promote i8 to i32 to use CMOV32
13046        const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
13047        unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13048        unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13049        unsigned t2 = MRI.createVirtualRegister(RC32);
13050
13051        unsigned Undef = MRI.createVirtualRegister(RC32);
13052        BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13053
13054        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13055          .addReg(Undef)
13056          .addReg(SrcReg)
13057          .addImm(X86::sub_8bit);
13058        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13059          .addReg(Undef)
13060          .addReg(AccReg)
13061          .addImm(X86::sub_8bit);
13062
13063        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13064          .addReg(SrcReg32)
13065          .addReg(AccReg32);
13066
13067        BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
13068          .addReg(t2, 0, X86::sub_8bit);
13069      }
13070    } else {
13071      // Use pseudo select and lower them.
13072      assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13073             "Invalid atomic-load-op transformation!");
13074      unsigned SelOpc = getPseudoCMOVOpc(VT);
13075      X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13076      assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13077      MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13078              .addReg(SrcReg).addReg(AccReg)
13079              .addImm(CC);
13080      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13081    }
13082    break;
13083  }
13084  }
13085
13086  // Copy AccPhyReg back from virtual register.
13087  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13088    .addReg(AccReg);
13089
13090  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13091  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13092    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13093  MIB.addReg(t1);
13094  MIB.setMemRefs(MMOBegin, MMOEnd);
13095
13096  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13097
13098  mainMBB->addSuccessor(origMainMBB);
13099  mainMBB->addSuccessor(sinkMBB);
13100
13101  // sinkMBB:
13102  sinkMBB->addLiveIn(AccPhyReg);
13103
13104  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13105          TII->get(TargetOpcode::COPY), DstReg)
13106    .addReg(AccPhyReg);
13107
13108  MI->eraseFromParent();
13109  return sinkMBB;
13110}
13111
13112// EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13113// instructions. They will be translated into a spin-loop or compare-exchange
13114// loop from
13115//
13116//    ...
13117//    dst = atomic-fetch-op MI.addr, MI.val
13118//    ...
13119//
13120// to
13121//
13122//    ...
13123//    EAX = LOAD [MI.addr + 0]
13124//    EDX = LOAD [MI.addr + 4]
13125// loop:
13126//    EBX = OP MI.val.lo, EAX
13127//    ECX = OP MI.val.hi, EDX
13128//    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13129//    JNE loop
13130// sink:
13131//    dst = EDX:EAX
13132//    ...
13133MachineBasicBlock *
13134X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13135                                           MachineBasicBlock *MBB) const {
13136  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13137  DebugLoc DL = MI->getDebugLoc();
13138
13139  MachineFunction *MF = MBB->getParent();
13140  MachineRegisterInfo &MRI = MF->getRegInfo();
13141
13142  const BasicBlock *BB = MBB->getBasicBlock();
13143  MachineFunction::iterator I = MBB;
13144  ++I;
13145
13146  assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13147         "Unexpected number of operands");
13148
13149  assert(MI->hasOneMemOperand() &&
13150         "Expected atomic-load-op32 to have one memoperand");
13151
13152  // Memory Reference
13153  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13154  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13155
13156  unsigned DstLoReg, DstHiReg;
13157  unsigned SrcLoReg, SrcHiReg;
13158  unsigned MemOpndSlot;
13159
13160  unsigned CurOp = 0;
13161
13162  DstLoReg = MI->getOperand(CurOp++).getReg();
13163  DstHiReg = MI->getOperand(CurOp++).getReg();
13164  MemOpndSlot = CurOp;
13165  CurOp += X86::AddrNumOperands;
13166  SrcLoReg = MI->getOperand(CurOp++).getReg();
13167  SrcHiReg = MI->getOperand(CurOp++).getReg();
13168
13169  const TargetRegisterClass *RC = &X86::GR32RegClass;
13170  const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13171
13172  unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13173  unsigned LOADOpc = X86::MOV32rm;
13174
13175  // For the atomic load-arith operator, we generate
13176  //
13177  //  thisMBB:
13178  //    EAX = LOAD [MI.addr + 0]
13179  //    EDX = LOAD [MI.addr + 4]
13180  //  mainMBB:
13181  //    EBX = OP MI.vallo, EAX
13182  //    ECX = OP MI.valhi, EDX
13183  //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13184  //    JNE mainMBB
13185  //  sinkMBB:
13186
13187  MachineBasicBlock *thisMBB = MBB;
13188  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13189  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13190  MF->insert(I, mainMBB);
13191  MF->insert(I, sinkMBB);
13192
13193  MachineInstrBuilder MIB;
13194
13195  // Transfer the remainder of BB and its successor edges to sinkMBB.
13196  sinkMBB->splice(sinkMBB->begin(), MBB,
13197                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13198  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13199
13200  // thisMBB:
13201  // Lo
13202  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13203  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13204    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13205  MIB.setMemRefs(MMOBegin, MMOEnd);
13206  // Hi
13207  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13208  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13209    if (i == X86::AddrDisp)
13210      MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13211    else
13212      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13213  }
13214  MIB.setMemRefs(MMOBegin, MMOEnd);
13215
13216  thisMBB->addSuccessor(mainMBB);
13217
13218  // mainMBB:
13219  MachineBasicBlock *origMainMBB = mainMBB;
13220  mainMBB->addLiveIn(X86::EAX);
13221  mainMBB->addLiveIn(X86::EDX);
13222
13223  // Copy EDX:EAX as they are used more than once.
13224  unsigned LoReg = MRI.createVirtualRegister(RC);
13225  unsigned HiReg = MRI.createVirtualRegister(RC);
13226  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13227  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13228
13229  unsigned t1L = MRI.createVirtualRegister(RC);
13230  unsigned t1H = MRI.createVirtualRegister(RC);
13231
13232  unsigned Opc = MI->getOpcode();
13233  switch (Opc) {
13234  default:
13235    llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13236  case X86::ATOMAND6432:
13237  case X86::ATOMOR6432:
13238  case X86::ATOMXOR6432:
13239  case X86::ATOMADD6432:
13240  case X86::ATOMSUB6432: {
13241    unsigned HiOpc;
13242    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13243    BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13244    BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13245    break;
13246  }
13247  case X86::ATOMNAND6432: {
13248    unsigned HiOpc, NOTOpc;
13249    unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13250    unsigned t2L = MRI.createVirtualRegister(RC);
13251    unsigned t2H = MRI.createVirtualRegister(RC);
13252    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13253    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13254    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13255    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13256    break;
13257  }
13258  case X86::ATOMMAX6432:
13259  case X86::ATOMMIN6432:
13260  case X86::ATOMUMAX6432:
13261  case X86::ATOMUMIN6432: {
13262    unsigned HiOpc;
13263    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13264    unsigned cL = MRI.createVirtualRegister(RC8);
13265    unsigned cH = MRI.createVirtualRegister(RC8);
13266    unsigned cL32 = MRI.createVirtualRegister(RC);
13267    unsigned cH32 = MRI.createVirtualRegister(RC);
13268    unsigned cc = MRI.createVirtualRegister(RC);
13269    // cl := cmp src_lo, lo
13270    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13271      .addReg(SrcLoReg).addReg(LoReg);
13272    BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13273    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13274    // ch := cmp src_hi, hi
13275    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13276      .addReg(SrcHiReg).addReg(HiReg);
13277    BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13278    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13279    // cc := if (src_hi == hi) ? cl : ch;
13280    if (Subtarget->hasCMov()) {
13281      BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13282        .addReg(cH32).addReg(cL32);
13283    } else {
13284      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13285              .addReg(cH32).addReg(cL32)
13286              .addImm(X86::COND_E);
13287      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13288    }
13289    BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13290    if (Subtarget->hasCMov()) {
13291      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13292        .addReg(SrcLoReg).addReg(LoReg);
13293      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13294        .addReg(SrcHiReg).addReg(HiReg);
13295    } else {
13296      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13297              .addReg(SrcLoReg).addReg(LoReg)
13298              .addImm(X86::COND_NE);
13299      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13300      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13301              .addReg(SrcHiReg).addReg(HiReg)
13302              .addImm(X86::COND_NE);
13303      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13304    }
13305    break;
13306  }
13307  case X86::ATOMSWAP6432: {
13308    unsigned HiOpc;
13309    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13310    BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13311    BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13312    break;
13313  }
13314  }
13315
13316  // Copy EDX:EAX back from HiReg:LoReg
13317  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13318  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13319  // Copy ECX:EBX from t1H:t1L
13320  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13321  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13322
13323  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13324  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13325    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13326  MIB.setMemRefs(MMOBegin, MMOEnd);
13327
13328  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13329
13330  mainMBB->addSuccessor(origMainMBB);
13331  mainMBB->addSuccessor(sinkMBB);
13332
13333  // sinkMBB:
13334  sinkMBB->addLiveIn(X86::EAX);
13335  sinkMBB->addLiveIn(X86::EDX);
13336
13337  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13338          TII->get(TargetOpcode::COPY), DstLoReg)
13339    .addReg(X86::EAX);
13340  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13341          TII->get(TargetOpcode::COPY), DstHiReg)
13342    .addReg(X86::EDX);
13343
13344  MI->eraseFromParent();
13345  return sinkMBB;
13346}
13347
13348// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13349// or XMM0_V32I8 in AVX all of this code can be replaced with that
13350// in the .td file.
13351static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13352                                       const TargetInstrInfo *TII) {
13353  unsigned Opc;
13354  switch (MI->getOpcode()) {
13355  default: llvm_unreachable("illegal opcode!");
13356  case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13357  case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13358  case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13359  case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13360  case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13361  case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13362  case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13363  case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13364  }
13365
13366  DebugLoc dl = MI->getDebugLoc();
13367  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13368
13369  unsigned NumArgs = MI->getNumOperands();
13370  for (unsigned i = 1; i < NumArgs; ++i) {
13371    MachineOperand &Op = MI->getOperand(i);
13372    if (!(Op.isReg() && Op.isImplicit()))
13373      MIB.addOperand(Op);
13374  }
13375  if (MI->hasOneMemOperand())
13376    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13377
13378  BuildMI(*BB, MI, dl,
13379    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13380    .addReg(X86::XMM0);
13381
13382  MI->eraseFromParent();
13383  return BB;
13384}
13385
13386// FIXME: Custom handling because TableGen doesn't support multiple implicit
13387// defs in an instruction pattern
13388static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13389                                       const TargetInstrInfo *TII) {
13390  unsigned Opc;
13391  switch (MI->getOpcode()) {
13392  default: llvm_unreachable("illegal opcode!");
13393  case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13394  case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13395  case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13396  case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13397  case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13398  case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13399  case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13400  case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13401  }
13402
13403  DebugLoc dl = MI->getDebugLoc();
13404  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13405
13406  unsigned NumArgs = MI->getNumOperands(); // remove the results
13407  for (unsigned i = 1; i < NumArgs; ++i) {
13408    MachineOperand &Op = MI->getOperand(i);
13409    if (!(Op.isReg() && Op.isImplicit()))
13410      MIB.addOperand(Op);
13411  }
13412  if (MI->hasOneMemOperand())
13413    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13414
13415  BuildMI(*BB, MI, dl,
13416    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13417    .addReg(X86::ECX);
13418
13419  MI->eraseFromParent();
13420  return BB;
13421}
13422
13423static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13424                                       const TargetInstrInfo *TII,
13425                                       const X86Subtarget* Subtarget) {
13426  DebugLoc dl = MI->getDebugLoc();
13427
13428  // Address into RAX/EAX, other two args into ECX, EDX.
13429  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13430  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13431  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13432  for (int i = 0; i < X86::AddrNumOperands; ++i)
13433    MIB.addOperand(MI->getOperand(i));
13434
13435  unsigned ValOps = X86::AddrNumOperands;
13436  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13437    .addReg(MI->getOperand(ValOps).getReg());
13438  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13439    .addReg(MI->getOperand(ValOps+1).getReg());
13440
13441  // The instruction doesn't actually take any operands though.
13442  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13443
13444  MI->eraseFromParent(); // The pseudo is gone now.
13445  return BB;
13446}
13447
13448MachineBasicBlock *
13449X86TargetLowering::EmitVAARG64WithCustomInserter(
13450                   MachineInstr *MI,
13451                   MachineBasicBlock *MBB) const {
13452  // Emit va_arg instruction on X86-64.
13453
13454  // Operands to this pseudo-instruction:
13455  // 0  ) Output        : destination address (reg)
13456  // 1-5) Input         : va_list address (addr, i64mem)
13457  // 6  ) ArgSize       : Size (in bytes) of vararg type
13458  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13459  // 8  ) Align         : Alignment of type
13460  // 9  ) EFLAGS (implicit-def)
13461
13462  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13463  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13464
13465  unsigned DestReg = MI->getOperand(0).getReg();
13466  MachineOperand &Base = MI->getOperand(1);
13467  MachineOperand &Scale = MI->getOperand(2);
13468  MachineOperand &Index = MI->getOperand(3);
13469  MachineOperand &Disp = MI->getOperand(4);
13470  MachineOperand &Segment = MI->getOperand(5);
13471  unsigned ArgSize = MI->getOperand(6).getImm();
13472  unsigned ArgMode = MI->getOperand(7).getImm();
13473  unsigned Align = MI->getOperand(8).getImm();
13474
13475  // Memory Reference
13476  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13477  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13478  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13479
13480  // Machine Information
13481  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13482  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13483  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13484  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13485  DebugLoc DL = MI->getDebugLoc();
13486
13487  // struct va_list {
13488  //   i32   gp_offset
13489  //   i32   fp_offset
13490  //   i64   overflow_area (address)
13491  //   i64   reg_save_area (address)
13492  // }
13493  // sizeof(va_list) = 24
13494  // alignment(va_list) = 8
13495
13496  unsigned TotalNumIntRegs = 6;
13497  unsigned TotalNumXMMRegs = 8;
13498  bool UseGPOffset = (ArgMode == 1);
13499  bool UseFPOffset = (ArgMode == 2);
13500  unsigned MaxOffset = TotalNumIntRegs * 8 +
13501                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13502
13503  /* Align ArgSize to a multiple of 8 */
13504  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13505  bool NeedsAlign = (Align > 8);
13506
13507  MachineBasicBlock *thisMBB = MBB;
13508  MachineBasicBlock *overflowMBB;
13509  MachineBasicBlock *offsetMBB;
13510  MachineBasicBlock *endMBB;
13511
13512  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13513  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13514  unsigned OffsetReg = 0;
13515
13516  if (!UseGPOffset && !UseFPOffset) {
13517    // If we only pull from the overflow region, we don't create a branch.
13518    // We don't need to alter control flow.
13519    OffsetDestReg = 0; // unused
13520    OverflowDestReg = DestReg;
13521
13522    offsetMBB = NULL;
13523    overflowMBB = thisMBB;
13524    endMBB = thisMBB;
13525  } else {
13526    // First emit code to check if gp_offset (or fp_offset) is below the bound.
13527    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13528    // If not, pull from overflow_area. (branch to overflowMBB)
13529    //
13530    //       thisMBB
13531    //         |     .
13532    //         |        .
13533    //     offsetMBB   overflowMBB
13534    //         |        .
13535    //         |     .
13536    //        endMBB
13537
13538    // Registers for the PHI in endMBB
13539    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13540    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13541
13542    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13543    MachineFunction *MF = MBB->getParent();
13544    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13545    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13546    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13547
13548    MachineFunction::iterator MBBIter = MBB;
13549    ++MBBIter;
13550
13551    // Insert the new basic blocks
13552    MF->insert(MBBIter, offsetMBB);
13553    MF->insert(MBBIter, overflowMBB);
13554    MF->insert(MBBIter, endMBB);
13555
13556    // Transfer the remainder of MBB and its successor edges to endMBB.
13557    endMBB->splice(endMBB->begin(), thisMBB,
13558                    llvm::next(MachineBasicBlock::iterator(MI)),
13559                    thisMBB->end());
13560    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13561
13562    // Make offsetMBB and overflowMBB successors of thisMBB
13563    thisMBB->addSuccessor(offsetMBB);
13564    thisMBB->addSuccessor(overflowMBB);
13565
13566    // endMBB is a successor of both offsetMBB and overflowMBB
13567    offsetMBB->addSuccessor(endMBB);
13568    overflowMBB->addSuccessor(endMBB);
13569
13570    // Load the offset value into a register
13571    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13572    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13573      .addOperand(Base)
13574      .addOperand(Scale)
13575      .addOperand(Index)
13576      .addDisp(Disp, UseFPOffset ? 4 : 0)
13577      .addOperand(Segment)
13578      .setMemRefs(MMOBegin, MMOEnd);
13579
13580    // Check if there is enough room left to pull this argument.
13581    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13582      .addReg(OffsetReg)
13583      .addImm(MaxOffset + 8 - ArgSizeA8);
13584
13585    // Branch to "overflowMBB" if offset >= max
13586    // Fall through to "offsetMBB" otherwise
13587    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13588      .addMBB(overflowMBB);
13589  }
13590
13591  // In offsetMBB, emit code to use the reg_save_area.
13592  if (offsetMBB) {
13593    assert(OffsetReg != 0);
13594
13595    // Read the reg_save_area address.
13596    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13597    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13598      .addOperand(Base)
13599      .addOperand(Scale)
13600      .addOperand(Index)
13601      .addDisp(Disp, 16)
13602      .addOperand(Segment)
13603      .setMemRefs(MMOBegin, MMOEnd);
13604
13605    // Zero-extend the offset
13606    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13607      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13608        .addImm(0)
13609        .addReg(OffsetReg)
13610        .addImm(X86::sub_32bit);
13611
13612    // Add the offset to the reg_save_area to get the final address.
13613    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13614      .addReg(OffsetReg64)
13615      .addReg(RegSaveReg);
13616
13617    // Compute the offset for the next argument
13618    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13619    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13620      .addReg(OffsetReg)
13621      .addImm(UseFPOffset ? 16 : 8);
13622
13623    // Store it back into the va_list.
13624    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13625      .addOperand(Base)
13626      .addOperand(Scale)
13627      .addOperand(Index)
13628      .addDisp(Disp, UseFPOffset ? 4 : 0)
13629      .addOperand(Segment)
13630      .addReg(NextOffsetReg)
13631      .setMemRefs(MMOBegin, MMOEnd);
13632
13633    // Jump to endMBB
13634    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13635      .addMBB(endMBB);
13636  }
13637
13638  //
13639  // Emit code to use overflow area
13640  //
13641
13642  // Load the overflow_area address into a register.
13643  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13644  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13645    .addOperand(Base)
13646    .addOperand(Scale)
13647    .addOperand(Index)
13648    .addDisp(Disp, 8)
13649    .addOperand(Segment)
13650    .setMemRefs(MMOBegin, MMOEnd);
13651
13652  // If we need to align it, do so. Otherwise, just copy the address
13653  // to OverflowDestReg.
13654  if (NeedsAlign) {
13655    // Align the overflow address
13656    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13657    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13658
13659    // aligned_addr = (addr + (align-1)) & ~(align-1)
13660    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13661      .addReg(OverflowAddrReg)
13662      .addImm(Align-1);
13663
13664    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13665      .addReg(TmpReg)
13666      .addImm(~(uint64_t)(Align-1));
13667  } else {
13668    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13669      .addReg(OverflowAddrReg);
13670  }
13671
13672  // Compute the next overflow address after this argument.
13673  // (the overflow address should be kept 8-byte aligned)
13674  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13675  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13676    .addReg(OverflowDestReg)
13677    .addImm(ArgSizeA8);
13678
13679  // Store the new overflow address.
13680  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13681    .addOperand(Base)
13682    .addOperand(Scale)
13683    .addOperand(Index)
13684    .addDisp(Disp, 8)
13685    .addOperand(Segment)
13686    .addReg(NextAddrReg)
13687    .setMemRefs(MMOBegin, MMOEnd);
13688
13689  // If we branched, emit the PHI to the front of endMBB.
13690  if (offsetMBB) {
13691    BuildMI(*endMBB, endMBB->begin(), DL,
13692            TII->get(X86::PHI), DestReg)
13693      .addReg(OffsetDestReg).addMBB(offsetMBB)
13694      .addReg(OverflowDestReg).addMBB(overflowMBB);
13695  }
13696
13697  // Erase the pseudo instruction
13698  MI->eraseFromParent();
13699
13700  return endMBB;
13701}
13702
13703MachineBasicBlock *
13704X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13705                                                 MachineInstr *MI,
13706                                                 MachineBasicBlock *MBB) const {
13707  // Emit code to save XMM registers to the stack. The ABI says that the
13708  // number of registers to save is given in %al, so it's theoretically
13709  // possible to do an indirect jump trick to avoid saving all of them,
13710  // however this code takes a simpler approach and just executes all
13711  // of the stores if %al is non-zero. It's less code, and it's probably
13712  // easier on the hardware branch predictor, and stores aren't all that
13713  // expensive anyway.
13714
13715  // Create the new basic blocks. One block contains all the XMM stores,
13716  // and one block is the final destination regardless of whether any
13717  // stores were performed.
13718  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13719  MachineFunction *F = MBB->getParent();
13720  MachineFunction::iterator MBBIter = MBB;
13721  ++MBBIter;
13722  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13723  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13724  F->insert(MBBIter, XMMSaveMBB);
13725  F->insert(MBBIter, EndMBB);
13726
13727  // Transfer the remainder of MBB and its successor edges to EndMBB.
13728  EndMBB->splice(EndMBB->begin(), MBB,
13729                 llvm::next(MachineBasicBlock::iterator(MI)),
13730                 MBB->end());
13731  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13732
13733  // The original block will now fall through to the XMM save block.
13734  MBB->addSuccessor(XMMSaveMBB);
13735  // The XMMSaveMBB will fall through to the end block.
13736  XMMSaveMBB->addSuccessor(EndMBB);
13737
13738  // Now add the instructions.
13739  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13740  DebugLoc DL = MI->getDebugLoc();
13741
13742  unsigned CountReg = MI->getOperand(0).getReg();
13743  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13744  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13745
13746  if (!Subtarget->isTargetWin64()) {
13747    // If %al is 0, branch around the XMM save block.
13748    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13749    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13750    MBB->addSuccessor(EndMBB);
13751  }
13752
13753  unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13754  // In the XMM save block, save all the XMM argument registers.
13755  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13756    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13757    MachineMemOperand *MMO =
13758      F->getMachineMemOperand(
13759          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13760        MachineMemOperand::MOStore,
13761        /*Size=*/16, /*Align=*/16);
13762    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13763      .addFrameIndex(RegSaveFrameIndex)
13764      .addImm(/*Scale=*/1)
13765      .addReg(/*IndexReg=*/0)
13766      .addImm(/*Disp=*/Offset)
13767      .addReg(/*Segment=*/0)
13768      .addReg(MI->getOperand(i).getReg())
13769      .addMemOperand(MMO);
13770  }
13771
13772  MI->eraseFromParent();   // The pseudo instruction is gone now.
13773
13774  return EndMBB;
13775}
13776
13777// The EFLAGS operand of SelectItr might be missing a kill marker
13778// because there were multiple uses of EFLAGS, and ISel didn't know
13779// which to mark. Figure out whether SelectItr should have had a
13780// kill marker, and set it if it should. Returns the correct kill
13781// marker value.
13782static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13783                                     MachineBasicBlock* BB,
13784                                     const TargetRegisterInfo* TRI) {
13785  // Scan forward through BB for a use/def of EFLAGS.
13786  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13787  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13788    const MachineInstr& mi = *miI;
13789    if (mi.readsRegister(X86::EFLAGS))
13790      return false;
13791    if (mi.definesRegister(X86::EFLAGS))
13792      break; // Should have kill-flag - update below.
13793  }
13794
13795  // If we hit the end of the block, check whether EFLAGS is live into a
13796  // successor.
13797  if (miI == BB->end()) {
13798    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13799                                          sEnd = BB->succ_end();
13800         sItr != sEnd; ++sItr) {
13801      MachineBasicBlock* succ = *sItr;
13802      if (succ->isLiveIn(X86::EFLAGS))
13803        return false;
13804    }
13805  }
13806
13807  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13808  // out. SelectMI should have a kill flag on EFLAGS.
13809  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13810  return true;
13811}
13812
13813MachineBasicBlock *
13814X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13815                                     MachineBasicBlock *BB) const {
13816  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13817  DebugLoc DL = MI->getDebugLoc();
13818
13819  // To "insert" a SELECT_CC instruction, we actually have to insert the
13820  // diamond control-flow pattern.  The incoming instruction knows the
13821  // destination vreg to set, the condition code register to branch on, the
13822  // true/false values to select between, and a branch opcode to use.
13823  const BasicBlock *LLVM_BB = BB->getBasicBlock();
13824  MachineFunction::iterator It = BB;
13825  ++It;
13826
13827  //  thisMBB:
13828  //  ...
13829  //   TrueVal = ...
13830  //   cmpTY ccX, r1, r2
13831  //   bCC copy1MBB
13832  //   fallthrough --> copy0MBB
13833  MachineBasicBlock *thisMBB = BB;
13834  MachineFunction *F = BB->getParent();
13835  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13836  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13837  F->insert(It, copy0MBB);
13838  F->insert(It, sinkMBB);
13839
13840  // If the EFLAGS register isn't dead in the terminator, then claim that it's
13841  // live into the sink and copy blocks.
13842  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13843  if (!MI->killsRegister(X86::EFLAGS) &&
13844      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13845    copy0MBB->addLiveIn(X86::EFLAGS);
13846    sinkMBB->addLiveIn(X86::EFLAGS);
13847  }
13848
13849  // Transfer the remainder of BB and its successor edges to sinkMBB.
13850  sinkMBB->splice(sinkMBB->begin(), BB,
13851                  llvm::next(MachineBasicBlock::iterator(MI)),
13852                  BB->end());
13853  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13854
13855  // Add the true and fallthrough blocks as its successors.
13856  BB->addSuccessor(copy0MBB);
13857  BB->addSuccessor(sinkMBB);
13858
13859  // Create the conditional branch instruction.
13860  unsigned Opc =
13861    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13862  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13863
13864  //  copy0MBB:
13865  //   %FalseValue = ...
13866  //   # fallthrough to sinkMBB
13867  copy0MBB->addSuccessor(sinkMBB);
13868
13869  //  sinkMBB:
13870  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13871  //  ...
13872  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13873          TII->get(X86::PHI), MI->getOperand(0).getReg())
13874    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13875    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13876
13877  MI->eraseFromParent();   // The pseudo instruction is gone now.
13878  return sinkMBB;
13879}
13880
13881MachineBasicBlock *
13882X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13883                                        bool Is64Bit) const {
13884  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13885  DebugLoc DL = MI->getDebugLoc();
13886  MachineFunction *MF = BB->getParent();
13887  const BasicBlock *LLVM_BB = BB->getBasicBlock();
13888
13889  assert(getTargetMachine().Options.EnableSegmentedStacks);
13890
13891  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13892  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13893
13894  // BB:
13895  //  ... [Till the alloca]
13896  // If stacklet is not large enough, jump to mallocMBB
13897  //
13898  // bumpMBB:
13899  //  Allocate by subtracting from RSP
13900  //  Jump to continueMBB
13901  //
13902  // mallocMBB:
13903  //  Allocate by call to runtime
13904  //
13905  // continueMBB:
13906  //  ...
13907  //  [rest of original BB]
13908  //
13909
13910  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13911  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13912  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13913
13914  MachineRegisterInfo &MRI = MF->getRegInfo();
13915  const TargetRegisterClass *AddrRegClass =
13916    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13917
13918  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13919    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13920    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13921    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13922    sizeVReg = MI->getOperand(1).getReg(),
13923    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13924
13925  MachineFunction::iterator MBBIter = BB;
13926  ++MBBIter;
13927
13928  MF->insert(MBBIter, bumpMBB);
13929  MF->insert(MBBIter, mallocMBB);
13930  MF->insert(MBBIter, continueMBB);
13931
13932  continueMBB->splice(continueMBB->begin(), BB, llvm::next
13933                      (MachineBasicBlock::iterator(MI)), BB->end());
13934  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13935
13936  // Add code to the main basic block to check if the stack limit has been hit,
13937  // and if so, jump to mallocMBB otherwise to bumpMBB.
13938  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13939  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13940    .addReg(tmpSPVReg).addReg(sizeVReg);
13941  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13942    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13943    .addReg(SPLimitVReg);
13944  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13945
13946  // bumpMBB simply decreases the stack pointer, since we know the current
13947  // stacklet has enough space.
13948  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13949    .addReg(SPLimitVReg);
13950  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13951    .addReg(SPLimitVReg);
13952  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13953
13954  // Calls into a routine in libgcc to allocate more space from the heap.
13955  const uint32_t *RegMask =
13956    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13957  if (Is64Bit) {
13958    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13959      .addReg(sizeVReg);
13960    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13961      .addExternalSymbol("__morestack_allocate_stack_space")
13962      .addRegMask(RegMask)
13963      .addReg(X86::RDI, RegState::Implicit)
13964      .addReg(X86::RAX, RegState::ImplicitDefine);
13965  } else {
13966    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13967      .addImm(12);
13968    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13969    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13970      .addExternalSymbol("__morestack_allocate_stack_space")
13971      .addRegMask(RegMask)
13972      .addReg(X86::EAX, RegState::ImplicitDefine);
13973  }
13974
13975  if (!Is64Bit)
13976    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13977      .addImm(16);
13978
13979  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13980    .addReg(Is64Bit ? X86::RAX : X86::EAX);
13981  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13982
13983  // Set up the CFG correctly.
13984  BB->addSuccessor(bumpMBB);
13985  BB->addSuccessor(mallocMBB);
13986  mallocMBB->addSuccessor(continueMBB);
13987  bumpMBB->addSuccessor(continueMBB);
13988
13989  // Take care of the PHI nodes.
13990  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13991          MI->getOperand(0).getReg())
13992    .addReg(mallocPtrVReg).addMBB(mallocMBB)
13993    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13994
13995  // Delete the original pseudo instruction.
13996  MI->eraseFromParent();
13997
13998  // And we're done.
13999  return continueMBB;
14000}
14001
14002MachineBasicBlock *
14003X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14004                                          MachineBasicBlock *BB) const {
14005  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14006  DebugLoc DL = MI->getDebugLoc();
14007
14008  assert(!Subtarget->isTargetEnvMacho());
14009
14010  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14011  // non-trivial part is impdef of ESP.
14012
14013  if (Subtarget->isTargetWin64()) {
14014    if (Subtarget->isTargetCygMing()) {
14015      // ___chkstk(Mingw64):
14016      // Clobbers R10, R11, RAX and EFLAGS.
14017      // Updates RSP.
14018      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14019        .addExternalSymbol("___chkstk")
14020        .addReg(X86::RAX, RegState::Implicit)
14021        .addReg(X86::RSP, RegState::Implicit)
14022        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14023        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14024        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14025    } else {
14026      // __chkstk(MSVCRT): does not update stack pointer.
14027      // Clobbers R10, R11 and EFLAGS.
14028      // FIXME: RAX(allocated size) might be reused and not killed.
14029      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14030        .addExternalSymbol("__chkstk")
14031        .addReg(X86::RAX, RegState::Implicit)
14032        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14033      // RAX has the offset to subtracted from RSP.
14034      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14035        .addReg(X86::RSP)
14036        .addReg(X86::RAX);
14037    }
14038  } else {
14039    const char *StackProbeSymbol =
14040      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14041
14042    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14043      .addExternalSymbol(StackProbeSymbol)
14044      .addReg(X86::EAX, RegState::Implicit)
14045      .addReg(X86::ESP, RegState::Implicit)
14046      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14047      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14048      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14049  }
14050
14051  MI->eraseFromParent();   // The pseudo instruction is gone now.
14052  return BB;
14053}
14054
14055MachineBasicBlock *
14056X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14057                                      MachineBasicBlock *BB) const {
14058  // This is pretty easy.  We're taking the value that we received from
14059  // our load from the relocation, sticking it in either RDI (x86-64)
14060  // or EAX and doing an indirect call.  The return value will then
14061  // be in the normal return register.
14062  const X86InstrInfo *TII
14063    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14064  DebugLoc DL = MI->getDebugLoc();
14065  MachineFunction *F = BB->getParent();
14066
14067  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14068  assert(MI->getOperand(3).isGlobal() && "This should be a global");
14069
14070  // Get a register mask for the lowered call.
14071  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14072  // proper register mask.
14073  const uint32_t *RegMask =
14074    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14075  if (Subtarget->is64Bit()) {
14076    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14077                                      TII->get(X86::MOV64rm), X86::RDI)
14078    .addReg(X86::RIP)
14079    .addImm(0).addReg(0)
14080    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14081                      MI->getOperand(3).getTargetFlags())
14082    .addReg(0);
14083    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14084    addDirectMem(MIB, X86::RDI);
14085    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14086  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14087    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14088                                      TII->get(X86::MOV32rm), X86::EAX)
14089    .addReg(0)
14090    .addImm(0).addReg(0)
14091    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14092                      MI->getOperand(3).getTargetFlags())
14093    .addReg(0);
14094    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14095    addDirectMem(MIB, X86::EAX);
14096    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14097  } else {
14098    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14099                                      TII->get(X86::MOV32rm), X86::EAX)
14100    .addReg(TII->getGlobalBaseReg(F))
14101    .addImm(0).addReg(0)
14102    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14103                      MI->getOperand(3).getTargetFlags())
14104    .addReg(0);
14105    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14106    addDirectMem(MIB, X86::EAX);
14107    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14108  }
14109
14110  MI->eraseFromParent(); // The pseudo instruction is gone now.
14111  return BB;
14112}
14113
14114MachineBasicBlock *
14115X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14116                                    MachineBasicBlock *MBB) const {
14117  DebugLoc DL = MI->getDebugLoc();
14118  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14119
14120  MachineFunction *MF = MBB->getParent();
14121  MachineRegisterInfo &MRI = MF->getRegInfo();
14122
14123  const BasicBlock *BB = MBB->getBasicBlock();
14124  MachineFunction::iterator I = MBB;
14125  ++I;
14126
14127  // Memory Reference
14128  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14129  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14130
14131  unsigned DstReg;
14132  unsigned MemOpndSlot = 0;
14133
14134  unsigned CurOp = 0;
14135
14136  DstReg = MI->getOperand(CurOp++).getReg();
14137  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14138  assert(RC->hasType(MVT::i32) && "Invalid destination!");
14139  unsigned mainDstReg = MRI.createVirtualRegister(RC);
14140  unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14141
14142  MemOpndSlot = CurOp;
14143
14144  MVT PVT = getPointerTy();
14145  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14146         "Invalid Pointer Size!");
14147
14148  // For v = setjmp(buf), we generate
14149  //
14150  // thisMBB:
14151  //  buf[LabelOffset] = restoreMBB
14152  //  SjLjSetup restoreMBB
14153  //
14154  // mainMBB:
14155  //  v_main = 0
14156  //
14157  // sinkMBB:
14158  //  v = phi(main, restore)
14159  //
14160  // restoreMBB:
14161  //  v_restore = 1
14162
14163  MachineBasicBlock *thisMBB = MBB;
14164  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14165  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14166  MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14167  MF->insert(I, mainMBB);
14168  MF->insert(I, sinkMBB);
14169  MF->push_back(restoreMBB);
14170
14171  MachineInstrBuilder MIB;
14172
14173  // Transfer the remainder of BB and its successor edges to sinkMBB.
14174  sinkMBB->splice(sinkMBB->begin(), MBB,
14175                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14176  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14177
14178  // thisMBB:
14179  unsigned PtrStoreOpc = 0;
14180  unsigned LabelReg = 0;
14181  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14182  Reloc::Model RM = getTargetMachine().getRelocationModel();
14183  bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14184                     (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14185
14186  // Prepare IP either in reg or imm.
14187  if (!UseImmLabel) {
14188    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14189    const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14190    LabelReg = MRI.createVirtualRegister(PtrRC);
14191    if (Subtarget->is64Bit()) {
14192      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14193              .addReg(X86::RIP)
14194              .addImm(0)
14195              .addReg(0)
14196              .addMBB(restoreMBB)
14197              .addReg(0);
14198    } else {
14199      const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14200      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14201              .addReg(XII->getGlobalBaseReg(MF))
14202              .addImm(0)
14203              .addReg(0)
14204              .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14205              .addReg(0);
14206    }
14207  } else
14208    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14209  // Store IP
14210  MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14211  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14212    if (i == X86::AddrDisp)
14213      MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14214    else
14215      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14216  }
14217  if (!UseImmLabel)
14218    MIB.addReg(LabelReg);
14219  else
14220    MIB.addMBB(restoreMBB);
14221  MIB.setMemRefs(MMOBegin, MMOEnd);
14222  // Setup
14223  MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14224          .addMBB(restoreMBB);
14225  MIB.addRegMask(RegInfo->getNoPreservedMask());
14226  thisMBB->addSuccessor(mainMBB);
14227  thisMBB->addSuccessor(restoreMBB);
14228
14229  // mainMBB:
14230  //  EAX = 0
14231  BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14232  mainMBB->addSuccessor(sinkMBB);
14233
14234  // sinkMBB:
14235  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14236          TII->get(X86::PHI), DstReg)
14237    .addReg(mainDstReg).addMBB(mainMBB)
14238    .addReg(restoreDstReg).addMBB(restoreMBB);
14239
14240  // restoreMBB:
14241  BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14242  BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14243  restoreMBB->addSuccessor(sinkMBB);
14244
14245  MI->eraseFromParent();
14246  return sinkMBB;
14247}
14248
14249MachineBasicBlock *
14250X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14251                                     MachineBasicBlock *MBB) const {
14252  DebugLoc DL = MI->getDebugLoc();
14253  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14254
14255  MachineFunction *MF = MBB->getParent();
14256  MachineRegisterInfo &MRI = MF->getRegInfo();
14257
14258  // Memory Reference
14259  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14260  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14261
14262  MVT PVT = getPointerTy();
14263  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14264         "Invalid Pointer Size!");
14265
14266  const TargetRegisterClass *RC =
14267    (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14268  unsigned Tmp = MRI.createVirtualRegister(RC);
14269  // Since FP is only updated here but NOT referenced, it's treated as GPR.
14270  unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14271  unsigned SP = RegInfo->getStackRegister();
14272
14273  MachineInstrBuilder MIB;
14274
14275  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14276  const int64_t SPOffset = 2 * PVT.getStoreSize();
14277
14278  unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14279  unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14280
14281  // Reload FP
14282  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14283  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14284    MIB.addOperand(MI->getOperand(i));
14285  MIB.setMemRefs(MMOBegin, MMOEnd);
14286  // Reload IP
14287  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14288  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14289    if (i == X86::AddrDisp)
14290      MIB.addDisp(MI->getOperand(i), LabelOffset);
14291    else
14292      MIB.addOperand(MI->getOperand(i));
14293  }
14294  MIB.setMemRefs(MMOBegin, MMOEnd);
14295  // Reload SP
14296  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14297  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14298    if (i == X86::AddrDisp)
14299      MIB.addDisp(MI->getOperand(i), SPOffset);
14300    else
14301      MIB.addOperand(MI->getOperand(i));
14302  }
14303  MIB.setMemRefs(MMOBegin, MMOEnd);
14304  // Jump
14305  BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14306
14307  MI->eraseFromParent();
14308  return MBB;
14309}
14310
14311MachineBasicBlock *
14312X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14313                                               MachineBasicBlock *BB) const {
14314  switch (MI->getOpcode()) {
14315  default: llvm_unreachable("Unexpected instr type to insert");
14316  case X86::TAILJMPd64:
14317  case X86::TAILJMPr64:
14318  case X86::TAILJMPm64:
14319    llvm_unreachable("TAILJMP64 would not be touched here.");
14320  case X86::TCRETURNdi64:
14321  case X86::TCRETURNri64:
14322  case X86::TCRETURNmi64:
14323    return BB;
14324  case X86::WIN_ALLOCA:
14325    return EmitLoweredWinAlloca(MI, BB);
14326  case X86::SEG_ALLOCA_32:
14327    return EmitLoweredSegAlloca(MI, BB, false);
14328  case X86::SEG_ALLOCA_64:
14329    return EmitLoweredSegAlloca(MI, BB, true);
14330  case X86::TLSCall_32:
14331  case X86::TLSCall_64:
14332    return EmitLoweredTLSCall(MI, BB);
14333  case X86::CMOV_GR8:
14334  case X86::CMOV_FR32:
14335  case X86::CMOV_FR64:
14336  case X86::CMOV_V4F32:
14337  case X86::CMOV_V2F64:
14338  case X86::CMOV_V2I64:
14339  case X86::CMOV_V8F32:
14340  case X86::CMOV_V4F64:
14341  case X86::CMOV_V4I64:
14342  case X86::CMOV_GR16:
14343  case X86::CMOV_GR32:
14344  case X86::CMOV_RFP32:
14345  case X86::CMOV_RFP64:
14346  case X86::CMOV_RFP80:
14347    return EmitLoweredSelect(MI, BB);
14348
14349  case X86::FP32_TO_INT16_IN_MEM:
14350  case X86::FP32_TO_INT32_IN_MEM:
14351  case X86::FP32_TO_INT64_IN_MEM:
14352  case X86::FP64_TO_INT16_IN_MEM:
14353  case X86::FP64_TO_INT32_IN_MEM:
14354  case X86::FP64_TO_INT64_IN_MEM:
14355  case X86::FP80_TO_INT16_IN_MEM:
14356  case X86::FP80_TO_INT32_IN_MEM:
14357  case X86::FP80_TO_INT64_IN_MEM: {
14358    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14359    DebugLoc DL = MI->getDebugLoc();
14360
14361    // Change the floating point control register to use "round towards zero"
14362    // mode when truncating to an integer value.
14363    MachineFunction *F = BB->getParent();
14364    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14365    addFrameReference(BuildMI(*BB, MI, DL,
14366                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
14367
14368    // Load the old value of the high byte of the control word...
14369    unsigned OldCW =
14370      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14371    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14372                      CWFrameIdx);
14373
14374    // Set the high part to be round to zero...
14375    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14376      .addImm(0xC7F);
14377
14378    // Reload the modified control word now...
14379    addFrameReference(BuildMI(*BB, MI, DL,
14380                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14381
14382    // Restore the memory image of control word to original value
14383    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14384      .addReg(OldCW);
14385
14386    // Get the X86 opcode to use.
14387    unsigned Opc;
14388    switch (MI->getOpcode()) {
14389    default: llvm_unreachable("illegal opcode!");
14390    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14391    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14392    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14393    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14394    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14395    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14396    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14397    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14398    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14399    }
14400
14401    X86AddressMode AM;
14402    MachineOperand &Op = MI->getOperand(0);
14403    if (Op.isReg()) {
14404      AM.BaseType = X86AddressMode::RegBase;
14405      AM.Base.Reg = Op.getReg();
14406    } else {
14407      AM.BaseType = X86AddressMode::FrameIndexBase;
14408      AM.Base.FrameIndex = Op.getIndex();
14409    }
14410    Op = MI->getOperand(1);
14411    if (Op.isImm())
14412      AM.Scale = Op.getImm();
14413    Op = MI->getOperand(2);
14414    if (Op.isImm())
14415      AM.IndexReg = Op.getImm();
14416    Op = MI->getOperand(3);
14417    if (Op.isGlobal()) {
14418      AM.GV = Op.getGlobal();
14419    } else {
14420      AM.Disp = Op.getImm();
14421    }
14422    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14423                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14424
14425    // Reload the original control word now.
14426    addFrameReference(BuildMI(*BB, MI, DL,
14427                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14428
14429    MI->eraseFromParent();   // The pseudo instruction is gone now.
14430    return BB;
14431  }
14432    // String/text processing lowering.
14433  case X86::PCMPISTRM128REG:
14434  case X86::VPCMPISTRM128REG:
14435  case X86::PCMPISTRM128MEM:
14436  case X86::VPCMPISTRM128MEM:
14437  case X86::PCMPESTRM128REG:
14438  case X86::VPCMPESTRM128REG:
14439  case X86::PCMPESTRM128MEM:
14440  case X86::VPCMPESTRM128MEM:
14441    assert(Subtarget->hasSSE42() &&
14442           "Target must have SSE4.2 or AVX features enabled");
14443    return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14444
14445  // String/text processing lowering.
14446  case X86::PCMPISTRIREG:
14447  case X86::VPCMPISTRIREG:
14448  case X86::PCMPISTRIMEM:
14449  case X86::VPCMPISTRIMEM:
14450  case X86::PCMPESTRIREG:
14451  case X86::VPCMPESTRIREG:
14452  case X86::PCMPESTRIMEM:
14453  case X86::VPCMPESTRIMEM:
14454    assert(Subtarget->hasSSE42() &&
14455           "Target must have SSE4.2 or AVX features enabled");
14456    return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14457
14458  // Thread synchronization.
14459  case X86::MONITOR:
14460    return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14461
14462  // xbegin
14463  case X86::XBEGIN:
14464    return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14465
14466  // Atomic Lowering.
14467  case X86::ATOMAND8:
14468  case X86::ATOMAND16:
14469  case X86::ATOMAND32:
14470  case X86::ATOMAND64:
14471    // Fall through
14472  case X86::ATOMOR8:
14473  case X86::ATOMOR16:
14474  case X86::ATOMOR32:
14475  case X86::ATOMOR64:
14476    // Fall through
14477  case X86::ATOMXOR16:
14478  case X86::ATOMXOR8:
14479  case X86::ATOMXOR32:
14480  case X86::ATOMXOR64:
14481    // Fall through
14482  case X86::ATOMNAND8:
14483  case X86::ATOMNAND16:
14484  case X86::ATOMNAND32:
14485  case X86::ATOMNAND64:
14486    // Fall through
14487  case X86::ATOMMAX8:
14488  case X86::ATOMMAX16:
14489  case X86::ATOMMAX32:
14490  case X86::ATOMMAX64:
14491    // Fall through
14492  case X86::ATOMMIN8:
14493  case X86::ATOMMIN16:
14494  case X86::ATOMMIN32:
14495  case X86::ATOMMIN64:
14496    // Fall through
14497  case X86::ATOMUMAX8:
14498  case X86::ATOMUMAX16:
14499  case X86::ATOMUMAX32:
14500  case X86::ATOMUMAX64:
14501    // Fall through
14502  case X86::ATOMUMIN8:
14503  case X86::ATOMUMIN16:
14504  case X86::ATOMUMIN32:
14505  case X86::ATOMUMIN64:
14506    return EmitAtomicLoadArith(MI, BB);
14507
14508  // This group does 64-bit operations on a 32-bit host.
14509  case X86::ATOMAND6432:
14510  case X86::ATOMOR6432:
14511  case X86::ATOMXOR6432:
14512  case X86::ATOMNAND6432:
14513  case X86::ATOMADD6432:
14514  case X86::ATOMSUB6432:
14515  case X86::ATOMMAX6432:
14516  case X86::ATOMMIN6432:
14517  case X86::ATOMUMAX6432:
14518  case X86::ATOMUMIN6432:
14519  case X86::ATOMSWAP6432:
14520    return EmitAtomicLoadArith6432(MI, BB);
14521
14522  case X86::VASTART_SAVE_XMM_REGS:
14523    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14524
14525  case X86::VAARG_64:
14526    return EmitVAARG64WithCustomInserter(MI, BB);
14527
14528  case X86::EH_SjLj_SetJmp32:
14529  case X86::EH_SjLj_SetJmp64:
14530    return emitEHSjLjSetJmp(MI, BB);
14531
14532  case X86::EH_SjLj_LongJmp32:
14533  case X86::EH_SjLj_LongJmp64:
14534    return emitEHSjLjLongJmp(MI, BB);
14535  }
14536}
14537
14538//===----------------------------------------------------------------------===//
14539//                           X86 Optimization Hooks
14540//===----------------------------------------------------------------------===//
14541
14542void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14543                                                       APInt &KnownZero,
14544                                                       APInt &KnownOne,
14545                                                       const SelectionDAG &DAG,
14546                                                       unsigned Depth) const {
14547  unsigned BitWidth = KnownZero.getBitWidth();
14548  unsigned Opc = Op.getOpcode();
14549  assert((Opc >= ISD::BUILTIN_OP_END ||
14550          Opc == ISD::INTRINSIC_WO_CHAIN ||
14551          Opc == ISD::INTRINSIC_W_CHAIN ||
14552          Opc == ISD::INTRINSIC_VOID) &&
14553         "Should use MaskedValueIsZero if you don't know whether Op"
14554         " is a target node!");
14555
14556  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14557  switch (Opc) {
14558  default: break;
14559  case X86ISD::ADD:
14560  case X86ISD::SUB:
14561  case X86ISD::ADC:
14562  case X86ISD::SBB:
14563  case X86ISD::SMUL:
14564  case X86ISD::UMUL:
14565  case X86ISD::INC:
14566  case X86ISD::DEC:
14567  case X86ISD::OR:
14568  case X86ISD::XOR:
14569  case X86ISD::AND:
14570    // These nodes' second result is a boolean.
14571    if (Op.getResNo() == 0)
14572      break;
14573    // Fallthrough
14574  case X86ISD::SETCC:
14575    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14576    break;
14577  case ISD::INTRINSIC_WO_CHAIN: {
14578    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14579    unsigned NumLoBits = 0;
14580    switch (IntId) {
14581    default: break;
14582    case Intrinsic::x86_sse_movmsk_ps:
14583    case Intrinsic::x86_avx_movmsk_ps_256:
14584    case Intrinsic::x86_sse2_movmsk_pd:
14585    case Intrinsic::x86_avx_movmsk_pd_256:
14586    case Intrinsic::x86_mmx_pmovmskb:
14587    case Intrinsic::x86_sse2_pmovmskb_128:
14588    case Intrinsic::x86_avx2_pmovmskb: {
14589      // High bits of movmskp{s|d}, pmovmskb are known zero.
14590      switch (IntId) {
14591        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14592        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14593        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14594        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14595        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14596        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14597        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14598        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14599      }
14600      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14601      break;
14602    }
14603    }
14604    break;
14605  }
14606  }
14607}
14608
14609unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14610                                                         unsigned Depth) const {
14611  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14612  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14613    return Op.getValueType().getScalarType().getSizeInBits();
14614
14615  // Fallback case.
14616  return 1;
14617}
14618
14619/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14620/// node is a GlobalAddress + offset.
14621bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14622                                       const GlobalValue* &GA,
14623                                       int64_t &Offset) const {
14624  if (N->getOpcode() == X86ISD::Wrapper) {
14625    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14626      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14627      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14628      return true;
14629    }
14630  }
14631  return TargetLowering::isGAPlusOffset(N, GA, Offset);
14632}
14633
14634/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14635/// same as extracting the high 128-bit part of 256-bit vector and then
14636/// inserting the result into the low part of a new 256-bit vector
14637static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14638  EVT VT = SVOp->getValueType(0);
14639  unsigned NumElems = VT.getVectorNumElements();
14640
14641  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14642  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14643    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14644        SVOp->getMaskElt(j) >= 0)
14645      return false;
14646
14647  return true;
14648}
14649
14650/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14651/// same as extracting the low 128-bit part of 256-bit vector and then
14652/// inserting the result into the high part of a new 256-bit vector
14653static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14654  EVT VT = SVOp->getValueType(0);
14655  unsigned NumElems = VT.getVectorNumElements();
14656
14657  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14658  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14659    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14660        SVOp->getMaskElt(j) >= 0)
14661      return false;
14662
14663  return true;
14664}
14665
14666/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14667static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14668                                        TargetLowering::DAGCombinerInfo &DCI,
14669                                        const X86Subtarget* Subtarget) {
14670  DebugLoc dl = N->getDebugLoc();
14671  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14672  SDValue V1 = SVOp->getOperand(0);
14673  SDValue V2 = SVOp->getOperand(1);
14674  EVT VT = SVOp->getValueType(0);
14675  unsigned NumElems = VT.getVectorNumElements();
14676
14677  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14678      V2.getOpcode() == ISD::CONCAT_VECTORS) {
14679    //
14680    //                   0,0,0,...
14681    //                      |
14682    //    V      UNDEF    BUILD_VECTOR    UNDEF
14683    //     \      /           \           /
14684    //  CONCAT_VECTOR         CONCAT_VECTOR
14685    //         \                  /
14686    //          \                /
14687    //          RESULT: V + zero extended
14688    //
14689    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14690        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14691        V1.getOperand(1).getOpcode() != ISD::UNDEF)
14692      return SDValue();
14693
14694    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14695      return SDValue();
14696
14697    // To match the shuffle mask, the first half of the mask should
14698    // be exactly the first vector, and all the rest a splat with the
14699    // first element of the second one.
14700    for (unsigned i = 0; i != NumElems/2; ++i)
14701      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14702          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14703        return SDValue();
14704
14705    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14706    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14707      if (Ld->hasNUsesOfValue(1, 0)) {
14708        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14709        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14710        SDValue ResNode =
14711          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14712                                  Ld->getMemoryVT(),
14713                                  Ld->getPointerInfo(),
14714                                  Ld->getAlignment(),
14715                                  false/*isVolatile*/, true/*ReadMem*/,
14716                                  false/*WriteMem*/);
14717
14718        // Make sure the newly-created LOAD is in the same position as Ld in
14719        // terms of dependency. We create a TokenFactor for Ld and ResNode,
14720        // and update uses of Ld's output chain to use the TokenFactor.
14721        if (Ld->hasAnyUseOfValue(1)) {
14722          SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14723                             SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14724          DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14725          DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14726                                 SDValue(ResNode.getNode(), 1));
14727        }
14728
14729        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14730      }
14731    }
14732
14733    // Emit a zeroed vector and insert the desired subvector on its
14734    // first half.
14735    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14736    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14737    return DCI.CombineTo(N, InsV);
14738  }
14739
14740  //===--------------------------------------------------------------------===//
14741  // Combine some shuffles into subvector extracts and inserts:
14742  //
14743
14744  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14745  if (isShuffleHigh128VectorInsertLow(SVOp)) {
14746    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14747    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14748    return DCI.CombineTo(N, InsV);
14749  }
14750
14751  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14752  if (isShuffleLow128VectorInsertHigh(SVOp)) {
14753    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14754    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14755    return DCI.CombineTo(N, InsV);
14756  }
14757
14758  return SDValue();
14759}
14760
14761/// PerformShuffleCombine - Performs several different shuffle combines.
14762static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14763                                     TargetLowering::DAGCombinerInfo &DCI,
14764                                     const X86Subtarget *Subtarget) {
14765  DebugLoc dl = N->getDebugLoc();
14766  EVT VT = N->getValueType(0);
14767
14768  // Don't create instructions with illegal types after legalize types has run.
14769  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14770  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14771    return SDValue();
14772
14773  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14774  if (Subtarget->hasFp256() && VT.is256BitVector() &&
14775      N->getOpcode() == ISD::VECTOR_SHUFFLE)
14776    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14777
14778  // Only handle 128 wide vector from here on.
14779  if (!VT.is128BitVector())
14780    return SDValue();
14781
14782  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14783  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14784  // consecutive, non-overlapping, and in the right order.
14785  SmallVector<SDValue, 16> Elts;
14786  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14787    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14788
14789  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14790}
14791
14792/// PerformTruncateCombine - Converts truncate operation to
14793/// a sequence of vector shuffle operations.
14794/// It is possible when we truncate 256-bit vector to 128-bit vector
14795static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14796                                      TargetLowering::DAGCombinerInfo &DCI,
14797                                      const X86Subtarget *Subtarget)  {
14798  return SDValue();
14799}
14800
14801/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14802/// specific shuffle of a load can be folded into a single element load.
14803/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14804/// shuffles have been customed lowered so we need to handle those here.
14805static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14806                                         TargetLowering::DAGCombinerInfo &DCI) {
14807  if (DCI.isBeforeLegalizeOps())
14808    return SDValue();
14809
14810  SDValue InVec = N->getOperand(0);
14811  SDValue EltNo = N->getOperand(1);
14812
14813  if (!isa<ConstantSDNode>(EltNo))
14814    return SDValue();
14815
14816  EVT VT = InVec.getValueType();
14817
14818  bool HasShuffleIntoBitcast = false;
14819  if (InVec.getOpcode() == ISD::BITCAST) {
14820    // Don't duplicate a load with other uses.
14821    if (!InVec.hasOneUse())
14822      return SDValue();
14823    EVT BCVT = InVec.getOperand(0).getValueType();
14824    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14825      return SDValue();
14826    InVec = InVec.getOperand(0);
14827    HasShuffleIntoBitcast = true;
14828  }
14829
14830  if (!isTargetShuffle(InVec.getOpcode()))
14831    return SDValue();
14832
14833  // Don't duplicate a load with other uses.
14834  if (!InVec.hasOneUse())
14835    return SDValue();
14836
14837  SmallVector<int, 16> ShuffleMask;
14838  bool UnaryShuffle;
14839  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14840                            UnaryShuffle))
14841    return SDValue();
14842
14843  // Select the input vector, guarding against out of range extract vector.
14844  unsigned NumElems = VT.getVectorNumElements();
14845  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14846  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14847  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14848                                         : InVec.getOperand(1);
14849
14850  // If inputs to shuffle are the same for both ops, then allow 2 uses
14851  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14852
14853  if (LdNode.getOpcode() == ISD::BITCAST) {
14854    // Don't duplicate a load with other uses.
14855    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14856      return SDValue();
14857
14858    AllowedUses = 1; // only allow 1 load use if we have a bitcast
14859    LdNode = LdNode.getOperand(0);
14860  }
14861
14862  if (!ISD::isNormalLoad(LdNode.getNode()))
14863    return SDValue();
14864
14865  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14866
14867  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14868    return SDValue();
14869
14870  if (HasShuffleIntoBitcast) {
14871    // If there's a bitcast before the shuffle, check if the load type and
14872    // alignment is valid.
14873    unsigned Align = LN0->getAlignment();
14874    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14875    unsigned NewAlign = TLI.getDataLayout()->
14876      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14877
14878    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14879      return SDValue();
14880  }
14881
14882  // All checks match so transform back to vector_shuffle so that DAG combiner
14883  // can finish the job
14884  DebugLoc dl = N->getDebugLoc();
14885
14886  // Create shuffle node taking into account the case that its a unary shuffle
14887  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14888  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14889                                 InVec.getOperand(0), Shuffle,
14890                                 &ShuffleMask[0]);
14891  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14892  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14893                     EltNo);
14894}
14895
14896/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14897/// generation and convert it from being a bunch of shuffles and extracts
14898/// to a simple store and scalar loads to extract the elements.
14899static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14900                                         TargetLowering::DAGCombinerInfo &DCI) {
14901  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14902  if (NewOp.getNode())
14903    return NewOp;
14904
14905  SDValue InputVector = N->getOperand(0);
14906  // Detect whether we are trying to convert from mmx to i32 and the bitcast
14907  // from mmx to v2i32 has a single usage.
14908  if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14909      InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14910      InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14911    return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14912                       N->getValueType(0),
14913                       InputVector.getNode()->getOperand(0));
14914
14915  // Only operate on vectors of 4 elements, where the alternative shuffling
14916  // gets to be more expensive.
14917  if (InputVector.getValueType() != MVT::v4i32)
14918    return SDValue();
14919
14920  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14921  // single use which is a sign-extend or zero-extend, and all elements are
14922  // used.
14923  SmallVector<SDNode *, 4> Uses;
14924  unsigned ExtractedElements = 0;
14925  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14926       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14927    if (UI.getUse().getResNo() != InputVector.getResNo())
14928      return SDValue();
14929
14930    SDNode *Extract = *UI;
14931    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14932      return SDValue();
14933
14934    if (Extract->getValueType(0) != MVT::i32)
14935      return SDValue();
14936    if (!Extract->hasOneUse())
14937      return SDValue();
14938    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14939        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14940      return SDValue();
14941    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14942      return SDValue();
14943
14944    // Record which element was extracted.
14945    ExtractedElements |=
14946      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14947
14948    Uses.push_back(Extract);
14949  }
14950
14951  // If not all the elements were used, this may not be worthwhile.
14952  if (ExtractedElements != 15)
14953    return SDValue();
14954
14955  // Ok, we've now decided to do the transformation.
14956  DebugLoc dl = InputVector.getDebugLoc();
14957
14958  // Store the value to a temporary stack slot.
14959  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14960  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14961                            MachinePointerInfo(), false, false, 0);
14962
14963  // Replace each use (extract) with a load of the appropriate element.
14964  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14965       UE = Uses.end(); UI != UE; ++UI) {
14966    SDNode *Extract = *UI;
14967
14968    // cOMpute the element's address.
14969    SDValue Idx = Extract->getOperand(1);
14970    unsigned EltSize =
14971        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14972    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14973    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14974    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14975
14976    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14977                                     StackPtr, OffsetVal);
14978
14979    // Load the scalar.
14980    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14981                                     ScalarAddr, MachinePointerInfo(),
14982                                     false, false, false, 0);
14983
14984    // Replace the exact with the load.
14985    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14986  }
14987
14988  // The replacement was made in place; don't return anything.
14989  return SDValue();
14990}
14991
14992/// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14993static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14994                                   SDValue RHS, SelectionDAG &DAG,
14995                                   const X86Subtarget *Subtarget) {
14996  if (!VT.isVector())
14997    return 0;
14998
14999  switch (VT.getSimpleVT().SimpleTy) {
15000  default: return 0;
15001  case MVT::v32i8:
15002  case MVT::v16i16:
15003  case MVT::v8i32:
15004    if (!Subtarget->hasAVX2())
15005      return 0;
15006  case MVT::v16i8:
15007  case MVT::v8i16:
15008  case MVT::v4i32:
15009    if (!Subtarget->hasSSE2())
15010      return 0;
15011  }
15012
15013  // SSE2 has only a small subset of the operations.
15014  bool hasUnsigned = Subtarget->hasSSE41() ||
15015                     (Subtarget->hasSSE2() && VT == MVT::v16i8);
15016  bool hasSigned = Subtarget->hasSSE41() ||
15017                   (Subtarget->hasSSE2() && VT == MVT::v8i16);
15018
15019  ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15020
15021  // Check for x CC y ? x : y.
15022  if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15023      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15024    switch (CC) {
15025    default: break;
15026    case ISD::SETULT:
15027    case ISD::SETULE:
15028      return hasUnsigned ? X86ISD::UMIN : 0;
15029    case ISD::SETUGT:
15030    case ISD::SETUGE:
15031      return hasUnsigned ? X86ISD::UMAX : 0;
15032    case ISD::SETLT:
15033    case ISD::SETLE:
15034      return hasSigned ? X86ISD::SMIN : 0;
15035    case ISD::SETGT:
15036    case ISD::SETGE:
15037      return hasSigned ? X86ISD::SMAX : 0;
15038    }
15039  // Check for x CC y ? y : x -- a min/max with reversed arms.
15040  } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15041             DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15042    switch (CC) {
15043    default: break;
15044    case ISD::SETULT:
15045    case ISD::SETULE:
15046      return hasUnsigned ? X86ISD::UMAX : 0;
15047    case ISD::SETUGT:
15048    case ISD::SETUGE:
15049      return hasUnsigned ? X86ISD::UMIN : 0;
15050    case ISD::SETLT:
15051    case ISD::SETLE:
15052      return hasSigned ? X86ISD::SMAX : 0;
15053    case ISD::SETGT:
15054    case ISD::SETGE:
15055      return hasSigned ? X86ISD::SMIN : 0;
15056    }
15057  }
15058
15059  return 0;
15060}
15061
15062/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15063/// nodes.
15064static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15065                                    TargetLowering::DAGCombinerInfo &DCI,
15066                                    const X86Subtarget *Subtarget) {
15067  DebugLoc DL = N->getDebugLoc();
15068  SDValue Cond = N->getOperand(0);
15069  // Get the LHS/RHS of the select.
15070  SDValue LHS = N->getOperand(1);
15071  SDValue RHS = N->getOperand(2);
15072  EVT VT = LHS.getValueType();
15073
15074  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15075  // instructions match the semantics of the common C idiom x<y?x:y but not
15076  // x<=y?x:y, because of how they handle negative zero (which can be
15077  // ignored in unsafe-math mode).
15078  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15079      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15080      (Subtarget->hasSSE2() ||
15081       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15082    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15083
15084    unsigned Opcode = 0;
15085    // Check for x CC y ? x : y.
15086    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15087        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15088      switch (CC) {
15089      default: break;
15090      case ISD::SETULT:
15091        // Converting this to a min would handle NaNs incorrectly, and swapping
15092        // the operands would cause it to handle comparisons between positive
15093        // and negative zero incorrectly.
15094        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15095          if (!DAG.getTarget().Options.UnsafeFPMath &&
15096              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15097            break;
15098          std::swap(LHS, RHS);
15099        }
15100        Opcode = X86ISD::FMIN;
15101        break;
15102      case ISD::SETOLE:
15103        // Converting this to a min would handle comparisons between positive
15104        // and negative zero incorrectly.
15105        if (!DAG.getTarget().Options.UnsafeFPMath &&
15106            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15107          break;
15108        Opcode = X86ISD::FMIN;
15109        break;
15110      case ISD::SETULE:
15111        // Converting this to a min would handle both negative zeros and NaNs
15112        // incorrectly, but we can swap the operands to fix both.
15113        std::swap(LHS, RHS);
15114      case ISD::SETOLT:
15115      case ISD::SETLT:
15116      case ISD::SETLE:
15117        Opcode = X86ISD::FMIN;
15118        break;
15119
15120      case ISD::SETOGE:
15121        // Converting this to a max would handle comparisons between positive
15122        // and negative zero incorrectly.
15123        if (!DAG.getTarget().Options.UnsafeFPMath &&
15124            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15125          break;
15126        Opcode = X86ISD::FMAX;
15127        break;
15128      case ISD::SETUGT:
15129        // Converting this to a max would handle NaNs incorrectly, and swapping
15130        // the operands would cause it to handle comparisons between positive
15131        // and negative zero incorrectly.
15132        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15133          if (!DAG.getTarget().Options.UnsafeFPMath &&
15134              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15135            break;
15136          std::swap(LHS, RHS);
15137        }
15138        Opcode = X86ISD::FMAX;
15139        break;
15140      case ISD::SETUGE:
15141        // Converting this to a max would handle both negative zeros and NaNs
15142        // incorrectly, but we can swap the operands to fix both.
15143        std::swap(LHS, RHS);
15144      case ISD::SETOGT:
15145      case ISD::SETGT:
15146      case ISD::SETGE:
15147        Opcode = X86ISD::FMAX;
15148        break;
15149      }
15150    // Check for x CC y ? y : x -- a min/max with reversed arms.
15151    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15152               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15153      switch (CC) {
15154      default: break;
15155      case ISD::SETOGE:
15156        // Converting this to a min would handle comparisons between positive
15157        // and negative zero incorrectly, and swapping the operands would
15158        // cause it to handle NaNs incorrectly.
15159        if (!DAG.getTarget().Options.UnsafeFPMath &&
15160            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15161          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15162            break;
15163          std::swap(LHS, RHS);
15164        }
15165        Opcode = X86ISD::FMIN;
15166        break;
15167      case ISD::SETUGT:
15168        // Converting this to a min would handle NaNs incorrectly.
15169        if (!DAG.getTarget().Options.UnsafeFPMath &&
15170            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15171          break;
15172        Opcode = X86ISD::FMIN;
15173        break;
15174      case ISD::SETUGE:
15175        // Converting this to a min would handle both negative zeros and NaNs
15176        // incorrectly, but we can swap the operands to fix both.
15177        std::swap(LHS, RHS);
15178      case ISD::SETOGT:
15179      case ISD::SETGT:
15180      case ISD::SETGE:
15181        Opcode = X86ISD::FMIN;
15182        break;
15183
15184      case ISD::SETULT:
15185        // Converting this to a max would handle NaNs incorrectly.
15186        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15187          break;
15188        Opcode = X86ISD::FMAX;
15189        break;
15190      case ISD::SETOLE:
15191        // Converting this to a max would handle comparisons between positive
15192        // and negative zero incorrectly, and swapping the operands would
15193        // cause it to handle NaNs incorrectly.
15194        if (!DAG.getTarget().Options.UnsafeFPMath &&
15195            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15196          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15197            break;
15198          std::swap(LHS, RHS);
15199        }
15200        Opcode = X86ISD::FMAX;
15201        break;
15202      case ISD::SETULE:
15203        // Converting this to a max would handle both negative zeros and NaNs
15204        // incorrectly, but we can swap the operands to fix both.
15205        std::swap(LHS, RHS);
15206      case ISD::SETOLT:
15207      case ISD::SETLT:
15208      case ISD::SETLE:
15209        Opcode = X86ISD::FMAX;
15210        break;
15211      }
15212    }
15213
15214    if (Opcode)
15215      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15216  }
15217
15218  // If this is a select between two integer constants, try to do some
15219  // optimizations.
15220  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15221    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15222      // Don't do this for crazy integer types.
15223      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15224        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15225        // so that TrueC (the true value) is larger than FalseC.
15226        bool NeedsCondInvert = false;
15227
15228        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15229            // Efficiently invertible.
15230            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15231             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15232              isa<ConstantSDNode>(Cond.getOperand(1))))) {
15233          NeedsCondInvert = true;
15234          std::swap(TrueC, FalseC);
15235        }
15236
15237        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15238        if (FalseC->getAPIntValue() == 0 &&
15239            TrueC->getAPIntValue().isPowerOf2()) {
15240          if (NeedsCondInvert) // Invert the condition if needed.
15241            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15242                               DAG.getConstant(1, Cond.getValueType()));
15243
15244          // Zero extend the condition if needed.
15245          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15246
15247          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15248          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15249                             DAG.getConstant(ShAmt, MVT::i8));
15250        }
15251
15252        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15253        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15254          if (NeedsCondInvert) // Invert the condition if needed.
15255            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15256                               DAG.getConstant(1, Cond.getValueType()));
15257
15258          // Zero extend the condition if needed.
15259          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15260                             FalseC->getValueType(0), Cond);
15261          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15262                             SDValue(FalseC, 0));
15263        }
15264
15265        // Optimize cases that will turn into an LEA instruction.  This requires
15266        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15267        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15268          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15269          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15270
15271          bool isFastMultiplier = false;
15272          if (Diff < 10) {
15273            switch ((unsigned char)Diff) {
15274              default: break;
15275              case 1:  // result = add base, cond
15276              case 2:  // result = lea base(    , cond*2)
15277              case 3:  // result = lea base(cond, cond*2)
15278              case 4:  // result = lea base(    , cond*4)
15279              case 5:  // result = lea base(cond, cond*4)
15280              case 8:  // result = lea base(    , cond*8)
15281              case 9:  // result = lea base(cond, cond*8)
15282                isFastMultiplier = true;
15283                break;
15284            }
15285          }
15286
15287          if (isFastMultiplier) {
15288            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15289            if (NeedsCondInvert) // Invert the condition if needed.
15290              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15291                                 DAG.getConstant(1, Cond.getValueType()));
15292
15293            // Zero extend the condition if needed.
15294            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15295                               Cond);
15296            // Scale the condition by the difference.
15297            if (Diff != 1)
15298              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15299                                 DAG.getConstant(Diff, Cond.getValueType()));
15300
15301            // Add the base if non-zero.
15302            if (FalseC->getAPIntValue() != 0)
15303              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15304                                 SDValue(FalseC, 0));
15305            return Cond;
15306          }
15307        }
15308      }
15309  }
15310
15311  // Canonicalize max and min:
15312  // (x > y) ? x : y -> (x >= y) ? x : y
15313  // (x < y) ? x : y -> (x <= y) ? x : y
15314  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15315  // the need for an extra compare
15316  // against zero. e.g.
15317  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15318  // subl   %esi, %edi
15319  // testl  %edi, %edi
15320  // movl   $0, %eax
15321  // cmovgl %edi, %eax
15322  // =>
15323  // xorl   %eax, %eax
15324  // subl   %esi, $edi
15325  // cmovsl %eax, %edi
15326  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15327      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15328      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15329    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15330    switch (CC) {
15331    default: break;
15332    case ISD::SETLT:
15333    case ISD::SETGT: {
15334      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15335      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15336                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
15337      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15338    }
15339    }
15340  }
15341
15342  // Match VSELECTs into subs with unsigned saturation.
15343  if (!DCI.isBeforeLegalize() &&
15344      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15345      // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15346      ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15347       (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15348    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15349
15350    // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15351    // left side invert the predicate to simplify logic below.
15352    SDValue Other;
15353    if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15354      Other = RHS;
15355      CC = ISD::getSetCCInverse(CC, true);
15356    } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15357      Other = LHS;
15358    }
15359
15360    if (Other.getNode() && Other->getNumOperands() == 2 &&
15361        DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15362      SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15363      SDValue CondRHS = Cond->getOperand(1);
15364
15365      // Look for a general sub with unsigned saturation first.
15366      // x >= y ? x-y : 0 --> subus x, y
15367      // x >  y ? x-y : 0 --> subus x, y
15368      if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15369          Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15370        return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15371
15372      // If the RHS is a constant we have to reverse the const canonicalization.
15373      // x > C-1 ? x+-C : 0 --> subus x, C
15374      if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15375          isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15376        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15377        if (CondRHS.getConstantOperandVal(0) == -A-1)
15378          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15379                             DAG.getConstant(-A, VT));
15380      }
15381
15382      // Another special case: If C was a sign bit, the sub has been
15383      // canonicalized into a xor.
15384      // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15385      //        it's safe to decanonicalize the xor?
15386      // x s< 0 ? x^C : 0 --> subus x, C
15387      if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15388          ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15389          isSplatVector(OpRHS.getNode())) {
15390        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15391        if (A.isSignBit())
15392          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15393      }
15394    }
15395  }
15396
15397  // Try to match a min/max vector operation.
15398  if (!DCI.isBeforeLegalize() &&
15399      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15400    if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15401      return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15402
15403  // If we know that this node is legal then we know that it is going to be
15404  // matched by one of the SSE/AVX BLEND instructions. These instructions only
15405  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15406  // to simplify previous instructions.
15407  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15408  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15409      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15410    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15411
15412    // Don't optimize vector selects that map to mask-registers.
15413    if (BitWidth == 1)
15414      return SDValue();
15415
15416    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15417    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15418
15419    APInt KnownZero, KnownOne;
15420    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15421                                          DCI.isBeforeLegalizeOps());
15422    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15423        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15424      DCI.CommitTargetLoweringOpt(TLO);
15425  }
15426
15427  return SDValue();
15428}
15429
15430// Check whether a boolean test is testing a boolean value generated by
15431// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15432// code.
15433//
15434// Simplify the following patterns:
15435// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15436// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15437// to (Op EFLAGS Cond)
15438//
15439// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15440// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15441// to (Op EFLAGS !Cond)
15442//
15443// where Op could be BRCOND or CMOV.
15444//
15445static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15446  // Quit if not CMP and SUB with its value result used.
15447  if (Cmp.getOpcode() != X86ISD::CMP &&
15448      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15449      return SDValue();
15450
15451  // Quit if not used as a boolean value.
15452  if (CC != X86::COND_E && CC != X86::COND_NE)
15453    return SDValue();
15454
15455  // Check CMP operands. One of them should be 0 or 1 and the other should be
15456  // an SetCC or extended from it.
15457  SDValue Op1 = Cmp.getOperand(0);
15458  SDValue Op2 = Cmp.getOperand(1);
15459
15460  SDValue SetCC;
15461  const ConstantSDNode* C = 0;
15462  bool needOppositeCond = (CC == X86::COND_E);
15463
15464  if ((C = dyn_cast<ConstantSDNode>(Op1)))
15465    SetCC = Op2;
15466  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15467    SetCC = Op1;
15468  else // Quit if all operands are not constants.
15469    return SDValue();
15470
15471  if (C->getZExtValue() == 1)
15472    needOppositeCond = !needOppositeCond;
15473  else if (C->getZExtValue() != 0)
15474    // Quit if the constant is neither 0 or 1.
15475    return SDValue();
15476
15477  // Skip 'zext' node.
15478  if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15479    SetCC = SetCC.getOperand(0);
15480
15481  switch (SetCC.getOpcode()) {
15482  case X86ISD::SETCC:
15483    // Set the condition code or opposite one if necessary.
15484    CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15485    if (needOppositeCond)
15486      CC = X86::GetOppositeBranchCondition(CC);
15487    return SetCC.getOperand(1);
15488  case X86ISD::CMOV: {
15489    // Check whether false/true value has canonical one, i.e. 0 or 1.
15490    ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15491    ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15492    // Quit if true value is not a constant.
15493    if (!TVal)
15494      return SDValue();
15495    // Quit if false value is not a constant.
15496    if (!FVal) {
15497      // A special case for rdrand, where 0 is set if false cond is found.
15498      SDValue Op = SetCC.getOperand(0);
15499      if (Op.getOpcode() != X86ISD::RDRAND)
15500        return SDValue();
15501    }
15502    // Quit if false value is not the constant 0 or 1.
15503    bool FValIsFalse = true;
15504    if (FVal && FVal->getZExtValue() != 0) {
15505      if (FVal->getZExtValue() != 1)
15506        return SDValue();
15507      // If FVal is 1, opposite cond is needed.
15508      needOppositeCond = !needOppositeCond;
15509      FValIsFalse = false;
15510    }
15511    // Quit if TVal is not the constant opposite of FVal.
15512    if (FValIsFalse && TVal->getZExtValue() != 1)
15513      return SDValue();
15514    if (!FValIsFalse && TVal->getZExtValue() != 0)
15515      return SDValue();
15516    CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15517    if (needOppositeCond)
15518      CC = X86::GetOppositeBranchCondition(CC);
15519    return SetCC.getOperand(3);
15520  }
15521  }
15522
15523  return SDValue();
15524}
15525
15526/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15527static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15528                                  TargetLowering::DAGCombinerInfo &DCI,
15529                                  const X86Subtarget *Subtarget) {
15530  DebugLoc DL = N->getDebugLoc();
15531
15532  // If the flag operand isn't dead, don't touch this CMOV.
15533  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15534    return SDValue();
15535
15536  SDValue FalseOp = N->getOperand(0);
15537  SDValue TrueOp = N->getOperand(1);
15538  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15539  SDValue Cond = N->getOperand(3);
15540
15541  if (CC == X86::COND_E || CC == X86::COND_NE) {
15542    switch (Cond.getOpcode()) {
15543    default: break;
15544    case X86ISD::BSR:
15545    case X86ISD::BSF:
15546      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15547      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15548        return (CC == X86::COND_E) ? FalseOp : TrueOp;
15549    }
15550  }
15551
15552  SDValue Flags;
15553
15554  Flags = checkBoolTestSetCCCombine(Cond, CC);
15555  if (Flags.getNode() &&
15556      // Extra check as FCMOV only supports a subset of X86 cond.
15557      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15558    SDValue Ops[] = { FalseOp, TrueOp,
15559                      DAG.getConstant(CC, MVT::i8), Flags };
15560    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15561                       Ops, array_lengthof(Ops));
15562  }
15563
15564  // If this is a select between two integer constants, try to do some
15565  // optimizations.  Note that the operands are ordered the opposite of SELECT
15566  // operands.
15567  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15568    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15569      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15570      // larger than FalseC (the false value).
15571      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15572        CC = X86::GetOppositeBranchCondition(CC);
15573        std::swap(TrueC, FalseC);
15574        std::swap(TrueOp, FalseOp);
15575      }
15576
15577      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15578      // This is efficient for any integer data type (including i8/i16) and
15579      // shift amount.
15580      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15581        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15582                           DAG.getConstant(CC, MVT::i8), Cond);
15583
15584        // Zero extend the condition if needed.
15585        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15586
15587        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15588        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15589                           DAG.getConstant(ShAmt, MVT::i8));
15590        if (N->getNumValues() == 2)  // Dead flag value?
15591          return DCI.CombineTo(N, Cond, SDValue());
15592        return Cond;
15593      }
15594
15595      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15596      // for any integer data type, including i8/i16.
15597      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15598        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15599                           DAG.getConstant(CC, MVT::i8), Cond);
15600
15601        // Zero extend the condition if needed.
15602        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15603                           FalseC->getValueType(0), Cond);
15604        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15605                           SDValue(FalseC, 0));
15606
15607        if (N->getNumValues() == 2)  // Dead flag value?
15608          return DCI.CombineTo(N, Cond, SDValue());
15609        return Cond;
15610      }
15611
15612      // Optimize cases that will turn into an LEA instruction.  This requires
15613      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15614      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15615        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15616        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15617
15618        bool isFastMultiplier = false;
15619        if (Diff < 10) {
15620          switch ((unsigned char)Diff) {
15621          default: break;
15622          case 1:  // result = add base, cond
15623          case 2:  // result = lea base(    , cond*2)
15624          case 3:  // result = lea base(cond, cond*2)
15625          case 4:  // result = lea base(    , cond*4)
15626          case 5:  // result = lea base(cond, cond*4)
15627          case 8:  // result = lea base(    , cond*8)
15628          case 9:  // result = lea base(cond, cond*8)
15629            isFastMultiplier = true;
15630            break;
15631          }
15632        }
15633
15634        if (isFastMultiplier) {
15635          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15636          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15637                             DAG.getConstant(CC, MVT::i8), Cond);
15638          // Zero extend the condition if needed.
15639          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15640                             Cond);
15641          // Scale the condition by the difference.
15642          if (Diff != 1)
15643            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15644                               DAG.getConstant(Diff, Cond.getValueType()));
15645
15646          // Add the base if non-zero.
15647          if (FalseC->getAPIntValue() != 0)
15648            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15649                               SDValue(FalseC, 0));
15650          if (N->getNumValues() == 2)  // Dead flag value?
15651            return DCI.CombineTo(N, Cond, SDValue());
15652          return Cond;
15653        }
15654      }
15655    }
15656  }
15657
15658  // Handle these cases:
15659  //   (select (x != c), e, c) -> select (x != c), e, x),
15660  //   (select (x == c), c, e) -> select (x == c), x, e)
15661  // where the c is an integer constant, and the "select" is the combination
15662  // of CMOV and CMP.
15663  //
15664  // The rationale for this change is that the conditional-move from a constant
15665  // needs two instructions, however, conditional-move from a register needs
15666  // only one instruction.
15667  //
15668  // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15669  //  some instruction-combining opportunities. This opt needs to be
15670  //  postponed as late as possible.
15671  //
15672  if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15673    // the DCI.xxxx conditions are provided to postpone the optimization as
15674    // late as possible.
15675
15676    ConstantSDNode *CmpAgainst = 0;
15677    if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15678        (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15679        !isa<ConstantSDNode>(Cond.getOperand(0))) {
15680
15681      if (CC == X86::COND_NE &&
15682          CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15683        CC = X86::GetOppositeBranchCondition(CC);
15684        std::swap(TrueOp, FalseOp);
15685      }
15686
15687      if (CC == X86::COND_E &&
15688          CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15689        SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15690                          DAG.getConstant(CC, MVT::i8), Cond };
15691        return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15692                           array_lengthof(Ops));
15693      }
15694    }
15695  }
15696
15697  return SDValue();
15698}
15699
15700/// PerformMulCombine - Optimize a single multiply with constant into two
15701/// in order to implement it with two cheaper instructions, e.g.
15702/// LEA + SHL, LEA + LEA.
15703static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15704                                 TargetLowering::DAGCombinerInfo &DCI) {
15705  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15706    return SDValue();
15707
15708  EVT VT = N->getValueType(0);
15709  if (VT != MVT::i64)
15710    return SDValue();
15711
15712  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15713  if (!C)
15714    return SDValue();
15715  uint64_t MulAmt = C->getZExtValue();
15716  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15717    return SDValue();
15718
15719  uint64_t MulAmt1 = 0;
15720  uint64_t MulAmt2 = 0;
15721  if ((MulAmt % 9) == 0) {
15722    MulAmt1 = 9;
15723    MulAmt2 = MulAmt / 9;
15724  } else if ((MulAmt % 5) == 0) {
15725    MulAmt1 = 5;
15726    MulAmt2 = MulAmt / 5;
15727  } else if ((MulAmt % 3) == 0) {
15728    MulAmt1 = 3;
15729    MulAmt2 = MulAmt / 3;
15730  }
15731  if (MulAmt2 &&
15732      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15733    DebugLoc DL = N->getDebugLoc();
15734
15735    if (isPowerOf2_64(MulAmt2) &&
15736        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15737      // If second multiplifer is pow2, issue it first. We want the multiply by
15738      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15739      // is an add.
15740      std::swap(MulAmt1, MulAmt2);
15741
15742    SDValue NewMul;
15743    if (isPowerOf2_64(MulAmt1))
15744      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15745                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15746    else
15747      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15748                           DAG.getConstant(MulAmt1, VT));
15749
15750    if (isPowerOf2_64(MulAmt2))
15751      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15752                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15753    else
15754      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15755                           DAG.getConstant(MulAmt2, VT));
15756
15757    // Do not add new nodes to DAG combiner worklist.
15758    DCI.CombineTo(N, NewMul, false);
15759  }
15760  return SDValue();
15761}
15762
15763static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15764  SDValue N0 = N->getOperand(0);
15765  SDValue N1 = N->getOperand(1);
15766  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15767  EVT VT = N0.getValueType();
15768
15769  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15770  // since the result of setcc_c is all zero's or all ones.
15771  if (VT.isInteger() && !VT.isVector() &&
15772      N1C && N0.getOpcode() == ISD::AND &&
15773      N0.getOperand(1).getOpcode() == ISD::Constant) {
15774    SDValue N00 = N0.getOperand(0);
15775    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15776        ((N00.getOpcode() == ISD::ANY_EXTEND ||
15777          N00.getOpcode() == ISD::ZERO_EXTEND) &&
15778         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15779      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15780      APInt ShAmt = N1C->getAPIntValue();
15781      Mask = Mask.shl(ShAmt);
15782      if (Mask != 0)
15783        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15784                           N00, DAG.getConstant(Mask, VT));
15785    }
15786  }
15787
15788  // Hardware support for vector shifts is sparse which makes us scalarize the
15789  // vector operations in many cases. Also, on sandybridge ADD is faster than
15790  // shl.
15791  // (shl V, 1) -> add V,V
15792  if (isSplatVector(N1.getNode())) {
15793    assert(N0.getValueType().isVector() && "Invalid vector shift type");
15794    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15795    // We shift all of the values by one. In many cases we do not have
15796    // hardware support for this operation. This is better expressed as an ADD
15797    // of two values.
15798    if (N1C && (1 == N1C->getZExtValue())) {
15799      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15800    }
15801  }
15802
15803  return SDValue();
15804}
15805
15806/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15807///                       when possible.
15808static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15809                                   TargetLowering::DAGCombinerInfo &DCI,
15810                                   const X86Subtarget *Subtarget) {
15811  EVT VT = N->getValueType(0);
15812  if (N->getOpcode() == ISD::SHL) {
15813    SDValue V = PerformSHLCombine(N, DAG);
15814    if (V.getNode()) return V;
15815  }
15816
15817  // On X86 with SSE2 support, we can transform this to a vector shift if
15818  // all elements are shifted by the same amount.  We can't do this in legalize
15819  // because the a constant vector is typically transformed to a constant pool
15820  // so we have no knowledge of the shift amount.
15821  if (!Subtarget->hasSSE2())
15822    return SDValue();
15823
15824  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15825      (!Subtarget->hasInt256() ||
15826       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15827    return SDValue();
15828
15829  SDValue ShAmtOp = N->getOperand(1);
15830  EVT EltVT = VT.getVectorElementType();
15831  DebugLoc DL = N->getDebugLoc();
15832  SDValue BaseShAmt = SDValue();
15833  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15834    unsigned NumElts = VT.getVectorNumElements();
15835    unsigned i = 0;
15836    for (; i != NumElts; ++i) {
15837      SDValue Arg = ShAmtOp.getOperand(i);
15838      if (Arg.getOpcode() == ISD::UNDEF) continue;
15839      BaseShAmt = Arg;
15840      break;
15841    }
15842    // Handle the case where the build_vector is all undef
15843    // FIXME: Should DAG allow this?
15844    if (i == NumElts)
15845      return SDValue();
15846
15847    for (; i != NumElts; ++i) {
15848      SDValue Arg = ShAmtOp.getOperand(i);
15849      if (Arg.getOpcode() == ISD::UNDEF) continue;
15850      if (Arg != BaseShAmt) {
15851        return SDValue();
15852      }
15853    }
15854  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15855             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15856    SDValue InVec = ShAmtOp.getOperand(0);
15857    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15858      unsigned NumElts = InVec.getValueType().getVectorNumElements();
15859      unsigned i = 0;
15860      for (; i != NumElts; ++i) {
15861        SDValue Arg = InVec.getOperand(i);
15862        if (Arg.getOpcode() == ISD::UNDEF) continue;
15863        BaseShAmt = Arg;
15864        break;
15865      }
15866    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15867       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15868         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15869         if (C->getZExtValue() == SplatIdx)
15870           BaseShAmt = InVec.getOperand(1);
15871       }
15872    }
15873    if (BaseShAmt.getNode() == 0) {
15874      // Don't create instructions with illegal types after legalize
15875      // types has run.
15876      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15877          !DCI.isBeforeLegalize())
15878        return SDValue();
15879
15880      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15881                              DAG.getIntPtrConstant(0));
15882    }
15883  } else
15884    return SDValue();
15885
15886  // The shift amount is an i32.
15887  if (EltVT.bitsGT(MVT::i32))
15888    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15889  else if (EltVT.bitsLT(MVT::i32))
15890    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15891
15892  // The shift amount is identical so we can do a vector shift.
15893  SDValue  ValOp = N->getOperand(0);
15894  switch (N->getOpcode()) {
15895  default:
15896    llvm_unreachable("Unknown shift opcode!");
15897  case ISD::SHL:
15898    switch (VT.getSimpleVT().SimpleTy) {
15899    default: return SDValue();
15900    case MVT::v2i64:
15901    case MVT::v4i32:
15902    case MVT::v8i16:
15903    case MVT::v4i64:
15904    case MVT::v8i32:
15905    case MVT::v16i16:
15906      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15907    }
15908  case ISD::SRA:
15909    switch (VT.getSimpleVT().SimpleTy) {
15910    default: return SDValue();
15911    case MVT::v4i32:
15912    case MVT::v8i16:
15913    case MVT::v8i32:
15914    case MVT::v16i16:
15915      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15916    }
15917  case ISD::SRL:
15918    switch (VT.getSimpleVT().SimpleTy) {
15919    default: return SDValue();
15920    case MVT::v2i64:
15921    case MVT::v4i32:
15922    case MVT::v8i16:
15923    case MVT::v4i64:
15924    case MVT::v8i32:
15925    case MVT::v16i16:
15926      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15927    }
15928  }
15929}
15930
15931// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15932// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15933// and friends.  Likewise for OR -> CMPNEQSS.
15934static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15935                            TargetLowering::DAGCombinerInfo &DCI,
15936                            const X86Subtarget *Subtarget) {
15937  unsigned opcode;
15938
15939  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15940  // we're requiring SSE2 for both.
15941  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15942    SDValue N0 = N->getOperand(0);
15943    SDValue N1 = N->getOperand(1);
15944    SDValue CMP0 = N0->getOperand(1);
15945    SDValue CMP1 = N1->getOperand(1);
15946    DebugLoc DL = N->getDebugLoc();
15947
15948    // The SETCCs should both refer to the same CMP.
15949    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15950      return SDValue();
15951
15952    SDValue CMP00 = CMP0->getOperand(0);
15953    SDValue CMP01 = CMP0->getOperand(1);
15954    EVT     VT    = CMP00.getValueType();
15955
15956    if (VT == MVT::f32 || VT == MVT::f64) {
15957      bool ExpectingFlags = false;
15958      // Check for any users that want flags:
15959      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
15960           !ExpectingFlags && UI != UE; ++UI)
15961        switch (UI->getOpcode()) {
15962        default:
15963        case ISD::BR_CC:
15964        case ISD::BRCOND:
15965        case ISD::SELECT:
15966          ExpectingFlags = true;
15967          break;
15968        case ISD::CopyToReg:
15969        case ISD::SIGN_EXTEND:
15970        case ISD::ZERO_EXTEND:
15971        case ISD::ANY_EXTEND:
15972          break;
15973        }
15974
15975      if (!ExpectingFlags) {
15976        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15977        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15978
15979        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15980          X86::CondCode tmp = cc0;
15981          cc0 = cc1;
15982          cc1 = tmp;
15983        }
15984
15985        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15986            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15987          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15988          X86ISD::NodeType NTOperator = is64BitFP ?
15989            X86ISD::FSETCCsd : X86ISD::FSETCCss;
15990          // FIXME: need symbolic constants for these magic numbers.
15991          // See X86ATTInstPrinter.cpp:printSSECC().
15992          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15993          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15994                                              DAG.getConstant(x86cc, MVT::i8));
15995          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15996                                              OnesOrZeroesF);
15997          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15998                                      DAG.getConstant(1, MVT::i32));
15999          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16000          return OneBitOfTruth;
16001        }
16002      }
16003    }
16004  }
16005  return SDValue();
16006}
16007
16008/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16009/// so it can be folded inside ANDNP.
16010static bool CanFoldXORWithAllOnes(const SDNode *N) {
16011  EVT VT = N->getValueType(0);
16012
16013  // Match direct AllOnes for 128 and 256-bit vectors
16014  if (ISD::isBuildVectorAllOnes(N))
16015    return true;
16016
16017  // Look through a bit convert.
16018  if (N->getOpcode() == ISD::BITCAST)
16019    N = N->getOperand(0).getNode();
16020
16021  // Sometimes the operand may come from a insert_subvector building a 256-bit
16022  // allones vector
16023  if (VT.is256BitVector() &&
16024      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16025    SDValue V1 = N->getOperand(0);
16026    SDValue V2 = N->getOperand(1);
16027
16028    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16029        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16030        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16031        ISD::isBuildVectorAllOnes(V2.getNode()))
16032      return true;
16033  }
16034
16035  return false;
16036}
16037
16038// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16039// register. In most cases we actually compare or select YMM-sized registers
16040// and mixing the two types creates horrible code. This method optimizes
16041// some of the transition sequences.
16042static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16043                                 TargetLowering::DAGCombinerInfo &DCI,
16044                                 const X86Subtarget *Subtarget) {
16045  EVT VT = N->getValueType(0);
16046  if (!VT.is256BitVector())
16047    return SDValue();
16048
16049  assert((N->getOpcode() == ISD::ANY_EXTEND ||
16050          N->getOpcode() == ISD::ZERO_EXTEND ||
16051          N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16052
16053  SDValue Narrow = N->getOperand(0);
16054  EVT NarrowVT = Narrow->getValueType(0);
16055  if (!NarrowVT.is128BitVector())
16056    return SDValue();
16057
16058  if (Narrow->getOpcode() != ISD::XOR &&
16059      Narrow->getOpcode() != ISD::AND &&
16060      Narrow->getOpcode() != ISD::OR)
16061    return SDValue();
16062
16063  SDValue N0  = Narrow->getOperand(0);
16064  SDValue N1  = Narrow->getOperand(1);
16065  DebugLoc DL = Narrow->getDebugLoc();
16066
16067  // The Left side has to be a trunc.
16068  if (N0.getOpcode() != ISD::TRUNCATE)
16069    return SDValue();
16070
16071  // The type of the truncated inputs.
16072  EVT WideVT = N0->getOperand(0)->getValueType(0);
16073  if (WideVT != VT)
16074    return SDValue();
16075
16076  // The right side has to be a 'trunc' or a constant vector.
16077  bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16078  bool RHSConst = (isSplatVector(N1.getNode()) &&
16079                   isa<ConstantSDNode>(N1->getOperand(0)));
16080  if (!RHSTrunc && !RHSConst)
16081    return SDValue();
16082
16083  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16084
16085  if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16086    return SDValue();
16087
16088  // Set N0 and N1 to hold the inputs to the new wide operation.
16089  N0 = N0->getOperand(0);
16090  if (RHSConst) {
16091    N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16092                     N1->getOperand(0));
16093    SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16094    N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16095  } else if (RHSTrunc) {
16096    N1 = N1->getOperand(0);
16097  }
16098
16099  // Generate the wide operation.
16100  SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16101  unsigned Opcode = N->getOpcode();
16102  switch (Opcode) {
16103  case ISD::ANY_EXTEND:
16104    return Op;
16105  case ISD::ZERO_EXTEND: {
16106    unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16107    APInt Mask = APInt::getAllOnesValue(InBits);
16108    Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16109    return DAG.getNode(ISD::AND, DL, VT,
16110                       Op, DAG.getConstant(Mask, VT));
16111  }
16112  case ISD::SIGN_EXTEND:
16113    return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16114                       Op, DAG.getValueType(NarrowVT));
16115  default:
16116    llvm_unreachable("Unexpected opcode");
16117  }
16118}
16119
16120static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16121                                 TargetLowering::DAGCombinerInfo &DCI,
16122                                 const X86Subtarget *Subtarget) {
16123  EVT VT = N->getValueType(0);
16124  if (DCI.isBeforeLegalizeOps())
16125    return SDValue();
16126
16127  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16128  if (R.getNode())
16129    return R;
16130
16131  // Create BLSI, and BLSR instructions
16132  // BLSI is X & (-X)
16133  // BLSR is X & (X-1)
16134  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16135    SDValue N0 = N->getOperand(0);
16136    SDValue N1 = N->getOperand(1);
16137    DebugLoc DL = N->getDebugLoc();
16138
16139    // Check LHS for neg
16140    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16141        isZero(N0.getOperand(0)))
16142      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16143
16144    // Check RHS for neg
16145    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16146        isZero(N1.getOperand(0)))
16147      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16148
16149    // Check LHS for X-1
16150    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16151        isAllOnes(N0.getOperand(1)))
16152      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16153
16154    // Check RHS for X-1
16155    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16156        isAllOnes(N1.getOperand(1)))
16157      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16158
16159    return SDValue();
16160  }
16161
16162  // Want to form ANDNP nodes:
16163  // 1) In the hopes of then easily combining them with OR and AND nodes
16164  //    to form PBLEND/PSIGN.
16165  // 2) To match ANDN packed intrinsics
16166  if (VT != MVT::v2i64 && VT != MVT::v4i64)
16167    return SDValue();
16168
16169  SDValue N0 = N->getOperand(0);
16170  SDValue N1 = N->getOperand(1);
16171  DebugLoc DL = N->getDebugLoc();
16172
16173  // Check LHS for vnot
16174  if (N0.getOpcode() == ISD::XOR &&
16175      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16176      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16177    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16178
16179  // Check RHS for vnot
16180  if (N1.getOpcode() == ISD::XOR &&
16181      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16182      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16183    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16184
16185  return SDValue();
16186}
16187
16188static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16189                                TargetLowering::DAGCombinerInfo &DCI,
16190                                const X86Subtarget *Subtarget) {
16191  EVT VT = N->getValueType(0);
16192  if (DCI.isBeforeLegalizeOps())
16193    return SDValue();
16194
16195  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16196  if (R.getNode())
16197    return R;
16198
16199  SDValue N0 = N->getOperand(0);
16200  SDValue N1 = N->getOperand(1);
16201
16202  // look for psign/blend
16203  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16204    if (!Subtarget->hasSSSE3() ||
16205        (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16206      return SDValue();
16207
16208    // Canonicalize pandn to RHS
16209    if (N0.getOpcode() == X86ISD::ANDNP)
16210      std::swap(N0, N1);
16211    // or (and (m, y), (pandn m, x))
16212    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16213      SDValue Mask = N1.getOperand(0);
16214      SDValue X    = N1.getOperand(1);
16215      SDValue Y;
16216      if (N0.getOperand(0) == Mask)
16217        Y = N0.getOperand(1);
16218      if (N0.getOperand(1) == Mask)
16219        Y = N0.getOperand(0);
16220
16221      // Check to see if the mask appeared in both the AND and ANDNP and
16222      if (!Y.getNode())
16223        return SDValue();
16224
16225      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16226      // Look through mask bitcast.
16227      if (Mask.getOpcode() == ISD::BITCAST)
16228        Mask = Mask.getOperand(0);
16229      if (X.getOpcode() == ISD::BITCAST)
16230        X = X.getOperand(0);
16231      if (Y.getOpcode() == ISD::BITCAST)
16232        Y = Y.getOperand(0);
16233
16234      EVT MaskVT = Mask.getValueType();
16235
16236      // Validate that the Mask operand is a vector sra node.
16237      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16238      // there is no psrai.b
16239      if (Mask.getOpcode() != X86ISD::VSRAI)
16240        return SDValue();
16241
16242      // Check that the SRA is all signbits.
16243      SDValue SraC = Mask.getOperand(1);
16244      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16245      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16246      if ((SraAmt + 1) != EltBits)
16247        return SDValue();
16248
16249      DebugLoc DL = N->getDebugLoc();
16250
16251      // Now we know we at least have a plendvb with the mask val.  See if
16252      // we can form a psignb/w/d.
16253      // psign = x.type == y.type == mask.type && y = sub(0, x);
16254      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16255          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16256          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16257        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16258               "Unsupported VT for PSIGN");
16259        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16260        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16261      }
16262      // PBLENDVB only available on SSE 4.1
16263      if (!Subtarget->hasSSE41())
16264        return SDValue();
16265
16266      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16267
16268      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16269      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16270      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16271      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16272      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16273    }
16274  }
16275
16276  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16277    return SDValue();
16278
16279  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16280  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16281    std::swap(N0, N1);
16282  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16283    return SDValue();
16284  if (!N0.hasOneUse() || !N1.hasOneUse())
16285    return SDValue();
16286
16287  SDValue ShAmt0 = N0.getOperand(1);
16288  if (ShAmt0.getValueType() != MVT::i8)
16289    return SDValue();
16290  SDValue ShAmt1 = N1.getOperand(1);
16291  if (ShAmt1.getValueType() != MVT::i8)
16292    return SDValue();
16293  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16294    ShAmt0 = ShAmt0.getOperand(0);
16295  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16296    ShAmt1 = ShAmt1.getOperand(0);
16297
16298  DebugLoc DL = N->getDebugLoc();
16299  unsigned Opc = X86ISD::SHLD;
16300  SDValue Op0 = N0.getOperand(0);
16301  SDValue Op1 = N1.getOperand(0);
16302  if (ShAmt0.getOpcode() == ISD::SUB) {
16303    Opc = X86ISD::SHRD;
16304    std::swap(Op0, Op1);
16305    std::swap(ShAmt0, ShAmt1);
16306  }
16307
16308  unsigned Bits = VT.getSizeInBits();
16309  if (ShAmt1.getOpcode() == ISD::SUB) {
16310    SDValue Sum = ShAmt1.getOperand(0);
16311    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16312      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16313      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16314        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16315      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16316        return DAG.getNode(Opc, DL, VT,
16317                           Op0, Op1,
16318                           DAG.getNode(ISD::TRUNCATE, DL,
16319                                       MVT::i8, ShAmt0));
16320    }
16321  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16322    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16323    if (ShAmt0C &&
16324        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16325      return DAG.getNode(Opc, DL, VT,
16326                         N0.getOperand(0), N1.getOperand(0),
16327                         DAG.getNode(ISD::TRUNCATE, DL,
16328                                       MVT::i8, ShAmt0));
16329  }
16330
16331  return SDValue();
16332}
16333
16334// Generate NEG and CMOV for integer abs.
16335static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16336  EVT VT = N->getValueType(0);
16337
16338  // Since X86 does not have CMOV for 8-bit integer, we don't convert
16339  // 8-bit integer abs to NEG and CMOV.
16340  if (VT.isInteger() && VT.getSizeInBits() == 8)
16341    return SDValue();
16342
16343  SDValue N0 = N->getOperand(0);
16344  SDValue N1 = N->getOperand(1);
16345  DebugLoc DL = N->getDebugLoc();
16346
16347  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16348  // and change it to SUB and CMOV.
16349  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16350      N0.getOpcode() == ISD::ADD &&
16351      N0.getOperand(1) == N1 &&
16352      N1.getOpcode() == ISD::SRA &&
16353      N1.getOperand(0) == N0.getOperand(0))
16354    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16355      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16356        // Generate SUB & CMOV.
16357        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16358                                  DAG.getConstant(0, VT), N0.getOperand(0));
16359
16360        SDValue Ops[] = { N0.getOperand(0), Neg,
16361                          DAG.getConstant(X86::COND_GE, MVT::i8),
16362                          SDValue(Neg.getNode(), 1) };
16363        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16364                           Ops, array_lengthof(Ops));
16365      }
16366  return SDValue();
16367}
16368
16369// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16370static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16371                                 TargetLowering::DAGCombinerInfo &DCI,
16372                                 const X86Subtarget *Subtarget) {
16373  EVT VT = N->getValueType(0);
16374  if (DCI.isBeforeLegalizeOps())
16375    return SDValue();
16376
16377  if (Subtarget->hasCMov()) {
16378    SDValue RV = performIntegerAbsCombine(N, DAG);
16379    if (RV.getNode())
16380      return RV;
16381  }
16382
16383  // Try forming BMI if it is available.
16384  if (!Subtarget->hasBMI())
16385    return SDValue();
16386
16387  if (VT != MVT::i32 && VT != MVT::i64)
16388    return SDValue();
16389
16390  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16391
16392  // Create BLSMSK instructions by finding X ^ (X-1)
16393  SDValue N0 = N->getOperand(0);
16394  SDValue N1 = N->getOperand(1);
16395  DebugLoc DL = N->getDebugLoc();
16396
16397  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16398      isAllOnes(N0.getOperand(1)))
16399    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16400
16401  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16402      isAllOnes(N1.getOperand(1)))
16403    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16404
16405  return SDValue();
16406}
16407
16408/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16409static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16410                                  TargetLowering::DAGCombinerInfo &DCI,
16411                                  const X86Subtarget *Subtarget) {
16412  LoadSDNode *Ld = cast<LoadSDNode>(N);
16413  EVT RegVT = Ld->getValueType(0);
16414  EVT MemVT = Ld->getMemoryVT();
16415  DebugLoc dl = Ld->getDebugLoc();
16416  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16417  unsigned RegSz = RegVT.getSizeInBits();
16418
16419  ISD::LoadExtType Ext = Ld->getExtensionType();
16420  unsigned Alignment = Ld->getAlignment();
16421  bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16422
16423  // On Sandybridge unaligned 256bit loads are inefficient.
16424  if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16425      !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16426    unsigned NumElems = RegVT.getVectorNumElements();
16427    if (NumElems < 2)
16428      return SDValue();
16429
16430    SDValue Ptr = Ld->getBasePtr();
16431    SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16432
16433    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16434                                  NumElems/2);
16435    SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16436                                Ld->getPointerInfo(), Ld->isVolatile(),
16437                                Ld->isNonTemporal(), Ld->isInvariant(),
16438                                Alignment);
16439    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16440    SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16441                                Ld->getPointerInfo(), Ld->isVolatile(),
16442                                Ld->isNonTemporal(), Ld->isInvariant(),
16443                                std::max(Alignment/2U, 1U));
16444    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16445                             Load1.getValue(1),
16446                             Load2.getValue(1));
16447
16448    SDValue NewVec = DAG.getUNDEF(RegVT);
16449    NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16450    NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16451    return DCI.CombineTo(N, NewVec, TF, true);
16452  }
16453
16454  // If this is a vector EXT Load then attempt to optimize it using a
16455  // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16456  // expansion is still better than scalar code.
16457  // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16458  // emit a shuffle and a arithmetic shift.
16459  // TODO: It is possible to support ZExt by zeroing the undef values
16460  // during the shuffle phase or after the shuffle.
16461  if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16462      (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16463    assert(MemVT != RegVT && "Cannot extend to the same type");
16464    assert(MemVT.isVector() && "Must load a vector from memory");
16465
16466    unsigned NumElems = RegVT.getVectorNumElements();
16467    unsigned MemSz = MemVT.getSizeInBits();
16468    assert(RegSz > MemSz && "Register size must be greater than the mem size");
16469
16470    if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16471      return SDValue();
16472
16473    // All sizes must be a power of two.
16474    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16475      return SDValue();
16476
16477    // Attempt to load the original value using scalar loads.
16478    // Find the largest scalar type that divides the total loaded size.
16479    MVT SclrLoadTy = MVT::i8;
16480    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16481         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16482      MVT Tp = (MVT::SimpleValueType)tp;
16483      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16484        SclrLoadTy = Tp;
16485      }
16486    }
16487
16488    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16489    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16490        (64 <= MemSz))
16491      SclrLoadTy = MVT::f64;
16492
16493    // Calculate the number of scalar loads that we need to perform
16494    // in order to load our vector from memory.
16495    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16496    if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16497      return SDValue();
16498
16499    unsigned loadRegZize = RegSz;
16500    if (Ext == ISD::SEXTLOAD && RegSz == 256)
16501      loadRegZize /= 2;
16502
16503    // Represent our vector as a sequence of elements which are the
16504    // largest scalar that we can load.
16505    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16506      loadRegZize/SclrLoadTy.getSizeInBits());
16507
16508    // Represent the data using the same element type that is stored in
16509    // memory. In practice, we ''widen'' MemVT.
16510    EVT WideVecVT =
16511          EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16512                       loadRegZize/MemVT.getScalarType().getSizeInBits());
16513
16514    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16515      "Invalid vector type");
16516
16517    // We can't shuffle using an illegal type.
16518    if (!TLI.isTypeLegal(WideVecVT))
16519      return SDValue();
16520
16521    SmallVector<SDValue, 8> Chains;
16522    SDValue Ptr = Ld->getBasePtr();
16523    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16524                                        TLI.getPointerTy());
16525    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16526
16527    for (unsigned i = 0; i < NumLoads; ++i) {
16528      // Perform a single load.
16529      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16530                                       Ptr, Ld->getPointerInfo(),
16531                                       Ld->isVolatile(), Ld->isNonTemporal(),
16532                                       Ld->isInvariant(), Ld->getAlignment());
16533      Chains.push_back(ScalarLoad.getValue(1));
16534      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16535      // another round of DAGCombining.
16536      if (i == 0)
16537        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16538      else
16539        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16540                          ScalarLoad, DAG.getIntPtrConstant(i));
16541
16542      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16543    }
16544
16545    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16546                               Chains.size());
16547
16548    // Bitcast the loaded value to a vector of the original element type, in
16549    // the size of the target vector type.
16550    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16551    unsigned SizeRatio = RegSz/MemSz;
16552
16553    if (Ext == ISD::SEXTLOAD) {
16554      // If we have SSE4.1 we can directly emit a VSEXT node.
16555      if (Subtarget->hasSSE41()) {
16556        SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16557        return DCI.CombineTo(N, Sext, TF, true);
16558      }
16559
16560      // Otherwise we'll shuffle the small elements in the high bits of the
16561      // larger type and perform an arithmetic shift. If the shift is not legal
16562      // it's better to scalarize.
16563      if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16564        return SDValue();
16565
16566      // Redistribute the loaded elements into the different locations.
16567      SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16568      for (unsigned i = 0; i != NumElems; ++i)
16569        ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16570
16571      SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16572                                           DAG.getUNDEF(WideVecVT),
16573                                           &ShuffleVec[0]);
16574
16575      Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16576
16577      // Build the arithmetic shift.
16578      unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16579                     MemVT.getVectorElementType().getSizeInBits();
16580      Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16581                          DAG.getConstant(Amt, RegVT));
16582
16583      return DCI.CombineTo(N, Shuff, TF, true);
16584    }
16585
16586    // Redistribute the loaded elements into the different locations.
16587    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16588    for (unsigned i = 0; i != NumElems; ++i)
16589      ShuffleVec[i*SizeRatio] = i;
16590
16591    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16592                                         DAG.getUNDEF(WideVecVT),
16593                                         &ShuffleVec[0]);
16594
16595    // Bitcast to the requested type.
16596    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16597    // Replace the original load with the new sequence
16598    // and return the new chain.
16599    return DCI.CombineTo(N, Shuff, TF, true);
16600  }
16601
16602  return SDValue();
16603}
16604
16605/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16606static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16607                                   const X86Subtarget *Subtarget) {
16608  StoreSDNode *St = cast<StoreSDNode>(N);
16609  EVT VT = St->getValue().getValueType();
16610  EVT StVT = St->getMemoryVT();
16611  DebugLoc dl = St->getDebugLoc();
16612  SDValue StoredVal = St->getOperand(1);
16613  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16614  unsigned Alignment = St->getAlignment();
16615  bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16616
16617  // If we are saving a concatenation of two XMM registers, perform two stores.
16618  // On Sandy Bridge, 256-bit memory operations are executed by two
16619  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16620  // memory  operation.
16621  if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16622      StVT == VT && !IsAligned) {
16623    unsigned NumElems = VT.getVectorNumElements();
16624    if (NumElems < 2)
16625      return SDValue();
16626
16627    SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16628    SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16629
16630    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16631    SDValue Ptr0 = St->getBasePtr();
16632    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16633
16634    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16635                                St->getPointerInfo(), St->isVolatile(),
16636                                St->isNonTemporal(), Alignment);
16637    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16638                                St->getPointerInfo(), St->isVolatile(),
16639                                St->isNonTemporal(),
16640                                std::max(Alignment/2U, 1U));
16641    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16642  }
16643
16644  // Optimize trunc store (of multiple scalars) to shuffle and store.
16645  // First, pack all of the elements in one place. Next, store to memory
16646  // in fewer chunks.
16647  if (St->isTruncatingStore() && VT.isVector()) {
16648    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16649    unsigned NumElems = VT.getVectorNumElements();
16650    assert(StVT != VT && "Cannot truncate to the same type");
16651    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16652    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16653
16654    // From, To sizes and ElemCount must be pow of two
16655    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16656    // We are going to use the original vector elt for storing.
16657    // Accumulated smaller vector elements must be a multiple of the store size.
16658    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16659
16660    unsigned SizeRatio  = FromSz / ToSz;
16661
16662    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16663
16664    // Create a type on which we perform the shuffle
16665    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16666            StVT.getScalarType(), NumElems*SizeRatio);
16667
16668    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16669
16670    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16671    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16672    for (unsigned i = 0; i != NumElems; ++i)
16673      ShuffleVec[i] = i * SizeRatio;
16674
16675    // Can't shuffle using an illegal type.
16676    if (!TLI.isTypeLegal(WideVecVT))
16677      return SDValue();
16678
16679    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16680                                         DAG.getUNDEF(WideVecVT),
16681                                         &ShuffleVec[0]);
16682    // At this point all of the data is stored at the bottom of the
16683    // register. We now need to save it to mem.
16684
16685    // Find the largest store unit
16686    MVT StoreType = MVT::i8;
16687    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16688         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16689      MVT Tp = (MVT::SimpleValueType)tp;
16690      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16691        StoreType = Tp;
16692    }
16693
16694    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16695    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16696        (64 <= NumElems * ToSz))
16697      StoreType = MVT::f64;
16698
16699    // Bitcast the original vector into a vector of store-size units
16700    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16701            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16702    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16703    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16704    SmallVector<SDValue, 8> Chains;
16705    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16706                                        TLI.getPointerTy());
16707    SDValue Ptr = St->getBasePtr();
16708
16709    // Perform one or more big stores into memory.
16710    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16711      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16712                                   StoreType, ShuffWide,
16713                                   DAG.getIntPtrConstant(i));
16714      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16715                                St->getPointerInfo(), St->isVolatile(),
16716                                St->isNonTemporal(), St->getAlignment());
16717      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16718      Chains.push_back(Ch);
16719    }
16720
16721    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16722                               Chains.size());
16723  }
16724
16725  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16726  // the FP state in cases where an emms may be missing.
16727  // A preferable solution to the general problem is to figure out the right
16728  // places to insert EMMS.  This qualifies as a quick hack.
16729
16730  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16731  if (VT.getSizeInBits() != 64)
16732    return SDValue();
16733
16734  const Function *F = DAG.getMachineFunction().getFunction();
16735  bool NoImplicitFloatOps = F->getAttributes().
16736    hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16737  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16738                     && Subtarget->hasSSE2();
16739  if ((VT.isVector() ||
16740       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16741      isa<LoadSDNode>(St->getValue()) &&
16742      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16743      St->getChain().hasOneUse() && !St->isVolatile()) {
16744    SDNode* LdVal = St->getValue().getNode();
16745    LoadSDNode *Ld = 0;
16746    int TokenFactorIndex = -1;
16747    SmallVector<SDValue, 8> Ops;
16748    SDNode* ChainVal = St->getChain().getNode();
16749    // Must be a store of a load.  We currently handle two cases:  the load
16750    // is a direct child, and it's under an intervening TokenFactor.  It is
16751    // possible to dig deeper under nested TokenFactors.
16752    if (ChainVal == LdVal)
16753      Ld = cast<LoadSDNode>(St->getChain());
16754    else if (St->getValue().hasOneUse() &&
16755             ChainVal->getOpcode() == ISD::TokenFactor) {
16756      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16757        if (ChainVal->getOperand(i).getNode() == LdVal) {
16758          TokenFactorIndex = i;
16759          Ld = cast<LoadSDNode>(St->getValue());
16760        } else
16761          Ops.push_back(ChainVal->getOperand(i));
16762      }
16763    }
16764
16765    if (!Ld || !ISD::isNormalLoad(Ld))
16766      return SDValue();
16767
16768    // If this is not the MMX case, i.e. we are just turning i64 load/store
16769    // into f64 load/store, avoid the transformation if there are multiple
16770    // uses of the loaded value.
16771    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16772      return SDValue();
16773
16774    DebugLoc LdDL = Ld->getDebugLoc();
16775    DebugLoc StDL = N->getDebugLoc();
16776    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16777    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16778    // pair instead.
16779    if (Subtarget->is64Bit() || F64IsLegal) {
16780      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16781      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16782                                  Ld->getPointerInfo(), Ld->isVolatile(),
16783                                  Ld->isNonTemporal(), Ld->isInvariant(),
16784                                  Ld->getAlignment());
16785      SDValue NewChain = NewLd.getValue(1);
16786      if (TokenFactorIndex != -1) {
16787        Ops.push_back(NewChain);
16788        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16789                               Ops.size());
16790      }
16791      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16792                          St->getPointerInfo(),
16793                          St->isVolatile(), St->isNonTemporal(),
16794                          St->getAlignment());
16795    }
16796
16797    // Otherwise, lower to two pairs of 32-bit loads / stores.
16798    SDValue LoAddr = Ld->getBasePtr();
16799    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16800                                 DAG.getConstant(4, MVT::i32));
16801
16802    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16803                               Ld->getPointerInfo(),
16804                               Ld->isVolatile(), Ld->isNonTemporal(),
16805                               Ld->isInvariant(), Ld->getAlignment());
16806    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16807                               Ld->getPointerInfo().getWithOffset(4),
16808                               Ld->isVolatile(), Ld->isNonTemporal(),
16809                               Ld->isInvariant(),
16810                               MinAlign(Ld->getAlignment(), 4));
16811
16812    SDValue NewChain = LoLd.getValue(1);
16813    if (TokenFactorIndex != -1) {
16814      Ops.push_back(LoLd);
16815      Ops.push_back(HiLd);
16816      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16817                             Ops.size());
16818    }
16819
16820    LoAddr = St->getBasePtr();
16821    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16822                         DAG.getConstant(4, MVT::i32));
16823
16824    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16825                                St->getPointerInfo(),
16826                                St->isVolatile(), St->isNonTemporal(),
16827                                St->getAlignment());
16828    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16829                                St->getPointerInfo().getWithOffset(4),
16830                                St->isVolatile(),
16831                                St->isNonTemporal(),
16832                                MinAlign(St->getAlignment(), 4));
16833    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16834  }
16835  return SDValue();
16836}
16837
16838/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16839/// and return the operands for the horizontal operation in LHS and RHS.  A
16840/// horizontal operation performs the binary operation on successive elements
16841/// of its first operand, then on successive elements of its second operand,
16842/// returning the resulting values in a vector.  For example, if
16843///   A = < float a0, float a1, float a2, float a3 >
16844/// and
16845///   B = < float b0, float b1, float b2, float b3 >
16846/// then the result of doing a horizontal operation on A and B is
16847///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16848/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16849/// A horizontal-op B, for some already available A and B, and if so then LHS is
16850/// set to A, RHS to B, and the routine returns 'true'.
16851/// Note that the binary operation should have the property that if one of the
16852/// operands is UNDEF then the result is UNDEF.
16853static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16854  // Look for the following pattern: if
16855  //   A = < float a0, float a1, float a2, float a3 >
16856  //   B = < float b0, float b1, float b2, float b3 >
16857  // and
16858  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16859  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16860  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16861  // which is A horizontal-op B.
16862
16863  // At least one of the operands should be a vector shuffle.
16864  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16865      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16866    return false;
16867
16868  EVT VT = LHS.getValueType();
16869
16870  assert((VT.is128BitVector() || VT.is256BitVector()) &&
16871         "Unsupported vector type for horizontal add/sub");
16872
16873  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16874  // operate independently on 128-bit lanes.
16875  unsigned NumElts = VT.getVectorNumElements();
16876  unsigned NumLanes = VT.getSizeInBits()/128;
16877  unsigned NumLaneElts = NumElts / NumLanes;
16878  assert((NumLaneElts % 2 == 0) &&
16879         "Vector type should have an even number of elements in each lane");
16880  unsigned HalfLaneElts = NumLaneElts/2;
16881
16882  // View LHS in the form
16883  //   LHS = VECTOR_SHUFFLE A, B, LMask
16884  // If LHS is not a shuffle then pretend it is the shuffle
16885  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16886  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16887  // type VT.
16888  SDValue A, B;
16889  SmallVector<int, 16> LMask(NumElts);
16890  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16891    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16892      A = LHS.getOperand(0);
16893    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16894      B = LHS.getOperand(1);
16895    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16896    std::copy(Mask.begin(), Mask.end(), LMask.begin());
16897  } else {
16898    if (LHS.getOpcode() != ISD::UNDEF)
16899      A = LHS;
16900    for (unsigned i = 0; i != NumElts; ++i)
16901      LMask[i] = i;
16902  }
16903
16904  // Likewise, view RHS in the form
16905  //   RHS = VECTOR_SHUFFLE C, D, RMask
16906  SDValue C, D;
16907  SmallVector<int, 16> RMask(NumElts);
16908  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16909    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16910      C = RHS.getOperand(0);
16911    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16912      D = RHS.getOperand(1);
16913    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16914    std::copy(Mask.begin(), Mask.end(), RMask.begin());
16915  } else {
16916    if (RHS.getOpcode() != ISD::UNDEF)
16917      C = RHS;
16918    for (unsigned i = 0; i != NumElts; ++i)
16919      RMask[i] = i;
16920  }
16921
16922  // Check that the shuffles are both shuffling the same vectors.
16923  if (!(A == C && B == D) && !(A == D && B == C))
16924    return false;
16925
16926  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16927  if (!A.getNode() && !B.getNode())
16928    return false;
16929
16930  // If A and B occur in reverse order in RHS, then "swap" them (which means
16931  // rewriting the mask).
16932  if (A != C)
16933    CommuteVectorShuffleMask(RMask, NumElts);
16934
16935  // At this point LHS and RHS are equivalent to
16936  //   LHS = VECTOR_SHUFFLE A, B, LMask
16937  //   RHS = VECTOR_SHUFFLE A, B, RMask
16938  // Check that the masks correspond to performing a horizontal operation.
16939  for (unsigned i = 0; i != NumElts; ++i) {
16940    int LIdx = LMask[i], RIdx = RMask[i];
16941
16942    // Ignore any UNDEF components.
16943    if (LIdx < 0 || RIdx < 0 ||
16944        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16945        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16946      continue;
16947
16948    // Check that successive elements are being operated on.  If not, this is
16949    // not a horizontal operation.
16950    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16951    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16952    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16953    if (!(LIdx == Index && RIdx == Index + 1) &&
16954        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16955      return false;
16956  }
16957
16958  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16959  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16960  return true;
16961}
16962
16963/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16964static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16965                                  const X86Subtarget *Subtarget) {
16966  EVT VT = N->getValueType(0);
16967  SDValue LHS = N->getOperand(0);
16968  SDValue RHS = N->getOperand(1);
16969
16970  // Try to synthesize horizontal adds from adds of shuffles.
16971  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16972       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16973      isHorizontalBinOp(LHS, RHS, true))
16974    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16975  return SDValue();
16976}
16977
16978/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16979static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16980                                  const X86Subtarget *Subtarget) {
16981  EVT VT = N->getValueType(0);
16982  SDValue LHS = N->getOperand(0);
16983  SDValue RHS = N->getOperand(1);
16984
16985  // Try to synthesize horizontal subs from subs of shuffles.
16986  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16987       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16988      isHorizontalBinOp(LHS, RHS, false))
16989    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16990  return SDValue();
16991}
16992
16993/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16994/// X86ISD::FXOR nodes.
16995static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16996  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16997  // F[X]OR(0.0, x) -> x
16998  // F[X]OR(x, 0.0) -> x
16999  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17000    if (C->getValueAPF().isPosZero())
17001      return N->getOperand(1);
17002  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17003    if (C->getValueAPF().isPosZero())
17004      return N->getOperand(0);
17005  return SDValue();
17006}
17007
17008/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17009/// X86ISD::FMAX nodes.
17010static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17011  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17012
17013  // Only perform optimizations if UnsafeMath is used.
17014  if (!DAG.getTarget().Options.UnsafeFPMath)
17015    return SDValue();
17016
17017  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17018  // into FMINC and FMAXC, which are Commutative operations.
17019  unsigned NewOp = 0;
17020  switch (N->getOpcode()) {
17021    default: llvm_unreachable("unknown opcode");
17022    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17023    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17024  }
17025
17026  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17027                     N->getOperand(0), N->getOperand(1));
17028}
17029
17030/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17031static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17032  // FAND(0.0, x) -> 0.0
17033  // FAND(x, 0.0) -> 0.0
17034  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17035    if (C->getValueAPF().isPosZero())
17036      return N->getOperand(0);
17037  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17038    if (C->getValueAPF().isPosZero())
17039      return N->getOperand(1);
17040  return SDValue();
17041}
17042
17043static SDValue PerformBTCombine(SDNode *N,
17044                                SelectionDAG &DAG,
17045                                TargetLowering::DAGCombinerInfo &DCI) {
17046  // BT ignores high bits in the bit index operand.
17047  SDValue Op1 = N->getOperand(1);
17048  if (Op1.hasOneUse()) {
17049    unsigned BitWidth = Op1.getValueSizeInBits();
17050    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17051    APInt KnownZero, KnownOne;
17052    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17053                                          !DCI.isBeforeLegalizeOps());
17054    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17055    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17056        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17057      DCI.CommitTargetLoweringOpt(TLO);
17058  }
17059  return SDValue();
17060}
17061
17062static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17063  SDValue Op = N->getOperand(0);
17064  if (Op.getOpcode() == ISD::BITCAST)
17065    Op = Op.getOperand(0);
17066  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17067  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17068      VT.getVectorElementType().getSizeInBits() ==
17069      OpVT.getVectorElementType().getSizeInBits()) {
17070    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17071  }
17072  return SDValue();
17073}
17074
17075static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17076                                               const X86Subtarget *Subtarget) {
17077  EVT VT = N->getValueType(0);
17078  if (!VT.isVector())
17079    return SDValue();
17080
17081  SDValue N0 = N->getOperand(0);
17082  SDValue N1 = N->getOperand(1);
17083  EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17084  DebugLoc dl = N->getDebugLoc();
17085
17086  // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17087  // both SSE and AVX2 since there is no sign-extended shift right
17088  // operation on a vector with 64-bit elements.
17089  //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17090  // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17091  if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17092      N0.getOpcode() == ISD::SIGN_EXTEND)) {
17093    SDValue N00 = N0.getOperand(0);
17094
17095    // EXTLOAD has a better solution on AVX2,
17096    // it may be replaced with X86ISD::VSEXT node.
17097    if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17098      if (!ISD::isNormalLoad(N00.getNode()))
17099        return SDValue();
17100
17101    if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17102        SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17103                                  N00, N1);
17104      return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17105    }
17106  }
17107  return SDValue();
17108}
17109
17110static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17111                                  TargetLowering::DAGCombinerInfo &DCI,
17112                                  const X86Subtarget *Subtarget) {
17113  if (!DCI.isBeforeLegalizeOps())
17114    return SDValue();
17115
17116  if (!Subtarget->hasFp256())
17117    return SDValue();
17118
17119  EVT VT = N->getValueType(0);
17120  if (VT.isVector() && VT.getSizeInBits() == 256) {
17121    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17122    if (R.getNode())
17123      return R;
17124  }
17125
17126  return SDValue();
17127}
17128
17129static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17130                                 const X86Subtarget* Subtarget) {
17131  DebugLoc dl = N->getDebugLoc();
17132  EVT VT = N->getValueType(0);
17133
17134  // Let legalize expand this if it isn't a legal type yet.
17135  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17136    return SDValue();
17137
17138  EVT ScalarVT = VT.getScalarType();
17139  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17140      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17141    return SDValue();
17142
17143  SDValue A = N->getOperand(0);
17144  SDValue B = N->getOperand(1);
17145  SDValue C = N->getOperand(2);
17146
17147  bool NegA = (A.getOpcode() == ISD::FNEG);
17148  bool NegB = (B.getOpcode() == ISD::FNEG);
17149  bool NegC = (C.getOpcode() == ISD::FNEG);
17150
17151  // Negative multiplication when NegA xor NegB
17152  bool NegMul = (NegA != NegB);
17153  if (NegA)
17154    A = A.getOperand(0);
17155  if (NegB)
17156    B = B.getOperand(0);
17157  if (NegC)
17158    C = C.getOperand(0);
17159
17160  unsigned Opcode;
17161  if (!NegMul)
17162    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17163  else
17164    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17165
17166  return DAG.getNode(Opcode, dl, VT, A, B, C);
17167}
17168
17169static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17170                                  TargetLowering::DAGCombinerInfo &DCI,
17171                                  const X86Subtarget *Subtarget) {
17172  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17173  //           (and (i32 x86isd::setcc_carry), 1)
17174  // This eliminates the zext. This transformation is necessary because
17175  // ISD::SETCC is always legalized to i8.
17176  DebugLoc dl = N->getDebugLoc();
17177  SDValue N0 = N->getOperand(0);
17178  EVT VT = N->getValueType(0);
17179
17180  if (N0.getOpcode() == ISD::AND &&
17181      N0.hasOneUse() &&
17182      N0.getOperand(0).hasOneUse()) {
17183    SDValue N00 = N0.getOperand(0);
17184    if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17185      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17186      if (!C || C->getZExtValue() != 1)
17187        return SDValue();
17188      return DAG.getNode(ISD::AND, dl, VT,
17189                         DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17190                                     N00.getOperand(0), N00.getOperand(1)),
17191                         DAG.getConstant(1, VT));
17192    }
17193  }
17194
17195  if (VT.is256BitVector()) {
17196    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17197    if (R.getNode())
17198      return R;
17199  }
17200
17201  return SDValue();
17202}
17203
17204// Optimize x == -y --> x+y == 0
17205//          x != -y --> x+y != 0
17206static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17207  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17208  SDValue LHS = N->getOperand(0);
17209  SDValue RHS = N->getOperand(1);
17210
17211  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17212    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17213      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17214        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17215                                   LHS.getValueType(), RHS, LHS.getOperand(1));
17216        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17217                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17218      }
17219  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17220    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17221      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17222        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17223                                   RHS.getValueType(), LHS, RHS.getOperand(1));
17224        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17225                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17226      }
17227  return SDValue();
17228}
17229
17230// Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17231// as "sbb reg,reg", since it can be extended without zext and produces
17232// an all-ones bit which is more useful than 0/1 in some cases.
17233static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17234  return DAG.getNode(ISD::AND, DL, MVT::i8,
17235                     DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17236                                 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17237                     DAG.getConstant(1, MVT::i8));
17238}
17239
17240// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17241static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17242                                   TargetLowering::DAGCombinerInfo &DCI,
17243                                   const X86Subtarget *Subtarget) {
17244  DebugLoc DL = N->getDebugLoc();
17245  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17246  SDValue EFLAGS = N->getOperand(1);
17247
17248  if (CC == X86::COND_A) {
17249    // Try to convert COND_A into COND_B in an attempt to facilitate
17250    // materializing "setb reg".
17251    //
17252    // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17253    // cannot take an immediate as its first operand.
17254    //
17255    if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17256        EFLAGS.getValueType().isInteger() &&
17257        !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17258      SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17259                                   EFLAGS.getNode()->getVTList(),
17260                                   EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17261      SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17262      return MaterializeSETB(DL, NewEFLAGS, DAG);
17263    }
17264  }
17265
17266  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17267  // a zext and produces an all-ones bit which is more useful than 0/1 in some
17268  // cases.
17269  if (CC == X86::COND_B)
17270    return MaterializeSETB(DL, EFLAGS, DAG);
17271
17272  SDValue Flags;
17273
17274  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17275  if (Flags.getNode()) {
17276    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17277    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17278  }
17279
17280  return SDValue();
17281}
17282
17283// Optimize branch condition evaluation.
17284//
17285static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17286                                    TargetLowering::DAGCombinerInfo &DCI,
17287                                    const X86Subtarget *Subtarget) {
17288  DebugLoc DL = N->getDebugLoc();
17289  SDValue Chain = N->getOperand(0);
17290  SDValue Dest = N->getOperand(1);
17291  SDValue EFLAGS = N->getOperand(3);
17292  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17293
17294  SDValue Flags;
17295
17296  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17297  if (Flags.getNode()) {
17298    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17299    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17300                       Flags);
17301  }
17302
17303  return SDValue();
17304}
17305
17306static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17307                                        const X86TargetLowering *XTLI) {
17308  SDValue Op0 = N->getOperand(0);
17309  EVT InVT = Op0->getValueType(0);
17310
17311  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17312  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17313    DebugLoc dl = N->getDebugLoc();
17314    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17315    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17316    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17317  }
17318
17319  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17320  // a 32-bit target where SSE doesn't support i64->FP operations.
17321  if (Op0.getOpcode() == ISD::LOAD) {
17322    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17323    EVT VT = Ld->getValueType(0);
17324    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17325        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17326        !XTLI->getSubtarget()->is64Bit() &&
17327        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17328      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17329                                          Ld->getChain(), Op0, DAG);
17330      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17331      return FILDChain;
17332    }
17333  }
17334  return SDValue();
17335}
17336
17337// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17338static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17339                                 X86TargetLowering::DAGCombinerInfo &DCI) {
17340  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17341  // the result is either zero or one (depending on the input carry bit).
17342  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17343  if (X86::isZeroNode(N->getOperand(0)) &&
17344      X86::isZeroNode(N->getOperand(1)) &&
17345      // We don't have a good way to replace an EFLAGS use, so only do this when
17346      // dead right now.
17347      SDValue(N, 1).use_empty()) {
17348    DebugLoc DL = N->getDebugLoc();
17349    EVT VT = N->getValueType(0);
17350    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17351    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17352                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17353                                           DAG.getConstant(X86::COND_B,MVT::i8),
17354                                           N->getOperand(2)),
17355                               DAG.getConstant(1, VT));
17356    return DCI.CombineTo(N, Res1, CarryOut);
17357  }
17358
17359  return SDValue();
17360}
17361
17362// fold (add Y, (sete  X, 0)) -> adc  0, Y
17363//      (add Y, (setne X, 0)) -> sbb -1, Y
17364//      (sub (sete  X, 0), Y) -> sbb  0, Y
17365//      (sub (setne X, 0), Y) -> adc -1, Y
17366static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17367  DebugLoc DL = N->getDebugLoc();
17368
17369  // Look through ZExts.
17370  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17371  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17372    return SDValue();
17373
17374  SDValue SetCC = Ext.getOperand(0);
17375  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17376    return SDValue();
17377
17378  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17379  if (CC != X86::COND_E && CC != X86::COND_NE)
17380    return SDValue();
17381
17382  SDValue Cmp = SetCC.getOperand(1);
17383  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17384      !X86::isZeroNode(Cmp.getOperand(1)) ||
17385      !Cmp.getOperand(0).getValueType().isInteger())
17386    return SDValue();
17387
17388  SDValue CmpOp0 = Cmp.getOperand(0);
17389  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17390                               DAG.getConstant(1, CmpOp0.getValueType()));
17391
17392  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17393  if (CC == X86::COND_NE)
17394    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17395                       DL, OtherVal.getValueType(), OtherVal,
17396                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17397  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17398                     DL, OtherVal.getValueType(), OtherVal,
17399                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17400}
17401
17402/// PerformADDCombine - Do target-specific dag combines on integer adds.
17403static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17404                                 const X86Subtarget *Subtarget) {
17405  EVT VT = N->getValueType(0);
17406  SDValue Op0 = N->getOperand(0);
17407  SDValue Op1 = N->getOperand(1);
17408
17409  // Try to synthesize horizontal adds from adds of shuffles.
17410  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17411       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17412      isHorizontalBinOp(Op0, Op1, true))
17413    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17414
17415  return OptimizeConditionalInDecrement(N, DAG);
17416}
17417
17418static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17419                                 const X86Subtarget *Subtarget) {
17420  SDValue Op0 = N->getOperand(0);
17421  SDValue Op1 = N->getOperand(1);
17422
17423  // X86 can't encode an immediate LHS of a sub. See if we can push the
17424  // negation into a preceding instruction.
17425  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17426    // If the RHS of the sub is a XOR with one use and a constant, invert the
17427    // immediate. Then add one to the LHS of the sub so we can turn
17428    // X-Y -> X+~Y+1, saving one register.
17429    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17430        isa<ConstantSDNode>(Op1.getOperand(1))) {
17431      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17432      EVT VT = Op0.getValueType();
17433      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17434                                   Op1.getOperand(0),
17435                                   DAG.getConstant(~XorC, VT));
17436      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17437                         DAG.getConstant(C->getAPIntValue()+1, VT));
17438    }
17439  }
17440
17441  // Try to synthesize horizontal adds from adds of shuffles.
17442  EVT VT = N->getValueType(0);
17443  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17444       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17445      isHorizontalBinOp(Op0, Op1, true))
17446    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17447
17448  return OptimizeConditionalInDecrement(N, DAG);
17449}
17450
17451/// performVZEXTCombine - Performs build vector combines
17452static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17453                                        TargetLowering::DAGCombinerInfo &DCI,
17454                                        const X86Subtarget *Subtarget) {
17455  // (vzext (bitcast (vzext (x)) -> (vzext x)
17456  SDValue In = N->getOperand(0);
17457  while (In.getOpcode() == ISD::BITCAST)
17458    In = In.getOperand(0);
17459
17460  if (In.getOpcode() != X86ISD::VZEXT)
17461    return SDValue();
17462
17463  return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17464                     In.getOperand(0));
17465}
17466
17467SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17468                                             DAGCombinerInfo &DCI) const {
17469  SelectionDAG &DAG = DCI.DAG;
17470  switch (N->getOpcode()) {
17471  default: break;
17472  case ISD::EXTRACT_VECTOR_ELT:
17473    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17474  case ISD::VSELECT:
17475  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17476  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17477  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17478  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17479  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17480  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17481  case ISD::SHL:
17482  case ISD::SRA:
17483  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17484  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17485  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17486  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17487  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17488  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17489  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17490  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17491  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17492  case X86ISD::FXOR:
17493  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17494  case X86ISD::FMIN:
17495  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17496  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17497  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17498  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17499  case ISD::ANY_EXTEND:
17500  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17501  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17502  case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17503  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17504  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17505  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17506  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17507  case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17508  case X86ISD::SHUFP:       // Handle all target specific shuffles
17509  case X86ISD::PALIGNR:
17510  case X86ISD::UNPCKH:
17511  case X86ISD::UNPCKL:
17512  case X86ISD::MOVHLPS:
17513  case X86ISD::MOVLHPS:
17514  case X86ISD::PSHUFD:
17515  case X86ISD::PSHUFHW:
17516  case X86ISD::PSHUFLW:
17517  case X86ISD::MOVSS:
17518  case X86ISD::MOVSD:
17519  case X86ISD::VPERMILP:
17520  case X86ISD::VPERM2X128:
17521  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17522  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17523  }
17524
17525  return SDValue();
17526}
17527
17528/// isTypeDesirableForOp - Return true if the target has native support for
17529/// the specified value type and it is 'desirable' to use the type for the
17530/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17531/// instruction encodings are longer and some i16 instructions are slow.
17532bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17533  if (!isTypeLegal(VT))
17534    return false;
17535  if (VT != MVT::i16)
17536    return true;
17537
17538  switch (Opc) {
17539  default:
17540    return true;
17541  case ISD::LOAD:
17542  case ISD::SIGN_EXTEND:
17543  case ISD::ZERO_EXTEND:
17544  case ISD::ANY_EXTEND:
17545  case ISD::SHL:
17546  case ISD::SRL:
17547  case ISD::SUB:
17548  case ISD::ADD:
17549  case ISD::MUL:
17550  case ISD::AND:
17551  case ISD::OR:
17552  case ISD::XOR:
17553    return false;
17554  }
17555}
17556
17557/// IsDesirableToPromoteOp - This method query the target whether it is
17558/// beneficial for dag combiner to promote the specified node. If true, it
17559/// should return the desired promotion type by reference.
17560bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17561  EVT VT = Op.getValueType();
17562  if (VT != MVT::i16)
17563    return false;
17564
17565  bool Promote = false;
17566  bool Commute = false;
17567  switch (Op.getOpcode()) {
17568  default: break;
17569  case ISD::LOAD: {
17570    LoadSDNode *LD = cast<LoadSDNode>(Op);
17571    // If the non-extending load has a single use and it's not live out, then it
17572    // might be folded.
17573    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17574                                                     Op.hasOneUse()*/) {
17575      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17576             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17577        // The only case where we'd want to promote LOAD (rather then it being
17578        // promoted as an operand is when it's only use is liveout.
17579        if (UI->getOpcode() != ISD::CopyToReg)
17580          return false;
17581      }
17582    }
17583    Promote = true;
17584    break;
17585  }
17586  case ISD::SIGN_EXTEND:
17587  case ISD::ZERO_EXTEND:
17588  case ISD::ANY_EXTEND:
17589    Promote = true;
17590    break;
17591  case ISD::SHL:
17592  case ISD::SRL: {
17593    SDValue N0 = Op.getOperand(0);
17594    // Look out for (store (shl (load), x)).
17595    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17596      return false;
17597    Promote = true;
17598    break;
17599  }
17600  case ISD::ADD:
17601  case ISD::MUL:
17602  case ISD::AND:
17603  case ISD::OR:
17604  case ISD::XOR:
17605    Commute = true;
17606    // fallthrough
17607  case ISD::SUB: {
17608    SDValue N0 = Op.getOperand(0);
17609    SDValue N1 = Op.getOperand(1);
17610    if (!Commute && MayFoldLoad(N1))
17611      return false;
17612    // Avoid disabling potential load folding opportunities.
17613    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17614      return false;
17615    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17616      return false;
17617    Promote = true;
17618  }
17619  }
17620
17621  PVT = MVT::i32;
17622  return Promote;
17623}
17624
17625//===----------------------------------------------------------------------===//
17626//                           X86 Inline Assembly Support
17627//===----------------------------------------------------------------------===//
17628
17629namespace {
17630  // Helper to match a string separated by whitespace.
17631  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17632    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17633
17634    for (unsigned i = 0, e = args.size(); i != e; ++i) {
17635      StringRef piece(*args[i]);
17636      if (!s.startswith(piece)) // Check if the piece matches.
17637        return false;
17638
17639      s = s.substr(piece.size());
17640      StringRef::size_type pos = s.find_first_not_of(" \t");
17641      if (pos == 0) // We matched a prefix.
17642        return false;
17643
17644      s = s.substr(pos);
17645    }
17646
17647    return s.empty();
17648  }
17649  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17650}
17651
17652bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17653  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17654
17655  std::string AsmStr = IA->getAsmString();
17656
17657  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17658  if (!Ty || Ty->getBitWidth() % 16 != 0)
17659    return false;
17660
17661  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17662  SmallVector<StringRef, 4> AsmPieces;
17663  SplitString(AsmStr, AsmPieces, ";\n");
17664
17665  switch (AsmPieces.size()) {
17666  default: return false;
17667  case 1:
17668    // FIXME: this should verify that we are targeting a 486 or better.  If not,
17669    // we will turn this bswap into something that will be lowered to logical
17670    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17671    // lower so don't worry about this.
17672    // bswap $0
17673    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17674        matchAsm(AsmPieces[0], "bswapl", "$0") ||
17675        matchAsm(AsmPieces[0], "bswapq", "$0") ||
17676        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17677        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17678        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17679      // No need to check constraints, nothing other than the equivalent of
17680      // "=r,0" would be valid here.
17681      return IntrinsicLowering::LowerToByteSwap(CI);
17682    }
17683
17684    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17685    if (CI->getType()->isIntegerTy(16) &&
17686        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17687        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17688         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17689      AsmPieces.clear();
17690      const std::string &ConstraintsStr = IA->getConstraintString();
17691      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17692      array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17693      if (AsmPieces.size() == 4 &&
17694          AsmPieces[0] == "~{cc}" &&
17695          AsmPieces[1] == "~{dirflag}" &&
17696          AsmPieces[2] == "~{flags}" &&
17697          AsmPieces[3] == "~{fpsr}")
17698      return IntrinsicLowering::LowerToByteSwap(CI);
17699    }
17700    break;
17701  case 3:
17702    if (CI->getType()->isIntegerTy(32) &&
17703        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17704        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17705        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17706        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17707      AsmPieces.clear();
17708      const std::string &ConstraintsStr = IA->getConstraintString();
17709      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17710      array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17711      if (AsmPieces.size() == 4 &&
17712          AsmPieces[0] == "~{cc}" &&
17713          AsmPieces[1] == "~{dirflag}" &&
17714          AsmPieces[2] == "~{flags}" &&
17715          AsmPieces[3] == "~{fpsr}")
17716        return IntrinsicLowering::LowerToByteSwap(CI);
17717    }
17718
17719    if (CI->getType()->isIntegerTy(64)) {
17720      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17721      if (Constraints.size() >= 2 &&
17722          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17723          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17724        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17725        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17726            matchAsm(AsmPieces[1], "bswap", "%edx") &&
17727            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17728          return IntrinsicLowering::LowerToByteSwap(CI);
17729      }
17730    }
17731    break;
17732  }
17733  return false;
17734}
17735
17736/// getConstraintType - Given a constraint letter, return the type of
17737/// constraint it is for this target.
17738X86TargetLowering::ConstraintType
17739X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17740  if (Constraint.size() == 1) {
17741    switch (Constraint[0]) {
17742    case 'R':
17743    case 'q':
17744    case 'Q':
17745    case 'f':
17746    case 't':
17747    case 'u':
17748    case 'y':
17749    case 'x':
17750    case 'Y':
17751    case 'l':
17752      return C_RegisterClass;
17753    case 'a':
17754    case 'b':
17755    case 'c':
17756    case 'd':
17757    case 'S':
17758    case 'D':
17759    case 'A':
17760      return C_Register;
17761    case 'I':
17762    case 'J':
17763    case 'K':
17764    case 'L':
17765    case 'M':
17766    case 'N':
17767    case 'G':
17768    case 'C':
17769    case 'e':
17770    case 'Z':
17771      return C_Other;
17772    default:
17773      break;
17774    }
17775  }
17776  return TargetLowering::getConstraintType(Constraint);
17777}
17778
17779/// Examine constraint type and operand type and determine a weight value.
17780/// This object must already have been set up with the operand type
17781/// and the current alternative constraint selected.
17782TargetLowering::ConstraintWeight
17783  X86TargetLowering::getSingleConstraintMatchWeight(
17784    AsmOperandInfo &info, const char *constraint) const {
17785  ConstraintWeight weight = CW_Invalid;
17786  Value *CallOperandVal = info.CallOperandVal;
17787    // If we don't have a value, we can't do a match,
17788    // but allow it at the lowest weight.
17789  if (CallOperandVal == NULL)
17790    return CW_Default;
17791  Type *type = CallOperandVal->getType();
17792  // Look at the constraint type.
17793  switch (*constraint) {
17794  default:
17795    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17796  case 'R':
17797  case 'q':
17798  case 'Q':
17799  case 'a':
17800  case 'b':
17801  case 'c':
17802  case 'd':
17803  case 'S':
17804  case 'D':
17805  case 'A':
17806    if (CallOperandVal->getType()->isIntegerTy())
17807      weight = CW_SpecificReg;
17808    break;
17809  case 'f':
17810  case 't':
17811  case 'u':
17812    if (type->isFloatingPointTy())
17813      weight = CW_SpecificReg;
17814    break;
17815  case 'y':
17816    if (type->isX86_MMXTy() && Subtarget->hasMMX())
17817      weight = CW_SpecificReg;
17818    break;
17819  case 'x':
17820  case 'Y':
17821    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17822        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17823      weight = CW_Register;
17824    break;
17825  case 'I':
17826    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17827      if (C->getZExtValue() <= 31)
17828        weight = CW_Constant;
17829    }
17830    break;
17831  case 'J':
17832    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17833      if (C->getZExtValue() <= 63)
17834        weight = CW_Constant;
17835    }
17836    break;
17837  case 'K':
17838    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17839      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17840        weight = CW_Constant;
17841    }
17842    break;
17843  case 'L':
17844    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17845      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17846        weight = CW_Constant;
17847    }
17848    break;
17849  case 'M':
17850    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17851      if (C->getZExtValue() <= 3)
17852        weight = CW_Constant;
17853    }
17854    break;
17855  case 'N':
17856    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17857      if (C->getZExtValue() <= 0xff)
17858        weight = CW_Constant;
17859    }
17860    break;
17861  case 'G':
17862  case 'C':
17863    if (dyn_cast<ConstantFP>(CallOperandVal)) {
17864      weight = CW_Constant;
17865    }
17866    break;
17867  case 'e':
17868    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17869      if ((C->getSExtValue() >= -0x80000000LL) &&
17870          (C->getSExtValue() <= 0x7fffffffLL))
17871        weight = CW_Constant;
17872    }
17873    break;
17874  case 'Z':
17875    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17876      if (C->getZExtValue() <= 0xffffffff)
17877        weight = CW_Constant;
17878    }
17879    break;
17880  }
17881  return weight;
17882}
17883
17884/// LowerXConstraint - try to replace an X constraint, which matches anything,
17885/// with another that has more specific requirements based on the type of the
17886/// corresponding operand.
17887const char *X86TargetLowering::
17888LowerXConstraint(EVT ConstraintVT) const {
17889  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17890  // 'f' like normal targets.
17891  if (ConstraintVT.isFloatingPoint()) {
17892    if (Subtarget->hasSSE2())
17893      return "Y";
17894    if (Subtarget->hasSSE1())
17895      return "x";
17896  }
17897
17898  return TargetLowering::LowerXConstraint(ConstraintVT);
17899}
17900
17901/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17902/// vector.  If it is invalid, don't add anything to Ops.
17903void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17904                                                     std::string &Constraint,
17905                                                     std::vector<SDValue>&Ops,
17906                                                     SelectionDAG &DAG) const {
17907  SDValue Result(0, 0);
17908
17909  // Only support length 1 constraints for now.
17910  if (Constraint.length() > 1) return;
17911
17912  char ConstraintLetter = Constraint[0];
17913  switch (ConstraintLetter) {
17914  default: break;
17915  case 'I':
17916    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17917      if (C->getZExtValue() <= 31) {
17918        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17919        break;
17920      }
17921    }
17922    return;
17923  case 'J':
17924    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17925      if (C->getZExtValue() <= 63) {
17926        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17927        break;
17928      }
17929    }
17930    return;
17931  case 'K':
17932    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17933      if (isInt<8>(C->getSExtValue())) {
17934        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17935        break;
17936      }
17937    }
17938    return;
17939  case 'N':
17940    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17941      if (C->getZExtValue() <= 255) {
17942        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17943        break;
17944      }
17945    }
17946    return;
17947  case 'e': {
17948    // 32-bit signed value
17949    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17950      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17951                                           C->getSExtValue())) {
17952        // Widen to 64 bits here to get it sign extended.
17953        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17954        break;
17955      }
17956    // FIXME gcc accepts some relocatable values here too, but only in certain
17957    // memory models; it's complicated.
17958    }
17959    return;
17960  }
17961  case 'Z': {
17962    // 32-bit unsigned value
17963    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17964      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17965                                           C->getZExtValue())) {
17966        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17967        break;
17968      }
17969    }
17970    // FIXME gcc accepts some relocatable values here too, but only in certain
17971    // memory models; it's complicated.
17972    return;
17973  }
17974  case 'i': {
17975    // Literal immediates are always ok.
17976    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17977      // Widen to 64 bits here to get it sign extended.
17978      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17979      break;
17980    }
17981
17982    // In any sort of PIC mode addresses need to be computed at runtime by
17983    // adding in a register or some sort of table lookup.  These can't
17984    // be used as immediates.
17985    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17986      return;
17987
17988    // If we are in non-pic codegen mode, we allow the address of a global (with
17989    // an optional displacement) to be used with 'i'.
17990    GlobalAddressSDNode *GA = 0;
17991    int64_t Offset = 0;
17992
17993    // Match either (GA), (GA+C), (GA+C1+C2), etc.
17994    while (1) {
17995      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17996        Offset += GA->getOffset();
17997        break;
17998      } else if (Op.getOpcode() == ISD::ADD) {
17999        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18000          Offset += C->getZExtValue();
18001          Op = Op.getOperand(0);
18002          continue;
18003        }
18004      } else if (Op.getOpcode() == ISD::SUB) {
18005        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18006          Offset += -C->getZExtValue();
18007          Op = Op.getOperand(0);
18008          continue;
18009        }
18010      }
18011
18012      // Otherwise, this isn't something we can handle, reject it.
18013      return;
18014    }
18015
18016    const GlobalValue *GV = GA->getGlobal();
18017    // If we require an extra load to get this address, as in PIC mode, we
18018    // can't accept it.
18019    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18020                                                        getTargetMachine())))
18021      return;
18022
18023    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18024                                        GA->getValueType(0), Offset);
18025    break;
18026  }
18027  }
18028
18029  if (Result.getNode()) {
18030    Ops.push_back(Result);
18031    return;
18032  }
18033  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18034}
18035
18036std::pair<unsigned, const TargetRegisterClass*>
18037X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18038                                                EVT VT) const {
18039  // First, see if this is a constraint that directly corresponds to an LLVM
18040  // register class.
18041  if (Constraint.size() == 1) {
18042    // GCC Constraint Letters
18043    switch (Constraint[0]) {
18044    default: break;
18045      // TODO: Slight differences here in allocation order and leaving
18046      // RIP in the class. Do they matter any more here than they do
18047      // in the normal allocation?
18048    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18049      if (Subtarget->is64Bit()) {
18050        if (VT == MVT::i32 || VT == MVT::f32)
18051          return std::make_pair(0U, &X86::GR32RegClass);
18052        if (VT == MVT::i16)
18053          return std::make_pair(0U, &X86::GR16RegClass);
18054        if (VT == MVT::i8 || VT == MVT::i1)
18055          return std::make_pair(0U, &X86::GR8RegClass);
18056        if (VT == MVT::i64 || VT == MVT::f64)
18057          return std::make_pair(0U, &X86::GR64RegClass);
18058        break;
18059      }
18060      // 32-bit fallthrough
18061    case 'Q':   // Q_REGS
18062      if (VT == MVT::i32 || VT == MVT::f32)
18063        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18064      if (VT == MVT::i16)
18065        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18066      if (VT == MVT::i8 || VT == MVT::i1)
18067        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18068      if (VT == MVT::i64)
18069        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18070      break;
18071    case 'r':   // GENERAL_REGS
18072    case 'l':   // INDEX_REGS
18073      if (VT == MVT::i8 || VT == MVT::i1)
18074        return std::make_pair(0U, &X86::GR8RegClass);
18075      if (VT == MVT::i16)
18076        return std::make_pair(0U, &X86::GR16RegClass);
18077      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18078        return std::make_pair(0U, &X86::GR32RegClass);
18079      return std::make_pair(0U, &X86::GR64RegClass);
18080    case 'R':   // LEGACY_REGS
18081      if (VT == MVT::i8 || VT == MVT::i1)
18082        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18083      if (VT == MVT::i16)
18084        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18085      if (VT == MVT::i32 || !Subtarget->is64Bit())
18086        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18087      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18088    case 'f':  // FP Stack registers.
18089      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18090      // value to the correct fpstack register class.
18091      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18092        return std::make_pair(0U, &X86::RFP32RegClass);
18093      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18094        return std::make_pair(0U, &X86::RFP64RegClass);
18095      return std::make_pair(0U, &X86::RFP80RegClass);
18096    case 'y':   // MMX_REGS if MMX allowed.
18097      if (!Subtarget->hasMMX()) break;
18098      return std::make_pair(0U, &X86::VR64RegClass);
18099    case 'Y':   // SSE_REGS if SSE2 allowed
18100      if (!Subtarget->hasSSE2()) break;
18101      // FALL THROUGH.
18102    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18103      if (!Subtarget->hasSSE1()) break;
18104
18105      switch (VT.getSimpleVT().SimpleTy) {
18106      default: break;
18107      // Scalar SSE types.
18108      case MVT::f32:
18109      case MVT::i32:
18110        return std::make_pair(0U, &X86::FR32RegClass);
18111      case MVT::f64:
18112      case MVT::i64:
18113        return std::make_pair(0U, &X86::FR64RegClass);
18114      // Vector types.
18115      case MVT::v16i8:
18116      case MVT::v8i16:
18117      case MVT::v4i32:
18118      case MVT::v2i64:
18119      case MVT::v4f32:
18120      case MVT::v2f64:
18121        return std::make_pair(0U, &X86::VR128RegClass);
18122      // AVX types.
18123      case MVT::v32i8:
18124      case MVT::v16i16:
18125      case MVT::v8i32:
18126      case MVT::v4i64:
18127      case MVT::v8f32:
18128      case MVT::v4f64:
18129        return std::make_pair(0U, &X86::VR256RegClass);
18130      }
18131      break;
18132    }
18133  }
18134
18135  // Use the default implementation in TargetLowering to convert the register
18136  // constraint into a member of a register class.
18137  std::pair<unsigned, const TargetRegisterClass*> Res;
18138  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18139
18140  // Not found as a standard register?
18141  if (Res.second == 0) {
18142    // Map st(0) -> st(7) -> ST0
18143    if (Constraint.size() == 7 && Constraint[0] == '{' &&
18144        tolower(Constraint[1]) == 's' &&
18145        tolower(Constraint[2]) == 't' &&
18146        Constraint[3] == '(' &&
18147        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18148        Constraint[5] == ')' &&
18149        Constraint[6] == '}') {
18150
18151      Res.first = X86::ST0+Constraint[4]-'0';
18152      Res.second = &X86::RFP80RegClass;
18153      return Res;
18154    }
18155
18156    // GCC allows "st(0)" to be called just plain "st".
18157    if (StringRef("{st}").equals_lower(Constraint)) {
18158      Res.first = X86::ST0;
18159      Res.second = &X86::RFP80RegClass;
18160      return Res;
18161    }
18162
18163    // flags -> EFLAGS
18164    if (StringRef("{flags}").equals_lower(Constraint)) {
18165      Res.first = X86::EFLAGS;
18166      Res.second = &X86::CCRRegClass;
18167      return Res;
18168    }
18169
18170    // 'A' means EAX + EDX.
18171    if (Constraint == "A") {
18172      Res.first = X86::EAX;
18173      Res.second = &X86::GR32_ADRegClass;
18174      return Res;
18175    }
18176    return Res;
18177  }
18178
18179  // Otherwise, check to see if this is a register class of the wrong value
18180  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18181  // turn into {ax},{dx}.
18182  if (Res.second->hasType(VT))
18183    return Res;   // Correct type already, nothing to do.
18184
18185  // All of the single-register GCC register classes map their values onto
18186  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18187  // really want an 8-bit or 32-bit register, map to the appropriate register
18188  // class and return the appropriate register.
18189  if (Res.second == &X86::GR16RegClass) {
18190    if (VT == MVT::i8 || VT == MVT::i1) {
18191      unsigned DestReg = 0;
18192      switch (Res.first) {
18193      default: break;
18194      case X86::AX: DestReg = X86::AL; break;
18195      case X86::DX: DestReg = X86::DL; break;
18196      case X86::CX: DestReg = X86::CL; break;
18197      case X86::BX: DestReg = X86::BL; break;
18198      }
18199      if (DestReg) {
18200        Res.first = DestReg;
18201        Res.second = &X86::GR8RegClass;
18202      }
18203    } else if (VT == MVT::i32 || VT == MVT::f32) {
18204      unsigned DestReg = 0;
18205      switch (Res.first) {
18206      default: break;
18207      case X86::AX: DestReg = X86::EAX; break;
18208      case X86::DX: DestReg = X86::EDX; break;
18209      case X86::CX: DestReg = X86::ECX; break;
18210      case X86::BX: DestReg = X86::EBX; break;
18211      case X86::SI: DestReg = X86::ESI; break;
18212      case X86::DI: DestReg = X86::EDI; break;
18213      case X86::BP: DestReg = X86::EBP; break;
18214      case X86::SP: DestReg = X86::ESP; break;
18215      }
18216      if (DestReg) {
18217        Res.first = DestReg;
18218        Res.second = &X86::GR32RegClass;
18219      }
18220    } else if (VT == MVT::i64 || VT == MVT::f64) {
18221      unsigned DestReg = 0;
18222      switch (Res.first) {
18223      default: break;
18224      case X86::AX: DestReg = X86::RAX; break;
18225      case X86::DX: DestReg = X86::RDX; break;
18226      case X86::CX: DestReg = X86::RCX; break;
18227      case X86::BX: DestReg = X86::RBX; break;
18228      case X86::SI: DestReg = X86::RSI; break;
18229      case X86::DI: DestReg = X86::RDI; break;
18230      case X86::BP: DestReg = X86::RBP; break;
18231      case X86::SP: DestReg = X86::RSP; break;
18232      }
18233      if (DestReg) {
18234        Res.first = DestReg;
18235        Res.second = &X86::GR64RegClass;
18236      }
18237    }
18238  } else if (Res.second == &X86::FR32RegClass ||
18239             Res.second == &X86::FR64RegClass ||
18240             Res.second == &X86::VR128RegClass) {
18241    // Handle references to XMM physical registers that got mapped into the
18242    // wrong class.  This can happen with constraints like {xmm0} where the
18243    // target independent register mapper will just pick the first match it can
18244    // find, ignoring the required type.
18245
18246    if (VT == MVT::f32 || VT == MVT::i32)
18247      Res.second = &X86::FR32RegClass;
18248    else if (VT == MVT::f64 || VT == MVT::i64)
18249      Res.second = &X86::FR64RegClass;
18250    else if (X86::VR128RegClass.hasType(VT))
18251      Res.second = &X86::VR128RegClass;
18252    else if (X86::VR256RegClass.hasType(VT))
18253      Res.second = &X86::VR256RegClass;
18254  }
18255
18256  return Res;
18257}
18258