X86ISelLowering.cpp revision 4362067d7c89291efe1cbe7d08e316d9ac4ca1c7
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 "X86.h"
18#include "X86InstrBuilder.h"
19#include "X86TargetMachine.h"
20#include "X86TargetObjectFile.h"
21#include "Utils/X86ShuffleDecode.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/GlobalVariable.h"
27#include "llvm/Function.h"
28#include "llvm/Instructions.h"
29#include "llvm/Intrinsics.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCContext.h"
40#include "llvm/MC/MCExpr.h"
41#include "llvm/MC/MCSymbol.h"
42#include "llvm/ADT/SmallSet.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/ADT/VariadicFunction.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  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163  RegInfo = TM.getRegisterInfo();
164  TD = getTargetData();
165
166  // Set up the TargetLowering object.
167  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169  // X86 is weird, it always uses i8 for shift amounts and setcc results.
170  setBooleanContents(ZeroOrOneBooleanContent);
171  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174  // For 64-bit since we have so many registers use the ILP scheduler, for
175  // 32-bit code use the register pressure specific scheduling.
176  // For Atom, always use ILP scheduling.
177  if (Subtarget->isAtom())
178    setSchedulingPreference(Sched::ILP);
179  else if (Subtarget->is64Bit())
180    setSchedulingPreference(Sched::ILP);
181  else
182    setSchedulingPreference(Sched::RegPressure);
183  setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185  // Bypass i32 with i8 on Atom when compiling with O2
186  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187    addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
188
189  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190    // Setup Windows compiler runtime calls.
191    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193    setLibcallName(RTLIB::SREM_I64, "_allrem");
194    setLibcallName(RTLIB::UREM_I64, "_aullrem");
195    setLibcallName(RTLIB::MUL_I64, "_allmul");
196    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201
202    // The _ftol2 runtime function has an unusual calling conv, which
203    // is modeled by a special pseudo-instruction.
204    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208  }
209
210  if (Subtarget->isTargetDarwin()) {
211    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212    setUseUnderscoreSetJmp(false);
213    setUseUnderscoreLongJmp(false);
214  } else if (Subtarget->isTargetMingw()) {
215    // MS runtime is weird: it exports _setjmp, but longjmp!
216    setUseUnderscoreSetJmp(true);
217    setUseUnderscoreLongJmp(false);
218  } else {
219    setUseUnderscoreSetJmp(true);
220    setUseUnderscoreLongJmp(true);
221  }
222
223  // Set up the register classes.
224  addRegisterClass(MVT::i8, &X86::GR8RegClass);
225  addRegisterClass(MVT::i16, &X86::GR16RegClass);
226  addRegisterClass(MVT::i32, &X86::GR32RegClass);
227  if (Subtarget->is64Bit())
228    addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232  // We don't accept any truncstore of integer registers.
233  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240  // SETOEQ and SETUNE require checking two conditions.
241  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249  // operation.
250  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254  if (Subtarget->is64Bit()) {
255    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257  } else if (!TM.Options.UseSoftFloat) {
258    // We have an algorithm for SSE2->double, and we turn this into a
259    // 64-bit FILD followed by conditional FADD for other targets.
260    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261    // We have an algorithm for SSE2, and we turn this into a 64-bit
262    // FILD for other targets.
263    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264  }
265
266  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267  // this operation.
268  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271  if (!TM.Options.UseSoftFloat) {
272    // SSE has no i16 to fp conversion, only i32
273    if (X86ScalarSSEf32) {
274      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275      // f32 and f64 cases are Legal, f80 case is not
276      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277    } else {
278      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280    }
281  } else {
282    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284  }
285
286  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287  // are Legal, f80 is custom lowered.
288  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292  // this operation.
293  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296  if (X86ScalarSSEf32) {
297    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298    // f32 and f64 cases are Legal, f80 case is not
299    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300  } else {
301    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303  }
304
305  // Handle FP_TO_UINT by promoting the destination to a larger signed
306  // conversion.
307  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311  if (Subtarget->is64Bit()) {
312    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314  } else if (!TM.Options.UseSoftFloat) {
315    // Since AVX is a superset of SSE3, only check for SSE here.
316    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317      // Expand FP_TO_UINT into a select.
318      // FIXME: We would like to use a Custom expander here eventually to do
319      // the optimal thing for SSE vs. the default expansion in the legalizer.
320      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321    else
322      // With SSE3 we can use fisttpll to convert to a signed i64; without
323      // SSE, we're stuck with a fistpll.
324      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325  }
326
327  if (isTargetFTOL()) {
328    // Use the _ftol2 runtime function, which has a pseudo-instruction
329    // to handle its weird calling convention.
330    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331  }
332
333  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334  if (!X86ScalarSSEf64) {
335    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337    if (Subtarget->is64Bit()) {
338      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339      // Without SSE, i64->f64 goes through memory.
340      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341    }
342  }
343
344  // Scalar integer divide and remainder are lowered to use operations that
345  // produce two results, to match the available instructions. This exposes
346  // the two-result form to trivial CSE, which is able to combine x/y and x%y
347  // into a single instruction.
348  //
349  // Scalar integer multiply-high is also lowered to use two-result
350  // operations, to match the available instructions. However, plain multiply
351  // (low) operations are left as Legal, as there are single-result
352  // instructions for this in x86. Using the two-result multiply instructions
353  // when both high and low results are needed must be arranged by dagcombine.
354  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355    MVT VT = IntVTs[i];
356    setOperationAction(ISD::MULHS, VT, Expand);
357    setOperationAction(ISD::MULHU, VT, Expand);
358    setOperationAction(ISD::SDIV, VT, Expand);
359    setOperationAction(ISD::UDIV, VT, Expand);
360    setOperationAction(ISD::SREM, VT, Expand);
361    setOperationAction(ISD::UREM, VT, Expand);
362
363    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364    setOperationAction(ISD::ADDC, VT, Custom);
365    setOperationAction(ISD::ADDE, VT, Custom);
366    setOperationAction(ISD::SUBC, VT, Custom);
367    setOperationAction(ISD::SUBE, VT, Custom);
368  }
369
370  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374  if (Subtarget->is64Bit())
375    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385  // Promote the i8 variants and force them on up to i32 which has a shorter
386  // encoding.
387  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391  if (Subtarget->hasBMI()) {
392    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394    if (Subtarget->is64Bit())
395      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396  } else {
397    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399    if (Subtarget->is64Bit())
400      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401  }
402
403  if (Subtarget->hasLZCNT()) {
404    // When promoting the i8 variants, force them to i32 for a shorter
405    // encoding.
406    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412    if (Subtarget->is64Bit())
413      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414  } else {
415    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421    if (Subtarget->is64Bit()) {
422      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424    }
425  }
426
427  if (Subtarget->hasPOPCNT()) {
428    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429  } else {
430    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433    if (Subtarget->is64Bit())
434      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435  }
436
437  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440  // These should be promoted to a larger select which is supported.
441  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442  // X86 wants to expand cmov itself.
443  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455  if (Subtarget->is64Bit()) {
456    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458  }
459  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460
461  // Darwin ABI issue.
462  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
463  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
464  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
465  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
466  if (Subtarget->is64Bit())
467    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
469  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
470  if (Subtarget->is64Bit()) {
471    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
472    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
473    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
474    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
475    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
476  }
477  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
479  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
480  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
481  if (Subtarget->is64Bit()) {
482    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
483    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
484    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
485  }
486
487  if (Subtarget->hasSSE1())
488    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
489
490  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
491  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
492
493  // On X86 and X86-64, atomic operations are lowered to locked instructions.
494  // Locked instructions, in turn, have implicit fence semantics (all memory
495  // operations are flushed before issuing the locked instruction, and they
496  // are not buffered), so we can fold away the common pattern of
497  // fence-atomic-fence.
498  setShouldFoldAtomicFences(true);
499
500  // Expand certain atomics
501  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
502    MVT VT = IntVTs[i];
503    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506  }
507
508  if (!Subtarget->is64Bit()) {
509    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517  }
518
519  if (Subtarget->hasCmpxchg16b()) {
520    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
521  }
522
523  // FIXME - use subtarget debug flags
524  if (!Subtarget->isTargetDarwin() &&
525      !Subtarget->isTargetELF() &&
526      !Subtarget->isTargetCygMing()) {
527    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528  }
529
530  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
532  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
534  if (Subtarget->is64Bit()) {
535    setExceptionPointerRegister(X86::RAX);
536    setExceptionSelectorRegister(X86::RDX);
537  } else {
538    setExceptionPointerRegister(X86::EAX);
539    setExceptionSelectorRegister(X86::EDX);
540  }
541  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
543
544  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
546
547  setOperationAction(ISD::TRAP, MVT::Other, Legal);
548
549  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
551  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
552  if (Subtarget->is64Bit()) {
553    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
554    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
555  } else {
556    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
557    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
558  }
559
560  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
561  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
562
563  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565                       MVT::i64 : MVT::i32, Custom);
566  else if (TM.Options.EnableSegmentedStacks)
567    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568                       MVT::i64 : MVT::i32, Custom);
569  else
570    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571                       MVT::i64 : MVT::i32, Expand);
572
573  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574    // f32 and f64 use SSE.
575    // Set up the FP register classes.
576    addRegisterClass(MVT::f32, &X86::FR32RegClass);
577    addRegisterClass(MVT::f64, &X86::FR64RegClass);
578
579    // Use ANDPD to simulate FABS.
580    setOperationAction(ISD::FABS , MVT::f64, Custom);
581    setOperationAction(ISD::FABS , MVT::f32, Custom);
582
583    // Use XORP to simulate FNEG.
584    setOperationAction(ISD::FNEG , MVT::f64, Custom);
585    setOperationAction(ISD::FNEG , MVT::f32, Custom);
586
587    // Use ANDPD and ORPD to simulate FCOPYSIGN.
588    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
590
591    // Lower this to FGETSIGNx86 plus an AND.
592    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
594
595    // We don't support sin/cos/fmod
596    setOperationAction(ISD::FSIN , MVT::f64, Expand);
597    setOperationAction(ISD::FCOS , MVT::f64, Expand);
598    setOperationAction(ISD::FSIN , MVT::f32, Expand);
599    setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601    // Expand FP immediates into loads from the stack, except for the special
602    // cases we handle.
603    addLegalFPImmediate(APFloat(+0.0)); // xorpd
604    addLegalFPImmediate(APFloat(+0.0f)); // xorps
605  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606    // Use SSE for f32, x87 for f64.
607    // Set up the FP register classes.
608    addRegisterClass(MVT::f32, &X86::FR32RegClass);
609    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
610
611    // Use ANDPS to simulate FABS.
612    setOperationAction(ISD::FABS , MVT::f32, Custom);
613
614    // Use XORP to simulate FNEG.
615    setOperationAction(ISD::FNEG , MVT::f32, Custom);
616
617    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
618
619    // Use ANDPS and ORPS to simulate FCOPYSIGN.
620    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
622
623    // We don't support sin/cos/fmod
624    setOperationAction(ISD::FSIN , MVT::f32, Expand);
625    setOperationAction(ISD::FCOS , MVT::f32, Expand);
626
627    // Special cases we handle for FP constants.
628    addLegalFPImmediate(APFloat(+0.0f)); // xorps
629    addLegalFPImmediate(APFloat(+0.0)); // FLD0
630    addLegalFPImmediate(APFloat(+1.0)); // FLD1
631    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633
634    if (!TM.Options.UnsafeFPMath) {
635      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
636      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
637    }
638  } else if (!TM.Options.UseSoftFloat) {
639    // f32 and f64 in x87.
640    // Set up the FP register classes.
641    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
643
644    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
645    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
646    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
648
649    if (!TM.Options.UnsafeFPMath) {
650      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
651      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
652    }
653    addLegalFPImmediate(APFloat(+0.0)); // FLD0
654    addLegalFPImmediate(APFloat(+1.0)); // FLD1
655    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
661  }
662
663  // We don't support FMA.
664  setOperationAction(ISD::FMA, MVT::f64, Expand);
665  setOperationAction(ISD::FMA, MVT::f32, Expand);
666
667  // Long double always uses X87.
668  if (!TM.Options.UseSoftFloat) {
669    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
671    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
672    {
673      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674      addLegalFPImmediate(TmpFlt);  // FLD0
675      TmpFlt.changeSign();
676      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
677
678      bool ignored;
679      APFloat TmpFlt2(+1.0);
680      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
681                      &ignored);
682      addLegalFPImmediate(TmpFlt2);  // FLD1
683      TmpFlt2.changeSign();
684      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
685    }
686
687    if (!TM.Options.UnsafeFPMath) {
688      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
689      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
690    }
691
692    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
694    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
696    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697    setOperationAction(ISD::FMA, MVT::f80, Expand);
698  }
699
700  // Always use a library call for pow.
701  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
702  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
703  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
704
705  setOperationAction(ISD::FLOG, MVT::f80, Expand);
706  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708  setOperationAction(ISD::FEXP, MVT::f80, Expand);
709  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
710
711  // First set operation action for all vector types to either promote
712  // (for widening) or expand (for scalarization). Then we will selectively
713  // turn on ones that can be effectively codegen'd.
714  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715           VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738    setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
739    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742    setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750    setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752    setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759    setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
771    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
772    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
773    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
774    setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
775    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777      setTruncStoreAction((MVT::SimpleValueType)VT,
778                          (MVT::SimpleValueType)InnerVT, Expand);
779    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
782  }
783
784  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785  // with -msoft-float, disable use of MMX as well.
786  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788    // No operations on x86mmx supported, everything uses intrinsics.
789  }
790
791  // MMX-sized vectors (other than x86mmx) are expected to be expanded
792  // into smaller operations.
793  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
794  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
795  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
796  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
797  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
798  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
799  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
800  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
801  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
802  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
803  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
804  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
805  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
806  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
807  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
808  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
809  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
810  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
811  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
812  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
813  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
814  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
815  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
816  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
817  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
818  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
819  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
820  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
821  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
822
823  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
825
826    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
827    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
828    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
829    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
830    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
831    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
832    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
833    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
834    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
835    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
836    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
838  }
839
840  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
842
843    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844    // registers cannot be used even for integer operations.
845    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
849
850    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
851    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
852    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
853    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
854    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
855    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
856    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
857    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
858    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
859    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
860    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
861    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
862    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
863    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
864    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
865    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
866    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
867
868    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
869    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
870    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
871    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
872
873    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
874    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
875    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
876    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
877    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
878
879    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881      MVT VT = (MVT::SimpleValueType)i;
882      // Do not attempt to custom lower non-power-of-2 vectors
883      if (!isPowerOf2_32(VT.getVectorNumElements()))
884        continue;
885      // Do not attempt to custom lower non-128-bit vectors
886      if (!VT.is128BitVector())
887        continue;
888      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
889      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
890      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891    }
892
893    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
894    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
895    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
896    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
897    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900    if (Subtarget->is64Bit()) {
901      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903    }
904
905    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907      MVT VT = (MVT::SimpleValueType)i;
908
909      // Do not attempt to promote non-128-bit vectors
910      if (!VT.is128BitVector())
911        continue;
912
913      setOperationAction(ISD::AND,    VT, Promote);
914      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915      setOperationAction(ISD::OR,     VT, Promote);
916      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917      setOperationAction(ISD::XOR,    VT, Promote);
918      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919      setOperationAction(ISD::LOAD,   VT, Promote);
920      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921      setOperationAction(ISD::SELECT, VT, Promote);
922      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923    }
924
925    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
926
927    // Custom lower v2i64 and v2f64 selects.
928    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
929    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
930    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
931    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
932
933    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
934    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
935  }
936
937  if (Subtarget->hasSSE41()) {
938    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
939    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
940    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
941    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
942    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
943    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
944    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
945    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
946    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
947    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
948
949    // FIXME: Do we need to handle scalar-to-vector here?
950    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
951
952    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
953    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
954    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
955    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
956    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
957
958    // i8 and i16 vectors are custom , because the source register and source
959    // source memory operand types are not the same width.  f32 vectors are
960    // custom since the immediate controlling the insert encodes additional
961    // information.
962    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
963    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
968    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
969    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
970    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
971
972    // FIXME: these should be Legal but thats only for the case where
973    // the index is constant.  For now custom expand to deal with that.
974    if (Subtarget->is64Bit()) {
975      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
976      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
977    }
978  }
979
980  if (Subtarget->hasSSE2()) {
981    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
982    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
983
984    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
985    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
986
987    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
988    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
989
990    if (Subtarget->hasAVX2()) {
991      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
992      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
993
994      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
995      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
996
997      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
998    } else {
999      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1000      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1001
1002      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1003      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1004
1005      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1006    }
1007  }
1008
1009  if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1011    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1013    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1014    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1015    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1016
1017    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1018    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1019    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1020
1021    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1022    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1023    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1024    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1025    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1026    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1027    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1028
1029    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1030    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1031    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1032    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1033    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1034    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1035    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1036
1037    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1038    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1039    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1040
1041    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1042    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1043
1044    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1045    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1046
1047    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1048    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1049
1050    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1051    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1052    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1053    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1054
1055    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1056    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1057    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1058
1059    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1060    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1061    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1062    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1063
1064    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1065      setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1066      setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1067      setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1068      setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1069      setOperationAction(ISD::FMA,             MVT::f32, Custom);
1070      setOperationAction(ISD::FMA,             MVT::f64, Custom);
1071    }
1072
1073    if (Subtarget->hasAVX2()) {
1074      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1075      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1076      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1077      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1078
1079      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1080      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1081      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1082      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1083
1084      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1085      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1086      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1087      // Don't lower v32i8 because there is no 128-bit byte mul
1088
1089      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1090
1091      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1092      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1093
1094      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1095      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1096
1097      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1098    } else {
1099      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1100      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1101      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1102      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1103
1104      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1105      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1106      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1107      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1108
1109      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1110      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1111      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1112      // Don't lower v32i8 because there is no 128-bit byte mul
1113
1114      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1115      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1116
1117      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1118      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1119
1120      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1121    }
1122
1123    // Custom lower several nodes for 256-bit types.
1124    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1125             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1126      MVT VT = (MVT::SimpleValueType)i;
1127
1128      // Extract subvector is special because the value type
1129      // (result) is 128-bit but the source is 256-bit wide.
1130      if (VT.is128BitVector())
1131        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1132
1133      // Do not attempt to custom lower other non-256-bit vectors
1134      if (!VT.is256BitVector())
1135        continue;
1136
1137      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1138      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1139      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1140      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1141      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1142      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1143      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1144    }
1145
1146    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1147    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1148      MVT VT = (MVT::SimpleValueType)i;
1149
1150      // Do not attempt to promote non-256-bit vectors
1151      if (!VT.is256BitVector())
1152        continue;
1153
1154      setOperationAction(ISD::AND,    VT, Promote);
1155      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1156      setOperationAction(ISD::OR,     VT, Promote);
1157      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1158      setOperationAction(ISD::XOR,    VT, Promote);
1159      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1160      setOperationAction(ISD::LOAD,   VT, Promote);
1161      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1162      setOperationAction(ISD::SELECT, VT, Promote);
1163      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1164    }
1165  }
1166
1167  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1168  // of this type with custom code.
1169  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1170           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1171    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1172                       Custom);
1173  }
1174
1175  // We want to custom lower some of our intrinsics.
1176  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1177  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1178
1179
1180  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1181  // handle type legalization for these operations here.
1182  //
1183  // FIXME: We really should do custom legalization for addition and
1184  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1185  // than generic legalization for 64-bit multiplication-with-overflow, though.
1186  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1187    // Add/Sub/Mul with overflow operations are custom lowered.
1188    MVT VT = IntVTs[i];
1189    setOperationAction(ISD::SADDO, VT, Custom);
1190    setOperationAction(ISD::UADDO, VT, Custom);
1191    setOperationAction(ISD::SSUBO, VT, Custom);
1192    setOperationAction(ISD::USUBO, VT, Custom);
1193    setOperationAction(ISD::SMULO, VT, Custom);
1194    setOperationAction(ISD::UMULO, VT, Custom);
1195  }
1196
1197  // There are no 8-bit 3-address imul/mul instructions
1198  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1199  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1200
1201  if (!Subtarget->is64Bit()) {
1202    // These libcalls are not available in 32-bit.
1203    setLibcallName(RTLIB::SHL_I128, 0);
1204    setLibcallName(RTLIB::SRL_I128, 0);
1205    setLibcallName(RTLIB::SRA_I128, 0);
1206  }
1207
1208  // We have target-specific dag combine patterns for the following nodes:
1209  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1210  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1211  setTargetDAGCombine(ISD::VSELECT);
1212  setTargetDAGCombine(ISD::SELECT);
1213  setTargetDAGCombine(ISD::SHL);
1214  setTargetDAGCombine(ISD::SRA);
1215  setTargetDAGCombine(ISD::SRL);
1216  setTargetDAGCombine(ISD::OR);
1217  setTargetDAGCombine(ISD::AND);
1218  setTargetDAGCombine(ISD::ADD);
1219  setTargetDAGCombine(ISD::FADD);
1220  setTargetDAGCombine(ISD::FSUB);
1221  setTargetDAGCombine(ISD::FMA);
1222  setTargetDAGCombine(ISD::SUB);
1223  setTargetDAGCombine(ISD::LOAD);
1224  setTargetDAGCombine(ISD::STORE);
1225  setTargetDAGCombine(ISD::ZERO_EXTEND);
1226  setTargetDAGCombine(ISD::ANY_EXTEND);
1227  setTargetDAGCombine(ISD::SIGN_EXTEND);
1228  setTargetDAGCombine(ISD::TRUNCATE);
1229  setTargetDAGCombine(ISD::UINT_TO_FP);
1230  setTargetDAGCombine(ISD::SINT_TO_FP);
1231  setTargetDAGCombine(ISD::SETCC);
1232  setTargetDAGCombine(ISD::FP_TO_SINT);
1233  if (Subtarget->is64Bit())
1234    setTargetDAGCombine(ISD::MUL);
1235  setTargetDAGCombine(ISD::XOR);
1236
1237  computeRegisterProperties();
1238
1239  // On Darwin, -Os means optimize for size without hurting performance,
1240  // do not reduce the limit.
1241  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1242  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1243  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1244  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1245  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1246  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1247  setPrefLoopAlignment(4); // 2^4 bytes.
1248  benefitFromCodePlacementOpt = true;
1249
1250  // Predictable cmov don't hurt on atom because it's in-order.
1251  predictableSelectIsExpensive = !Subtarget->isAtom();
1252
1253  setPrefFunctionAlignment(4); // 2^4 bytes.
1254}
1255
1256
1257EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1258  if (!VT.isVector()) return MVT::i8;
1259  return VT.changeVectorElementTypeToInteger();
1260}
1261
1262
1263/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1264/// the desired ByVal argument alignment.
1265static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1266  if (MaxAlign == 16)
1267    return;
1268  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1269    if (VTy->getBitWidth() == 128)
1270      MaxAlign = 16;
1271  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1272    unsigned EltAlign = 0;
1273    getMaxByValAlign(ATy->getElementType(), EltAlign);
1274    if (EltAlign > MaxAlign)
1275      MaxAlign = EltAlign;
1276  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1277    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278      unsigned EltAlign = 0;
1279      getMaxByValAlign(STy->getElementType(i), EltAlign);
1280      if (EltAlign > MaxAlign)
1281        MaxAlign = EltAlign;
1282      if (MaxAlign == 16)
1283        break;
1284    }
1285  }
1286}
1287
1288/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1289/// function arguments in the caller parameter area. For X86, aggregates
1290/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1291/// are at 4-byte boundaries.
1292unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1293  if (Subtarget->is64Bit()) {
1294    // Max of 8 and alignment of type.
1295    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1296    if (TyAlign > 8)
1297      return TyAlign;
1298    return 8;
1299  }
1300
1301  unsigned Align = 4;
1302  if (Subtarget->hasSSE1())
1303    getMaxByValAlign(Ty, Align);
1304  return Align;
1305}
1306
1307/// getOptimalMemOpType - Returns the target specific optimal type for load
1308/// and store operations as a result of memset, memcpy, and memmove
1309/// lowering. If DstAlign is zero that means it's safe to destination
1310/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1311/// means there isn't a need to check it against alignment requirement,
1312/// probably because the source does not need to be loaded. If
1313/// 'IsZeroVal' is true, that means it's safe to return a
1314/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1315/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1316/// constant so it does not need to be loaded.
1317/// It returns EVT::Other if the type should be determined using generic
1318/// target-independent logic.
1319EVT
1320X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1321                                       unsigned DstAlign, unsigned SrcAlign,
1322                                       bool IsZeroVal,
1323                                       bool MemcpyStrSrc,
1324                                       MachineFunction &MF) const {
1325  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1326  // linux.  This is because the stack realignment code can't handle certain
1327  // cases like PR2962.  This should be removed when PR2962 is fixed.
1328  const Function *F = MF.getFunction();
1329  if (IsZeroVal &&
1330      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1331    if (Size >= 16 &&
1332        (Subtarget->isUnalignedMemAccessFast() ||
1333         ((DstAlign == 0 || DstAlign >= 16) &&
1334          (SrcAlign == 0 || SrcAlign >= 16))) &&
1335        Subtarget->getStackAlignment() >= 16) {
1336      if (Subtarget->getStackAlignment() >= 32) {
1337        if (Subtarget->hasAVX2())
1338          return MVT::v8i32;
1339        if (Subtarget->hasAVX())
1340          return MVT::v8f32;
1341      }
1342      if (Subtarget->hasSSE2())
1343        return MVT::v4i32;
1344      if (Subtarget->hasSSE1())
1345        return MVT::v4f32;
1346    } else if (!MemcpyStrSrc && Size >= 8 &&
1347               !Subtarget->is64Bit() &&
1348               Subtarget->getStackAlignment() >= 8 &&
1349               Subtarget->hasSSE2()) {
1350      // Do not use f64 to lower memcpy if source is string constant. It's
1351      // better to use i32 to avoid the loads.
1352      return MVT::f64;
1353    }
1354  }
1355  if (Subtarget->is64Bit() && Size >= 8)
1356    return MVT::i64;
1357  return MVT::i32;
1358}
1359
1360/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1361/// current function.  The returned value is a member of the
1362/// MachineJumpTableInfo::JTEntryKind enum.
1363unsigned X86TargetLowering::getJumpTableEncoding() const {
1364  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1365  // symbol.
1366  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1367      Subtarget->isPICStyleGOT())
1368    return MachineJumpTableInfo::EK_Custom32;
1369
1370  // Otherwise, use the normal jump table encoding heuristics.
1371  return TargetLowering::getJumpTableEncoding();
1372}
1373
1374const MCExpr *
1375X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1376                                             const MachineBasicBlock *MBB,
1377                                             unsigned uid,MCContext &Ctx) const{
1378  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379         Subtarget->isPICStyleGOT());
1380  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1381  // entries.
1382  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1383                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1384}
1385
1386/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1387/// jumptable.
1388SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1389                                                    SelectionDAG &DAG) const {
1390  if (!Subtarget->is64Bit())
1391    // This doesn't have DebugLoc associated with it, but is not really the
1392    // same as a Register.
1393    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1394  return Table;
1395}
1396
1397/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1398/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1399/// MCExpr.
1400const MCExpr *X86TargetLowering::
1401getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1402                             MCContext &Ctx) const {
1403  // X86-64 uses RIP relative addressing based on the jump table label.
1404  if (Subtarget->isPICStyleRIPRel())
1405    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1406
1407  // Otherwise, the reference is relative to the PIC base.
1408  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1409}
1410
1411// FIXME: Why this routine is here? Move to RegInfo!
1412std::pair<const TargetRegisterClass*, uint8_t>
1413X86TargetLowering::findRepresentativeClass(EVT VT) const{
1414  const TargetRegisterClass *RRC = 0;
1415  uint8_t Cost = 1;
1416  switch (VT.getSimpleVT().SimpleTy) {
1417  default:
1418    return TargetLowering::findRepresentativeClass(VT);
1419  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1420    RRC = Subtarget->is64Bit() ?
1421      (const TargetRegisterClass*)&X86::GR64RegClass :
1422      (const TargetRegisterClass*)&X86::GR32RegClass;
1423    break;
1424  case MVT::x86mmx:
1425    RRC = &X86::VR64RegClass;
1426    break;
1427  case MVT::f32: case MVT::f64:
1428  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1429  case MVT::v4f32: case MVT::v2f64:
1430  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1431  case MVT::v4f64:
1432    RRC = &X86::VR128RegClass;
1433    break;
1434  }
1435  return std::make_pair(RRC, Cost);
1436}
1437
1438bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1439                                               unsigned &Offset) const {
1440  if (!Subtarget->isTargetLinux())
1441    return false;
1442
1443  if (Subtarget->is64Bit()) {
1444    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1445    Offset = 0x28;
1446    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1447      AddressSpace = 256;
1448    else
1449      AddressSpace = 257;
1450  } else {
1451    // %gs:0x14 on i386
1452    Offset = 0x14;
1453    AddressSpace = 256;
1454  }
1455  return true;
1456}
1457
1458
1459//===----------------------------------------------------------------------===//
1460//               Return Value Calling Convention Implementation
1461//===----------------------------------------------------------------------===//
1462
1463#include "X86GenCallingConv.inc"
1464
1465bool
1466X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1467                                  MachineFunction &MF, bool isVarArg,
1468                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1469                        LLVMContext &Context) const {
1470  SmallVector<CCValAssign, 16> RVLocs;
1471  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1472                 RVLocs, Context);
1473  return CCInfo.CheckReturn(Outs, RetCC_X86);
1474}
1475
1476SDValue
1477X86TargetLowering::LowerReturn(SDValue Chain,
1478                               CallingConv::ID CallConv, bool isVarArg,
1479                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1480                               const SmallVectorImpl<SDValue> &OutVals,
1481                               DebugLoc dl, SelectionDAG &DAG) const {
1482  MachineFunction &MF = DAG.getMachineFunction();
1483  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1484
1485  SmallVector<CCValAssign, 16> RVLocs;
1486  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487                 RVLocs, *DAG.getContext());
1488  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1489
1490  // Add the regs to the liveout set for the function.
1491  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1492  for (unsigned i = 0; i != RVLocs.size(); ++i)
1493    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1494      MRI.addLiveOut(RVLocs[i].getLocReg());
1495
1496  SDValue Flag;
1497
1498  SmallVector<SDValue, 6> RetOps;
1499  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1500  // Operand #1 = Bytes To Pop
1501  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1502                   MVT::i16));
1503
1504  // Copy the result values into the output registers.
1505  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506    CCValAssign &VA = RVLocs[i];
1507    assert(VA.isRegLoc() && "Can only return in registers!");
1508    SDValue ValToCopy = OutVals[i];
1509    EVT ValVT = ValToCopy.getValueType();
1510
1511    // Promote values to the appropriate types
1512    if (VA.getLocInfo() == CCValAssign::SExt)
1513      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514    else if (VA.getLocInfo() == CCValAssign::ZExt)
1515      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1516    else if (VA.getLocInfo() == CCValAssign::AExt)
1517      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1518    else if (VA.getLocInfo() == CCValAssign::BCvt)
1519      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1520
1521    // If this is x86-64, and we disabled SSE, we can't return FP values,
1522    // or SSE or MMX vectors.
1523    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1524         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1525          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1526      report_fatal_error("SSE register return with SSE disabled");
1527    }
1528    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1529    // llvm-gcc has never done it right and no one has noticed, so this
1530    // should be OK for now.
1531    if (ValVT == MVT::f64 &&
1532        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1533      report_fatal_error("SSE2 register return with SSE2 disabled");
1534
1535    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1536    // the RET instruction and handled by the FP Stackifier.
1537    if (VA.getLocReg() == X86::ST0 ||
1538        VA.getLocReg() == X86::ST1) {
1539      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1540      // change the value to the FP stack register class.
1541      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1542        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1543      RetOps.push_back(ValToCopy);
1544      // Don't emit a copytoreg.
1545      continue;
1546    }
1547
1548    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1549    // which is returned in RAX / RDX.
1550    if (Subtarget->is64Bit()) {
1551      if (ValVT == MVT::x86mmx) {
1552        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1553          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1554          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1555                                  ValToCopy);
1556          // If we don't have SSE2 available, convert to v4f32 so the generated
1557          // register is legal.
1558          if (!Subtarget->hasSSE2())
1559            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1560        }
1561      }
1562    }
1563
1564    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1565    Flag = Chain.getValue(1);
1566  }
1567
1568  // The x86-64 ABI for returning structs by value requires that we copy
1569  // the sret argument into %rax for the return. We saved the argument into
1570  // a virtual register in the entry block, so now we copy the value out
1571  // and into %rax.
1572  if (Subtarget->is64Bit() &&
1573      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1574    MachineFunction &MF = DAG.getMachineFunction();
1575    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1576    unsigned Reg = FuncInfo->getSRetReturnReg();
1577    assert(Reg &&
1578           "SRetReturnReg should have been set in LowerFormalArguments().");
1579    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1580
1581    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1582    Flag = Chain.getValue(1);
1583
1584    // RAX now acts like a return value.
1585    MRI.addLiveOut(X86::RAX);
1586  }
1587
1588  RetOps[0] = Chain;  // Update chain.
1589
1590  // Add the flag if we have it.
1591  if (Flag.getNode())
1592    RetOps.push_back(Flag);
1593
1594  return DAG.getNode(X86ISD::RET_FLAG, dl,
1595                     MVT::Other, &RetOps[0], RetOps.size());
1596}
1597
1598bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1599  if (N->getNumValues() != 1)
1600    return false;
1601  if (!N->hasNUsesOfValue(1, 0))
1602    return false;
1603
1604  SDValue TCChain = Chain;
1605  SDNode *Copy = *N->use_begin();
1606  if (Copy->getOpcode() == ISD::CopyToReg) {
1607    // If the copy has a glue operand, we conservatively assume it isn't safe to
1608    // perform a tail call.
1609    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1610      return false;
1611    TCChain = Copy->getOperand(0);
1612  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1613    return false;
1614
1615  bool HasRet = false;
1616  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1617       UI != UE; ++UI) {
1618    if (UI->getOpcode() != X86ISD::RET_FLAG)
1619      return false;
1620    HasRet = true;
1621  }
1622
1623  if (!HasRet)
1624    return false;
1625
1626  Chain = TCChain;
1627  return true;
1628}
1629
1630EVT
1631X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1632                                            ISD::NodeType ExtendKind) const {
1633  MVT ReturnMVT;
1634  // TODO: Is this also valid on 32-bit?
1635  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1636    ReturnMVT = MVT::i8;
1637  else
1638    ReturnMVT = MVT::i32;
1639
1640  EVT MinVT = getRegisterType(Context, ReturnMVT);
1641  return VT.bitsLT(MinVT) ? MinVT : VT;
1642}
1643
1644/// LowerCallResult - Lower the result values of a call into the
1645/// appropriate copies out of appropriate physical registers.
1646///
1647SDValue
1648X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1649                                   CallingConv::ID CallConv, bool isVarArg,
1650                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1651                                   DebugLoc dl, SelectionDAG &DAG,
1652                                   SmallVectorImpl<SDValue> &InVals) const {
1653
1654  // Assign locations to each value returned by this call.
1655  SmallVector<CCValAssign, 16> RVLocs;
1656  bool Is64Bit = Subtarget->is64Bit();
1657  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1658                 getTargetMachine(), RVLocs, *DAG.getContext());
1659  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1660
1661  // Copy all of the result registers out of their specified physreg.
1662  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1663    CCValAssign &VA = RVLocs[i];
1664    EVT CopyVT = VA.getValVT();
1665
1666    // If this is x86-64, and we disabled SSE, we can't return FP values
1667    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1668        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1669      report_fatal_error("SSE register return with SSE disabled");
1670    }
1671
1672    SDValue Val;
1673
1674    // If this is a call to a function that returns an fp value on the floating
1675    // point stack, we must guarantee the value is popped from the stack, so
1676    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1677    // if the return value is not used. We use the FpPOP_RETVAL instruction
1678    // instead.
1679    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1680      // If we prefer to use the value in xmm registers, copy it out as f80 and
1681      // use a truncate to move it from fp stack reg to xmm reg.
1682      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1683      SDValue Ops[] = { Chain, InFlag };
1684      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1685                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1686      Val = Chain.getValue(0);
1687
1688      // Round the f80 to the right size, which also moves it to the appropriate
1689      // xmm register.
1690      if (CopyVT != VA.getValVT())
1691        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1692                          // This truncation won't change the value.
1693                          DAG.getIntPtrConstant(1));
1694    } else {
1695      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1696                                 CopyVT, InFlag).getValue(1);
1697      Val = Chain.getValue(0);
1698    }
1699    InFlag = Chain.getValue(2);
1700    InVals.push_back(Val);
1701  }
1702
1703  return Chain;
1704}
1705
1706
1707//===----------------------------------------------------------------------===//
1708//                C & StdCall & Fast Calling Convention implementation
1709//===----------------------------------------------------------------------===//
1710//  StdCall calling convention seems to be standard for many Windows' API
1711//  routines and around. It differs from C calling convention just a little:
1712//  callee should clean up the stack, not caller. Symbols should be also
1713//  decorated in some fancy way :) It doesn't support any vector arguments.
1714//  For info on fast calling convention see Fast Calling Convention (tail call)
1715//  implementation LowerX86_32FastCCCallTo.
1716
1717/// CallIsStructReturn - Determines whether a call uses struct return
1718/// semantics.
1719enum StructReturnType {
1720  NotStructReturn,
1721  RegStructReturn,
1722  StackStructReturn
1723};
1724static StructReturnType
1725callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1726  if (Outs.empty())
1727    return NotStructReturn;
1728
1729  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1730  if (!Flags.isSRet())
1731    return NotStructReturn;
1732  if (Flags.isInReg())
1733    return RegStructReturn;
1734  return StackStructReturn;
1735}
1736
1737/// ArgsAreStructReturn - Determines whether a function uses struct
1738/// return semantics.
1739static StructReturnType
1740argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1741  if (Ins.empty())
1742    return NotStructReturn;
1743
1744  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1745  if (!Flags.isSRet())
1746    return NotStructReturn;
1747  if (Flags.isInReg())
1748    return RegStructReturn;
1749  return StackStructReturn;
1750}
1751
1752/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1753/// by "Src" to address "Dst" with size and alignment information specified by
1754/// the specific parameter attribute. The copy will be passed as a byval
1755/// function parameter.
1756static SDValue
1757CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1758                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1759                          DebugLoc dl) {
1760  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1761
1762  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1763                       /*isVolatile*/false, /*AlwaysInline=*/true,
1764                       MachinePointerInfo(), MachinePointerInfo());
1765}
1766
1767/// IsTailCallConvention - Return true if the calling convention is one that
1768/// supports tail call optimization.
1769static bool IsTailCallConvention(CallingConv::ID CC) {
1770  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1771}
1772
1773bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1774  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1775    return false;
1776
1777  CallSite CS(CI);
1778  CallingConv::ID CalleeCC = CS.getCallingConv();
1779  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1780    return false;
1781
1782  return true;
1783}
1784
1785/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1786/// a tailcall target by changing its ABI.
1787static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1788                                   bool GuaranteedTailCallOpt) {
1789  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1790}
1791
1792SDValue
1793X86TargetLowering::LowerMemArgument(SDValue Chain,
1794                                    CallingConv::ID CallConv,
1795                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1796                                    DebugLoc dl, SelectionDAG &DAG,
1797                                    const CCValAssign &VA,
1798                                    MachineFrameInfo *MFI,
1799                                    unsigned i) const {
1800  // Create the nodes corresponding to a load from this parameter slot.
1801  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1802  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1803                              getTargetMachine().Options.GuaranteedTailCallOpt);
1804  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1805  EVT ValVT;
1806
1807  // If value is passed by pointer we have address passed instead of the value
1808  // itself.
1809  if (VA.getLocInfo() == CCValAssign::Indirect)
1810    ValVT = VA.getLocVT();
1811  else
1812    ValVT = VA.getValVT();
1813
1814  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1815  // changed with more analysis.
1816  // In case of tail call optimization mark all arguments mutable. Since they
1817  // could be overwritten by lowering of arguments in case of a tail call.
1818  if (Flags.isByVal()) {
1819    unsigned Bytes = Flags.getByValSize();
1820    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1821    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1822    return DAG.getFrameIndex(FI, getPointerTy());
1823  } else {
1824    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1825                                    VA.getLocMemOffset(), isImmutable);
1826    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1827    return DAG.getLoad(ValVT, dl, Chain, FIN,
1828                       MachinePointerInfo::getFixedStack(FI),
1829                       false, false, false, 0);
1830  }
1831}
1832
1833SDValue
1834X86TargetLowering::LowerFormalArguments(SDValue Chain,
1835                                        CallingConv::ID CallConv,
1836                                        bool isVarArg,
1837                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1838                                        DebugLoc dl,
1839                                        SelectionDAG &DAG,
1840                                        SmallVectorImpl<SDValue> &InVals)
1841                                          const {
1842  MachineFunction &MF = DAG.getMachineFunction();
1843  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1844
1845  const Function* Fn = MF.getFunction();
1846  if (Fn->hasExternalLinkage() &&
1847      Subtarget->isTargetCygMing() &&
1848      Fn->getName() == "main")
1849    FuncInfo->setForceFramePointer(true);
1850
1851  MachineFrameInfo *MFI = MF.getFrameInfo();
1852  bool Is64Bit = Subtarget->is64Bit();
1853  bool IsWindows = Subtarget->isTargetWindows();
1854  bool IsWin64 = Subtarget->isTargetWin64();
1855
1856  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1857         "Var args not supported with calling convention fastcc or ghc");
1858
1859  // Assign locations to all of the incoming arguments.
1860  SmallVector<CCValAssign, 16> ArgLocs;
1861  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1862                 ArgLocs, *DAG.getContext());
1863
1864  // Allocate shadow area for Win64
1865  if (IsWin64) {
1866    CCInfo.AllocateStack(32, 8);
1867  }
1868
1869  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1870
1871  unsigned LastVal = ~0U;
1872  SDValue ArgValue;
1873  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1874    CCValAssign &VA = ArgLocs[i];
1875    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1876    // places.
1877    assert(VA.getValNo() != LastVal &&
1878           "Don't support value assigned to multiple locs yet");
1879    (void)LastVal;
1880    LastVal = VA.getValNo();
1881
1882    if (VA.isRegLoc()) {
1883      EVT RegVT = VA.getLocVT();
1884      const TargetRegisterClass *RC;
1885      if (RegVT == MVT::i32)
1886        RC = &X86::GR32RegClass;
1887      else if (Is64Bit && RegVT == MVT::i64)
1888        RC = &X86::GR64RegClass;
1889      else if (RegVT == MVT::f32)
1890        RC = &X86::FR32RegClass;
1891      else if (RegVT == MVT::f64)
1892        RC = &X86::FR64RegClass;
1893      else if (RegVT.is256BitVector())
1894        RC = &X86::VR256RegClass;
1895      else if (RegVT.is128BitVector())
1896        RC = &X86::VR128RegClass;
1897      else if (RegVT == MVT::x86mmx)
1898        RC = &X86::VR64RegClass;
1899      else
1900        llvm_unreachable("Unknown argument type!");
1901
1902      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1903      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1904
1905      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1906      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1907      // right size.
1908      if (VA.getLocInfo() == CCValAssign::SExt)
1909        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1910                               DAG.getValueType(VA.getValVT()));
1911      else if (VA.getLocInfo() == CCValAssign::ZExt)
1912        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1913                               DAG.getValueType(VA.getValVT()));
1914      else if (VA.getLocInfo() == CCValAssign::BCvt)
1915        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1916
1917      if (VA.isExtInLoc()) {
1918        // Handle MMX values passed in XMM regs.
1919        if (RegVT.isVector()) {
1920          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1921                                 ArgValue);
1922        } else
1923          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1924      }
1925    } else {
1926      assert(VA.isMemLoc());
1927      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1928    }
1929
1930    // If value is passed via pointer - do a load.
1931    if (VA.getLocInfo() == CCValAssign::Indirect)
1932      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1933                             MachinePointerInfo(), false, false, false, 0);
1934
1935    InVals.push_back(ArgValue);
1936  }
1937
1938  // The x86-64 ABI for returning structs by value requires that we copy
1939  // the sret argument into %rax for the return. Save the argument into
1940  // a virtual register so that we can access it from the return points.
1941  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1942    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1943    unsigned Reg = FuncInfo->getSRetReturnReg();
1944    if (!Reg) {
1945      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1946      FuncInfo->setSRetReturnReg(Reg);
1947    }
1948    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1949    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1950  }
1951
1952  unsigned StackSize = CCInfo.getNextStackOffset();
1953  // Align stack specially for tail calls.
1954  if (FuncIsMadeTailCallSafe(CallConv,
1955                             MF.getTarget().Options.GuaranteedTailCallOpt))
1956    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1957
1958  // If the function takes variable number of arguments, make a frame index for
1959  // the start of the first vararg value... for expansion of llvm.va_start.
1960  if (isVarArg) {
1961    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1962                    CallConv != CallingConv::X86_ThisCall)) {
1963      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1964    }
1965    if (Is64Bit) {
1966      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1967
1968      // FIXME: We should really autogenerate these arrays
1969      static const uint16_t GPR64ArgRegsWin64[] = {
1970        X86::RCX, X86::RDX, X86::R8,  X86::R9
1971      };
1972      static const uint16_t GPR64ArgRegs64Bit[] = {
1973        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1974      };
1975      static const uint16_t XMMArgRegs64Bit[] = {
1976        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1977        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1978      };
1979      const uint16_t *GPR64ArgRegs;
1980      unsigned NumXMMRegs = 0;
1981
1982      if (IsWin64) {
1983        // The XMM registers which might contain var arg parameters are shadowed
1984        // in their paired GPR.  So we only need to save the GPR to their home
1985        // slots.
1986        TotalNumIntRegs = 4;
1987        GPR64ArgRegs = GPR64ArgRegsWin64;
1988      } else {
1989        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1990        GPR64ArgRegs = GPR64ArgRegs64Bit;
1991
1992        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1993                                                TotalNumXMMRegs);
1994      }
1995      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1996                                                       TotalNumIntRegs);
1997
1998      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1999      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2000             "SSE register cannot be used when SSE is disabled!");
2001      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2002               NoImplicitFloatOps) &&
2003             "SSE register cannot be used when SSE is disabled!");
2004      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2005          !Subtarget->hasSSE1())
2006        // Kernel mode asks for SSE to be disabled, so don't push them
2007        // on the stack.
2008        TotalNumXMMRegs = 0;
2009
2010      if (IsWin64) {
2011        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2012        // Get to the caller-allocated home save location.  Add 8 to account
2013        // for the return address.
2014        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2015        FuncInfo->setRegSaveFrameIndex(
2016          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2017        // Fixup to set vararg frame on shadow area (4 x i64).
2018        if (NumIntRegs < 4)
2019          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2020      } else {
2021        // For X86-64, if there are vararg parameters that are passed via
2022        // registers, then we must store them to their spots on the stack so
2023        // they may be loaded by deferencing the result of va_next.
2024        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2025        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2026        FuncInfo->setRegSaveFrameIndex(
2027          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2028                               false));
2029      }
2030
2031      // Store the integer parameter registers.
2032      SmallVector<SDValue, 8> MemOps;
2033      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2034                                        getPointerTy());
2035      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2036      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2037        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2038                                  DAG.getIntPtrConstant(Offset));
2039        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2040                                     &X86::GR64RegClass);
2041        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2042        SDValue Store =
2043          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2044                       MachinePointerInfo::getFixedStack(
2045                         FuncInfo->getRegSaveFrameIndex(), Offset),
2046                       false, false, 0);
2047        MemOps.push_back(Store);
2048        Offset += 8;
2049      }
2050
2051      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2052        // Now store the XMM (fp + vector) parameter registers.
2053        SmallVector<SDValue, 11> SaveXMMOps;
2054        SaveXMMOps.push_back(Chain);
2055
2056        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2057        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2058        SaveXMMOps.push_back(ALVal);
2059
2060        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2061                               FuncInfo->getRegSaveFrameIndex()));
2062        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2063                               FuncInfo->getVarArgsFPOffset()));
2064
2065        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2066          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2067                                       &X86::VR128RegClass);
2068          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2069          SaveXMMOps.push_back(Val);
2070        }
2071        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2072                                     MVT::Other,
2073                                     &SaveXMMOps[0], SaveXMMOps.size()));
2074      }
2075
2076      if (!MemOps.empty())
2077        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2078                            &MemOps[0], MemOps.size());
2079    }
2080  }
2081
2082  // Some CCs need callee pop.
2083  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2084                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2085    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2086  } else {
2087    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2088    // If this is an sret function, the return should pop the hidden pointer.
2089    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2090        argsAreStructReturn(Ins) == StackStructReturn)
2091      FuncInfo->setBytesToPopOnReturn(4);
2092  }
2093
2094  if (!Is64Bit) {
2095    // RegSaveFrameIndex is X86-64 only.
2096    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2097    if (CallConv == CallingConv::X86_FastCall ||
2098        CallConv == CallingConv::X86_ThisCall)
2099      // fastcc functions can't have varargs.
2100      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2101  }
2102
2103  FuncInfo->setArgumentStackSize(StackSize);
2104
2105  return Chain;
2106}
2107
2108SDValue
2109X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2110                                    SDValue StackPtr, SDValue Arg,
2111                                    DebugLoc dl, SelectionDAG &DAG,
2112                                    const CCValAssign &VA,
2113                                    ISD::ArgFlagsTy Flags) const {
2114  unsigned LocMemOffset = VA.getLocMemOffset();
2115  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2116  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2117  if (Flags.isByVal())
2118    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2119
2120  return DAG.getStore(Chain, dl, Arg, PtrOff,
2121                      MachinePointerInfo::getStack(LocMemOffset),
2122                      false, false, 0);
2123}
2124
2125/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2126/// optimization is performed and it is required.
2127SDValue
2128X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2129                                           SDValue &OutRetAddr, SDValue Chain,
2130                                           bool IsTailCall, bool Is64Bit,
2131                                           int FPDiff, DebugLoc dl) const {
2132  // Adjust the Return address stack slot.
2133  EVT VT = getPointerTy();
2134  OutRetAddr = getReturnAddressFrameIndex(DAG);
2135
2136  // Load the "old" Return address.
2137  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2138                           false, false, false, 0);
2139  return SDValue(OutRetAddr.getNode(), 1);
2140}
2141
2142/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2143/// optimization is performed and it is required (FPDiff!=0).
2144static SDValue
2145EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2146                         SDValue Chain, SDValue RetAddrFrIdx,
2147                         bool Is64Bit, int FPDiff, DebugLoc dl) {
2148  // Store the return address to the appropriate stack slot.
2149  if (!FPDiff) return Chain;
2150  // Calculate the new stack slot for the return address.
2151  int SlotSize = Is64Bit ? 8 : 4;
2152  int NewReturnAddrFI =
2153    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2154  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2155  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2156  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2157                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2158                       false, false, 0);
2159  return Chain;
2160}
2161
2162SDValue
2163X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2164                             SmallVectorImpl<SDValue> &InVals) const {
2165  SelectionDAG &DAG                     = CLI.DAG;
2166  DebugLoc &dl                          = CLI.DL;
2167  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2168  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2169  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2170  SDValue Chain                         = CLI.Chain;
2171  SDValue Callee                        = CLI.Callee;
2172  CallingConv::ID CallConv              = CLI.CallConv;
2173  bool &isTailCall                      = CLI.IsTailCall;
2174  bool isVarArg                         = CLI.IsVarArg;
2175
2176  MachineFunction &MF = DAG.getMachineFunction();
2177  bool Is64Bit        = Subtarget->is64Bit();
2178  bool IsWin64        = Subtarget->isTargetWin64();
2179  bool IsWindows      = Subtarget->isTargetWindows();
2180  StructReturnType SR = callIsStructReturn(Outs);
2181  bool IsSibcall      = false;
2182
2183  if (MF.getTarget().Options.DisableTailCalls)
2184    isTailCall = false;
2185
2186  if (isTailCall) {
2187    // Check if it's really possible to do a tail call.
2188    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2189                    isVarArg, SR != NotStructReturn,
2190                    MF.getFunction()->hasStructRetAttr(),
2191                    Outs, OutVals, Ins, DAG);
2192
2193    // Sibcalls are automatically detected tailcalls which do not require
2194    // ABI changes.
2195    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2196      IsSibcall = true;
2197
2198    if (isTailCall)
2199      ++NumTailCalls;
2200  }
2201
2202  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2203         "Var args not supported with calling convention fastcc or ghc");
2204
2205  // Analyze operands of the call, assigning locations to each operand.
2206  SmallVector<CCValAssign, 16> ArgLocs;
2207  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2208                 ArgLocs, *DAG.getContext());
2209
2210  // Allocate shadow area for Win64
2211  if (IsWin64) {
2212    CCInfo.AllocateStack(32, 8);
2213  }
2214
2215  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2216
2217  // Get a count of how many bytes are to be pushed on the stack.
2218  unsigned NumBytes = CCInfo.getNextStackOffset();
2219  if (IsSibcall)
2220    // This is a sibcall. The memory operands are available in caller's
2221    // own caller's stack.
2222    NumBytes = 0;
2223  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2224           IsTailCallConvention(CallConv))
2225    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2226
2227  int FPDiff = 0;
2228  if (isTailCall && !IsSibcall) {
2229    // Lower arguments at fp - stackoffset + fpdiff.
2230    unsigned NumBytesCallerPushed =
2231      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2232    FPDiff = NumBytesCallerPushed - NumBytes;
2233
2234    // Set the delta of movement of the returnaddr stackslot.
2235    // But only set if delta is greater than previous delta.
2236    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2237      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2238  }
2239
2240  if (!IsSibcall)
2241    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2242
2243  SDValue RetAddrFrIdx;
2244  // Load return address for tail calls.
2245  if (isTailCall && FPDiff)
2246    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2247                                    Is64Bit, FPDiff, dl);
2248
2249  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2250  SmallVector<SDValue, 8> MemOpChains;
2251  SDValue StackPtr;
2252
2253  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2254  // of tail call optimization arguments are handle later.
2255  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2256    CCValAssign &VA = ArgLocs[i];
2257    EVT RegVT = VA.getLocVT();
2258    SDValue Arg = OutVals[i];
2259    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2260    bool isByVal = Flags.isByVal();
2261
2262    // Promote the value if needed.
2263    switch (VA.getLocInfo()) {
2264    default: llvm_unreachable("Unknown loc info!");
2265    case CCValAssign::Full: break;
2266    case CCValAssign::SExt:
2267      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2268      break;
2269    case CCValAssign::ZExt:
2270      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2271      break;
2272    case CCValAssign::AExt:
2273      if (RegVT.is128BitVector()) {
2274        // Special case: passing MMX values in XMM registers.
2275        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2276        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2277        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2278      } else
2279        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2280      break;
2281    case CCValAssign::BCvt:
2282      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2283      break;
2284    case CCValAssign::Indirect: {
2285      // Store the argument.
2286      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2287      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2288      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2289                           MachinePointerInfo::getFixedStack(FI),
2290                           false, false, 0);
2291      Arg = SpillSlot;
2292      break;
2293    }
2294    }
2295
2296    if (VA.isRegLoc()) {
2297      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2298      if (isVarArg && IsWin64) {
2299        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2300        // shadow reg if callee is a varargs function.
2301        unsigned ShadowReg = 0;
2302        switch (VA.getLocReg()) {
2303        case X86::XMM0: ShadowReg = X86::RCX; break;
2304        case X86::XMM1: ShadowReg = X86::RDX; break;
2305        case X86::XMM2: ShadowReg = X86::R8; break;
2306        case X86::XMM3: ShadowReg = X86::R9; break;
2307        }
2308        if (ShadowReg)
2309          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2310      }
2311    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2312      assert(VA.isMemLoc());
2313      if (StackPtr.getNode() == 0)
2314        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2315      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2316                                             dl, DAG, VA, Flags));
2317    }
2318  }
2319
2320  if (!MemOpChains.empty())
2321    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2322                        &MemOpChains[0], MemOpChains.size());
2323
2324  if (Subtarget->isPICStyleGOT()) {
2325    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2326    // GOT pointer.
2327    if (!isTailCall) {
2328      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2329               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2330    } else {
2331      // If we are tail calling and generating PIC/GOT style code load the
2332      // address of the callee into ECX. The value in ecx is used as target of
2333      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2334      // for tail calls on PIC/GOT architectures. Normally we would just put the
2335      // address of GOT into ebx and then call target@PLT. But for tail calls
2336      // ebx would be restored (since ebx is callee saved) before jumping to the
2337      // target@PLT.
2338
2339      // Note: The actual moving to ECX is done further down.
2340      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2341      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2342          !G->getGlobal()->hasProtectedVisibility())
2343        Callee = LowerGlobalAddress(Callee, DAG);
2344      else if (isa<ExternalSymbolSDNode>(Callee))
2345        Callee = LowerExternalSymbol(Callee, DAG);
2346    }
2347  }
2348
2349  if (Is64Bit && isVarArg && !IsWin64) {
2350    // From AMD64 ABI document:
2351    // For calls that may call functions that use varargs or stdargs
2352    // (prototype-less calls or calls to functions containing ellipsis (...) in
2353    // the declaration) %al is used as hidden argument to specify the number
2354    // of SSE registers used. The contents of %al do not need to match exactly
2355    // the number of registers, but must be an ubound on the number of SSE
2356    // registers used and is in the range 0 - 8 inclusive.
2357
2358    // Count the number of XMM registers allocated.
2359    static const uint16_t XMMArgRegs[] = {
2360      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2361      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2362    };
2363    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2364    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2365           && "SSE registers cannot be used when SSE is disabled");
2366
2367    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2368                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2369  }
2370
2371  // For tail calls lower the arguments to the 'real' stack slot.
2372  if (isTailCall) {
2373    // Force all the incoming stack arguments to be loaded from the stack
2374    // before any new outgoing arguments are stored to the stack, because the
2375    // outgoing stack slots may alias the incoming argument stack slots, and
2376    // the alias isn't otherwise explicit. This is slightly more conservative
2377    // than necessary, because it means that each store effectively depends
2378    // on every argument instead of just those arguments it would clobber.
2379    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2380
2381    SmallVector<SDValue, 8> MemOpChains2;
2382    SDValue FIN;
2383    int FI = 0;
2384    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2385      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2386        CCValAssign &VA = ArgLocs[i];
2387        if (VA.isRegLoc())
2388          continue;
2389        assert(VA.isMemLoc());
2390        SDValue Arg = OutVals[i];
2391        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2392        // Create frame index.
2393        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2394        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2395        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2396        FIN = DAG.getFrameIndex(FI, getPointerTy());
2397
2398        if (Flags.isByVal()) {
2399          // Copy relative to framepointer.
2400          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2401          if (StackPtr.getNode() == 0)
2402            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2403                                          getPointerTy());
2404          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2405
2406          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2407                                                           ArgChain,
2408                                                           Flags, DAG, dl));
2409        } else {
2410          // Store relative to framepointer.
2411          MemOpChains2.push_back(
2412            DAG.getStore(ArgChain, dl, Arg, FIN,
2413                         MachinePointerInfo::getFixedStack(FI),
2414                         false, false, 0));
2415        }
2416      }
2417    }
2418
2419    if (!MemOpChains2.empty())
2420      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2421                          &MemOpChains2[0], MemOpChains2.size());
2422
2423    // Store the return address to the appropriate stack slot.
2424    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2425                                     FPDiff, dl);
2426  }
2427
2428  // Build a sequence of copy-to-reg nodes chained together with token chain
2429  // and flag operands which copy the outgoing args into registers.
2430  SDValue InFlag;
2431  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2432    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2433                             RegsToPass[i].second, InFlag);
2434    InFlag = Chain.getValue(1);
2435  }
2436
2437  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2438    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2439    // In the 64-bit large code model, we have to make all calls
2440    // through a register, since the call instruction's 32-bit
2441    // pc-relative offset may not be large enough to hold the whole
2442    // address.
2443  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2444    // If the callee is a GlobalAddress node (quite common, every direct call
2445    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2446    // it.
2447
2448    // We should use extra load for direct calls to dllimported functions in
2449    // non-JIT mode.
2450    const GlobalValue *GV = G->getGlobal();
2451    if (!GV->hasDLLImportLinkage()) {
2452      unsigned char OpFlags = 0;
2453      bool ExtraLoad = false;
2454      unsigned WrapperKind = ISD::DELETED_NODE;
2455
2456      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2457      // external symbols most go through the PLT in PIC mode.  If the symbol
2458      // has hidden or protected visibility, or if it is static or local, then
2459      // we don't need to use the PLT - we can directly call it.
2460      if (Subtarget->isTargetELF() &&
2461          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2462          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2463        OpFlags = X86II::MO_PLT;
2464      } else if (Subtarget->isPICStyleStubAny() &&
2465                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2466                 (!Subtarget->getTargetTriple().isMacOSX() ||
2467                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2468        // PC-relative references to external symbols should go through $stub,
2469        // unless we're building with the leopard linker or later, which
2470        // automatically synthesizes these stubs.
2471        OpFlags = X86II::MO_DARWIN_STUB;
2472      } else if (Subtarget->isPICStyleRIPRel() &&
2473                 isa<Function>(GV) &&
2474                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2475        // If the function is marked as non-lazy, generate an indirect call
2476        // which loads from the GOT directly. This avoids runtime overhead
2477        // at the cost of eager binding (and one extra byte of encoding).
2478        OpFlags = X86II::MO_GOTPCREL;
2479        WrapperKind = X86ISD::WrapperRIP;
2480        ExtraLoad = true;
2481      }
2482
2483      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2484                                          G->getOffset(), OpFlags);
2485
2486      // Add a wrapper if needed.
2487      if (WrapperKind != ISD::DELETED_NODE)
2488        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2489      // Add extra indirection if needed.
2490      if (ExtraLoad)
2491        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2492                             MachinePointerInfo::getGOT(),
2493                             false, false, false, 0);
2494    }
2495  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2496    unsigned char OpFlags = 0;
2497
2498    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2499    // external symbols should go through the PLT.
2500    if (Subtarget->isTargetELF() &&
2501        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2502      OpFlags = X86II::MO_PLT;
2503    } else if (Subtarget->isPICStyleStubAny() &&
2504               (!Subtarget->getTargetTriple().isMacOSX() ||
2505                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2506      // PC-relative references to external symbols should go through $stub,
2507      // unless we're building with the leopard linker or later, which
2508      // automatically synthesizes these stubs.
2509      OpFlags = X86II::MO_DARWIN_STUB;
2510    }
2511
2512    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2513                                         OpFlags);
2514  }
2515
2516  // Returns a chain & a flag for retval copy to use.
2517  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2518  SmallVector<SDValue, 8> Ops;
2519
2520  if (!IsSibcall && isTailCall) {
2521    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2522                           DAG.getIntPtrConstant(0, true), InFlag);
2523    InFlag = Chain.getValue(1);
2524  }
2525
2526  Ops.push_back(Chain);
2527  Ops.push_back(Callee);
2528
2529  if (isTailCall)
2530    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2531
2532  // Add argument registers to the end of the list so that they are known live
2533  // into the call.
2534  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2535    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2536                                  RegsToPass[i].second.getValueType()));
2537
2538  // Add a register mask operand representing the call-preserved registers.
2539  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2540  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2541  assert(Mask && "Missing call preserved mask for calling convention");
2542  Ops.push_back(DAG.getRegisterMask(Mask));
2543
2544  if (InFlag.getNode())
2545    Ops.push_back(InFlag);
2546
2547  if (isTailCall) {
2548    // We used to do:
2549    //// If this is the first return lowered for this function, add the regs
2550    //// to the liveout set for the function.
2551    // This isn't right, although it's probably harmless on x86; liveouts
2552    // should be computed from returns not tail calls.  Consider a void
2553    // function making a tail call to a function returning int.
2554    return DAG.getNode(X86ISD::TC_RETURN, dl,
2555                       NodeTys, &Ops[0], Ops.size());
2556  }
2557
2558  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2559  InFlag = Chain.getValue(1);
2560
2561  // Create the CALLSEQ_END node.
2562  unsigned NumBytesForCalleeToPush;
2563  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2564                       getTargetMachine().Options.GuaranteedTailCallOpt))
2565    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2566  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2567           SR == StackStructReturn)
2568    // If this is a call to a struct-return function, the callee
2569    // pops the hidden struct pointer, so we have to push it back.
2570    // This is common for Darwin/X86, Linux & Mingw32 targets.
2571    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2572    NumBytesForCalleeToPush = 4;
2573  else
2574    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2575
2576  // Returns a flag for retval copy to use.
2577  if (!IsSibcall) {
2578    Chain = DAG.getCALLSEQ_END(Chain,
2579                               DAG.getIntPtrConstant(NumBytes, true),
2580                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2581                                                     true),
2582                               InFlag);
2583    InFlag = Chain.getValue(1);
2584  }
2585
2586  // Handle result values, copying them out of physregs into vregs that we
2587  // return.
2588  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2589                         Ins, dl, DAG, InVals);
2590}
2591
2592
2593//===----------------------------------------------------------------------===//
2594//                Fast Calling Convention (tail call) implementation
2595//===----------------------------------------------------------------------===//
2596
2597//  Like std call, callee cleans arguments, convention except that ECX is
2598//  reserved for storing the tail called function address. Only 2 registers are
2599//  free for argument passing (inreg). Tail call optimization is performed
2600//  provided:
2601//                * tailcallopt is enabled
2602//                * caller/callee are fastcc
2603//  On X86_64 architecture with GOT-style position independent code only local
2604//  (within module) calls are supported at the moment.
2605//  To keep the stack aligned according to platform abi the function
2606//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2607//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2608//  If a tail called function callee has more arguments than the caller the
2609//  caller needs to make sure that there is room to move the RETADDR to. This is
2610//  achieved by reserving an area the size of the argument delta right after the
2611//  original REtADDR, but before the saved framepointer or the spilled registers
2612//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2613//  stack layout:
2614//    arg1
2615//    arg2
2616//    RETADDR
2617//    [ new RETADDR
2618//      move area ]
2619//    (possible EBP)
2620//    ESI
2621//    EDI
2622//    local1 ..
2623
2624/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2625/// for a 16 byte align requirement.
2626unsigned
2627X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2628                                               SelectionDAG& DAG) const {
2629  MachineFunction &MF = DAG.getMachineFunction();
2630  const TargetMachine &TM = MF.getTarget();
2631  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2632  unsigned StackAlignment = TFI.getStackAlignment();
2633  uint64_t AlignMask = StackAlignment - 1;
2634  int64_t Offset = StackSize;
2635  uint64_t SlotSize = TD->getPointerSize();
2636  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2637    // Number smaller than 12 so just add the difference.
2638    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2639  } else {
2640    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2641    Offset = ((~AlignMask) & Offset) + StackAlignment +
2642      (StackAlignment-SlotSize);
2643  }
2644  return Offset;
2645}
2646
2647/// MatchingStackOffset - Return true if the given stack call argument is
2648/// already available in the same position (relatively) of the caller's
2649/// incoming argument stack.
2650static
2651bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2652                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2653                         const X86InstrInfo *TII) {
2654  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2655  int FI = INT_MAX;
2656  if (Arg.getOpcode() == ISD::CopyFromReg) {
2657    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2658    if (!TargetRegisterInfo::isVirtualRegister(VR))
2659      return false;
2660    MachineInstr *Def = MRI->getVRegDef(VR);
2661    if (!Def)
2662      return false;
2663    if (!Flags.isByVal()) {
2664      if (!TII->isLoadFromStackSlot(Def, FI))
2665        return false;
2666    } else {
2667      unsigned Opcode = Def->getOpcode();
2668      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2669          Def->getOperand(1).isFI()) {
2670        FI = Def->getOperand(1).getIndex();
2671        Bytes = Flags.getByValSize();
2672      } else
2673        return false;
2674    }
2675  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2676    if (Flags.isByVal())
2677      // ByVal argument is passed in as a pointer but it's now being
2678      // dereferenced. e.g.
2679      // define @foo(%struct.X* %A) {
2680      //   tail call @bar(%struct.X* byval %A)
2681      // }
2682      return false;
2683    SDValue Ptr = Ld->getBasePtr();
2684    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2685    if (!FINode)
2686      return false;
2687    FI = FINode->getIndex();
2688  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2689    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2690    FI = FINode->getIndex();
2691    Bytes = Flags.getByValSize();
2692  } else
2693    return false;
2694
2695  assert(FI != INT_MAX);
2696  if (!MFI->isFixedObjectIndex(FI))
2697    return false;
2698  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2699}
2700
2701/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2702/// for tail call optimization. Targets which want to do tail call
2703/// optimization should implement this function.
2704bool
2705X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2706                                                     CallingConv::ID CalleeCC,
2707                                                     bool isVarArg,
2708                                                     bool isCalleeStructRet,
2709                                                     bool isCallerStructRet,
2710                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2711                                    const SmallVectorImpl<SDValue> &OutVals,
2712                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2713                                                     SelectionDAG& DAG) const {
2714  if (!IsTailCallConvention(CalleeCC) &&
2715      CalleeCC != CallingConv::C)
2716    return false;
2717
2718  // If -tailcallopt is specified, make fastcc functions tail-callable.
2719  const MachineFunction &MF = DAG.getMachineFunction();
2720  const Function *CallerF = DAG.getMachineFunction().getFunction();
2721  CallingConv::ID CallerCC = CallerF->getCallingConv();
2722  bool CCMatch = CallerCC == CalleeCC;
2723
2724  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2725    if (IsTailCallConvention(CalleeCC) && CCMatch)
2726      return true;
2727    return false;
2728  }
2729
2730  // Look for obvious safe cases to perform tail call optimization that do not
2731  // require ABI changes. This is what gcc calls sibcall.
2732
2733  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2734  // emit a special epilogue.
2735  if (RegInfo->needsStackRealignment(MF))
2736    return false;
2737
2738  // Also avoid sibcall optimization if either caller or callee uses struct
2739  // return semantics.
2740  if (isCalleeStructRet || isCallerStructRet)
2741    return false;
2742
2743  // An stdcall caller is expected to clean up its arguments; the callee
2744  // isn't going to do that.
2745  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2746    return false;
2747
2748  // Do not sibcall optimize vararg calls unless all arguments are passed via
2749  // registers.
2750  if (isVarArg && !Outs.empty()) {
2751
2752    // Optimizing for varargs on Win64 is unlikely to be safe without
2753    // additional testing.
2754    if (Subtarget->isTargetWin64())
2755      return false;
2756
2757    SmallVector<CCValAssign, 16> ArgLocs;
2758    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2759                   getTargetMachine(), ArgLocs, *DAG.getContext());
2760
2761    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2762    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2763      if (!ArgLocs[i].isRegLoc())
2764        return false;
2765  }
2766
2767  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2768  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2769  // this into a sibcall.
2770  bool Unused = false;
2771  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2772    if (!Ins[i].Used) {
2773      Unused = true;
2774      break;
2775    }
2776  }
2777  if (Unused) {
2778    SmallVector<CCValAssign, 16> RVLocs;
2779    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2780                   getTargetMachine(), RVLocs, *DAG.getContext());
2781    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2782    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2783      CCValAssign &VA = RVLocs[i];
2784      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2785        return false;
2786    }
2787  }
2788
2789  // If the calling conventions do not match, then we'd better make sure the
2790  // results are returned in the same way as what the caller expects.
2791  if (!CCMatch) {
2792    SmallVector<CCValAssign, 16> RVLocs1;
2793    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2794                    getTargetMachine(), RVLocs1, *DAG.getContext());
2795    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2796
2797    SmallVector<CCValAssign, 16> RVLocs2;
2798    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2799                    getTargetMachine(), RVLocs2, *DAG.getContext());
2800    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2801
2802    if (RVLocs1.size() != RVLocs2.size())
2803      return false;
2804    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2805      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2806        return false;
2807      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2808        return false;
2809      if (RVLocs1[i].isRegLoc()) {
2810        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2811          return false;
2812      } else {
2813        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2814          return false;
2815      }
2816    }
2817  }
2818
2819  // If the callee takes no arguments then go on to check the results of the
2820  // call.
2821  if (!Outs.empty()) {
2822    // Check if stack adjustment is needed. For now, do not do this if any
2823    // argument is passed on the stack.
2824    SmallVector<CCValAssign, 16> ArgLocs;
2825    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2826                   getTargetMachine(), ArgLocs, *DAG.getContext());
2827
2828    // Allocate shadow area for Win64
2829    if (Subtarget->isTargetWin64()) {
2830      CCInfo.AllocateStack(32, 8);
2831    }
2832
2833    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2834    if (CCInfo.getNextStackOffset()) {
2835      MachineFunction &MF = DAG.getMachineFunction();
2836      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2837        return false;
2838
2839      // Check if the arguments are already laid out in the right way as
2840      // the caller's fixed stack objects.
2841      MachineFrameInfo *MFI = MF.getFrameInfo();
2842      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2843      const X86InstrInfo *TII =
2844        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2845      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846        CCValAssign &VA = ArgLocs[i];
2847        SDValue Arg = OutVals[i];
2848        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849        if (VA.getLocInfo() == CCValAssign::Indirect)
2850          return false;
2851        if (!VA.isRegLoc()) {
2852          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2853                                   MFI, MRI, TII))
2854            return false;
2855        }
2856      }
2857    }
2858
2859    // If the tailcall address may be in a register, then make sure it's
2860    // possible to register allocate for it. In 32-bit, the call address can
2861    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2862    // callee-saved registers are restored. These happen to be the same
2863    // registers used to pass 'inreg' arguments so watch out for those.
2864    if (!Subtarget->is64Bit() &&
2865        !isa<GlobalAddressSDNode>(Callee) &&
2866        !isa<ExternalSymbolSDNode>(Callee)) {
2867      unsigned NumInRegs = 0;
2868      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2869        CCValAssign &VA = ArgLocs[i];
2870        if (!VA.isRegLoc())
2871          continue;
2872        unsigned Reg = VA.getLocReg();
2873        switch (Reg) {
2874        default: break;
2875        case X86::EAX: case X86::EDX: case X86::ECX:
2876          if (++NumInRegs == 3)
2877            return false;
2878          break;
2879        }
2880      }
2881    }
2882  }
2883
2884  return true;
2885}
2886
2887FastISel *
2888X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2889                                  const TargetLibraryInfo *libInfo) const {
2890  return X86::createFastISel(funcInfo, libInfo);
2891}
2892
2893
2894//===----------------------------------------------------------------------===//
2895//                           Other Lowering Hooks
2896//===----------------------------------------------------------------------===//
2897
2898static bool MayFoldLoad(SDValue Op) {
2899  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2900}
2901
2902static bool MayFoldIntoStore(SDValue Op) {
2903  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2904}
2905
2906static bool isTargetShuffle(unsigned Opcode) {
2907  switch(Opcode) {
2908  default: return false;
2909  case X86ISD::PSHUFD:
2910  case X86ISD::PSHUFHW:
2911  case X86ISD::PSHUFLW:
2912  case X86ISD::SHUFP:
2913  case X86ISD::PALIGN:
2914  case X86ISD::MOVLHPS:
2915  case X86ISD::MOVLHPD:
2916  case X86ISD::MOVHLPS:
2917  case X86ISD::MOVLPS:
2918  case X86ISD::MOVLPD:
2919  case X86ISD::MOVSHDUP:
2920  case X86ISD::MOVSLDUP:
2921  case X86ISD::MOVDDUP:
2922  case X86ISD::MOVSS:
2923  case X86ISD::MOVSD:
2924  case X86ISD::UNPCKL:
2925  case X86ISD::UNPCKH:
2926  case X86ISD::VPERMILP:
2927  case X86ISD::VPERM2X128:
2928  case X86ISD::VPERMI:
2929    return true;
2930  }
2931}
2932
2933static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2934                                    SDValue V1, SelectionDAG &DAG) {
2935  switch(Opc) {
2936  default: llvm_unreachable("Unknown x86 shuffle node");
2937  case X86ISD::MOVSHDUP:
2938  case X86ISD::MOVSLDUP:
2939  case X86ISD::MOVDDUP:
2940    return DAG.getNode(Opc, dl, VT, V1);
2941  }
2942}
2943
2944static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2945                                    SDValue V1, unsigned TargetMask,
2946                                    SelectionDAG &DAG) {
2947  switch(Opc) {
2948  default: llvm_unreachable("Unknown x86 shuffle node");
2949  case X86ISD::PSHUFD:
2950  case X86ISD::PSHUFHW:
2951  case X86ISD::PSHUFLW:
2952  case X86ISD::VPERMILP:
2953  case X86ISD::VPERMI:
2954    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2955  }
2956}
2957
2958static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2959                                    SDValue V1, SDValue V2, unsigned TargetMask,
2960                                    SelectionDAG &DAG) {
2961  switch(Opc) {
2962  default: llvm_unreachable("Unknown x86 shuffle node");
2963  case X86ISD::PALIGN:
2964  case X86ISD::SHUFP:
2965  case X86ISD::VPERM2X128:
2966    return DAG.getNode(Opc, dl, VT, V1, V2,
2967                       DAG.getConstant(TargetMask, MVT::i8));
2968  }
2969}
2970
2971static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2972                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2973  switch(Opc) {
2974  default: llvm_unreachable("Unknown x86 shuffle node");
2975  case X86ISD::MOVLHPS:
2976  case X86ISD::MOVLHPD:
2977  case X86ISD::MOVHLPS:
2978  case X86ISD::MOVLPS:
2979  case X86ISD::MOVLPD:
2980  case X86ISD::MOVSS:
2981  case X86ISD::MOVSD:
2982  case X86ISD::UNPCKL:
2983  case X86ISD::UNPCKH:
2984    return DAG.getNode(Opc, dl, VT, V1, V2);
2985  }
2986}
2987
2988SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2989  MachineFunction &MF = DAG.getMachineFunction();
2990  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2991  int ReturnAddrIndex = FuncInfo->getRAIndex();
2992
2993  if (ReturnAddrIndex == 0) {
2994    // Set up a frame object for the return address.
2995    uint64_t SlotSize = TD->getPointerSize();
2996    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2997                                                           false);
2998    FuncInfo->setRAIndex(ReturnAddrIndex);
2999  }
3000
3001  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3002}
3003
3004
3005bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3006                                       bool hasSymbolicDisplacement) {
3007  // Offset should fit into 32 bit immediate field.
3008  if (!isInt<32>(Offset))
3009    return false;
3010
3011  // If we don't have a symbolic displacement - we don't have any extra
3012  // restrictions.
3013  if (!hasSymbolicDisplacement)
3014    return true;
3015
3016  // FIXME: Some tweaks might be needed for medium code model.
3017  if (M != CodeModel::Small && M != CodeModel::Kernel)
3018    return false;
3019
3020  // For small code model we assume that latest object is 16MB before end of 31
3021  // bits boundary. We may also accept pretty large negative constants knowing
3022  // that all objects are in the positive half of address space.
3023  if (M == CodeModel::Small && Offset < 16*1024*1024)
3024    return true;
3025
3026  // For kernel code model we know that all object resist in the negative half
3027  // of 32bits address space. We may not accept negative offsets, since they may
3028  // be just off and we may accept pretty large positive ones.
3029  if (M == CodeModel::Kernel && Offset > 0)
3030    return true;
3031
3032  return false;
3033}
3034
3035/// isCalleePop - Determines whether the callee is required to pop its
3036/// own arguments. Callee pop is necessary to support tail calls.
3037bool X86::isCalleePop(CallingConv::ID CallingConv,
3038                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3039  if (IsVarArg)
3040    return false;
3041
3042  switch (CallingConv) {
3043  default:
3044    return false;
3045  case CallingConv::X86_StdCall:
3046    return !is64Bit;
3047  case CallingConv::X86_FastCall:
3048    return !is64Bit;
3049  case CallingConv::X86_ThisCall:
3050    return !is64Bit;
3051  case CallingConv::Fast:
3052    return TailCallOpt;
3053  case CallingConv::GHC:
3054    return TailCallOpt;
3055  }
3056}
3057
3058/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3059/// specific condition code, returning the condition code and the LHS/RHS of the
3060/// comparison to make.
3061static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3062                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3063  if (!isFP) {
3064    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3065      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3066        // X > -1   -> X == 0, jump !sign.
3067        RHS = DAG.getConstant(0, RHS.getValueType());
3068        return X86::COND_NS;
3069      }
3070      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3071        // X < 0   -> X == 0, jump on sign.
3072        return X86::COND_S;
3073      }
3074      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3075        // X < 1   -> X <= 0
3076        RHS = DAG.getConstant(0, RHS.getValueType());
3077        return X86::COND_LE;
3078      }
3079    }
3080
3081    switch (SetCCOpcode) {
3082    default: llvm_unreachable("Invalid integer condition!");
3083    case ISD::SETEQ:  return X86::COND_E;
3084    case ISD::SETGT:  return X86::COND_G;
3085    case ISD::SETGE:  return X86::COND_GE;
3086    case ISD::SETLT:  return X86::COND_L;
3087    case ISD::SETLE:  return X86::COND_LE;
3088    case ISD::SETNE:  return X86::COND_NE;
3089    case ISD::SETULT: return X86::COND_B;
3090    case ISD::SETUGT: return X86::COND_A;
3091    case ISD::SETULE: return X86::COND_BE;
3092    case ISD::SETUGE: return X86::COND_AE;
3093    }
3094  }
3095
3096  // First determine if it is required or is profitable to flip the operands.
3097
3098  // If LHS is a foldable load, but RHS is not, flip the condition.
3099  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3100      !ISD::isNON_EXTLoad(RHS.getNode())) {
3101    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3102    std::swap(LHS, RHS);
3103  }
3104
3105  switch (SetCCOpcode) {
3106  default: break;
3107  case ISD::SETOLT:
3108  case ISD::SETOLE:
3109  case ISD::SETUGT:
3110  case ISD::SETUGE:
3111    std::swap(LHS, RHS);
3112    break;
3113  }
3114
3115  // On a floating point condition, the flags are set as follows:
3116  // ZF  PF  CF   op
3117  //  0 | 0 | 0 | X > Y
3118  //  0 | 0 | 1 | X < Y
3119  //  1 | 0 | 0 | X == Y
3120  //  1 | 1 | 1 | unordered
3121  switch (SetCCOpcode) {
3122  default: llvm_unreachable("Condcode should be pre-legalized away");
3123  case ISD::SETUEQ:
3124  case ISD::SETEQ:   return X86::COND_E;
3125  case ISD::SETOLT:              // flipped
3126  case ISD::SETOGT:
3127  case ISD::SETGT:   return X86::COND_A;
3128  case ISD::SETOLE:              // flipped
3129  case ISD::SETOGE:
3130  case ISD::SETGE:   return X86::COND_AE;
3131  case ISD::SETUGT:              // flipped
3132  case ISD::SETULT:
3133  case ISD::SETLT:   return X86::COND_B;
3134  case ISD::SETUGE:              // flipped
3135  case ISD::SETULE:
3136  case ISD::SETLE:   return X86::COND_BE;
3137  case ISD::SETONE:
3138  case ISD::SETNE:   return X86::COND_NE;
3139  case ISD::SETUO:   return X86::COND_P;
3140  case ISD::SETO:    return X86::COND_NP;
3141  case ISD::SETOEQ:
3142  case ISD::SETUNE:  return X86::COND_INVALID;
3143  }
3144}
3145
3146/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3147/// code. Current x86 isa includes the following FP cmov instructions:
3148/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3149static bool hasFPCMov(unsigned X86CC) {
3150  switch (X86CC) {
3151  default:
3152    return false;
3153  case X86::COND_B:
3154  case X86::COND_BE:
3155  case X86::COND_E:
3156  case X86::COND_P:
3157  case X86::COND_A:
3158  case X86::COND_AE:
3159  case X86::COND_NE:
3160  case X86::COND_NP:
3161    return true;
3162  }
3163}
3164
3165/// isFPImmLegal - Returns true if the target can instruction select the
3166/// specified FP immediate natively. If false, the legalizer will
3167/// materialize the FP immediate as a load from a constant pool.
3168bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3169  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3170    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3171      return true;
3172  }
3173  return false;
3174}
3175
3176/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3177/// the specified range (L, H].
3178static bool isUndefOrInRange(int Val, int Low, int Hi) {
3179  return (Val < 0) || (Val >= Low && Val < Hi);
3180}
3181
3182/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3183/// specified value.
3184static bool isUndefOrEqual(int Val, int CmpVal) {
3185  if (Val < 0 || Val == CmpVal)
3186    return true;
3187  return false;
3188}
3189
3190/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3191/// from position Pos and ending in Pos+Size, falls within the specified
3192/// sequential range (L, L+Pos]. or is undef.
3193static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3194                                       unsigned Pos, unsigned Size, int Low) {
3195  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3196    if (!isUndefOrEqual(Mask[i], Low))
3197      return false;
3198  return true;
3199}
3200
3201/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3202/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3203/// the second operand.
3204static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3205  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3206    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3207  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3208    return (Mask[0] < 2 && Mask[1] < 2);
3209  return false;
3210}
3211
3212/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3213/// is suitable for input to PSHUFHW.
3214static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3215  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3216    return false;
3217
3218  // Lower quadword copied in order or undef.
3219  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3220    return false;
3221
3222  // Upper quadword shuffled.
3223  for (unsigned i = 4; i != 8; ++i)
3224    if (!isUndefOrInRange(Mask[i], 4, 8))
3225      return false;
3226
3227  if (VT == MVT::v16i16) {
3228    // Lower quadword copied in order or undef.
3229    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3230      return false;
3231
3232    // Upper quadword shuffled.
3233    for (unsigned i = 12; i != 16; ++i)
3234      if (!isUndefOrInRange(Mask[i], 12, 16))
3235        return false;
3236  }
3237
3238  return true;
3239}
3240
3241/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3242/// is suitable for input to PSHUFLW.
3243static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3244  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3245    return false;
3246
3247  // Upper quadword copied in order.
3248  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3249    return false;
3250
3251  // Lower quadword shuffled.
3252  for (unsigned i = 0; i != 4; ++i)
3253    if (!isUndefOrInRange(Mask[i], 0, 4))
3254      return false;
3255
3256  if (VT == MVT::v16i16) {
3257    // Upper quadword copied in order.
3258    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3259      return false;
3260
3261    // Lower quadword shuffled.
3262    for (unsigned i = 8; i != 12; ++i)
3263      if (!isUndefOrInRange(Mask[i], 8, 12))
3264        return false;
3265  }
3266
3267  return true;
3268}
3269
3270/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3271/// is suitable for input to PALIGNR.
3272static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3273                          const X86Subtarget *Subtarget) {
3274  if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3275      (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3276    return false;
3277
3278  unsigned NumElts = VT.getVectorNumElements();
3279  unsigned NumLanes = VT.getSizeInBits()/128;
3280  unsigned NumLaneElts = NumElts/NumLanes;
3281
3282  // Do not handle 64-bit element shuffles with palignr.
3283  if (NumLaneElts == 2)
3284    return false;
3285
3286  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3287    unsigned i;
3288    for (i = 0; i != NumLaneElts; ++i) {
3289      if (Mask[i+l] >= 0)
3290        break;
3291    }
3292
3293    // Lane is all undef, go to next lane
3294    if (i == NumLaneElts)
3295      continue;
3296
3297    int Start = Mask[i+l];
3298
3299    // Make sure its in this lane in one of the sources
3300    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3301        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3302      return false;
3303
3304    // If not lane 0, then we must match lane 0
3305    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3306      return false;
3307
3308    // Correct second source to be contiguous with first source
3309    if (Start >= (int)NumElts)
3310      Start -= NumElts - NumLaneElts;
3311
3312    // Make sure we're shifting in the right direction.
3313    if (Start <= (int)(i+l))
3314      return false;
3315
3316    Start -= i;
3317
3318    // Check the rest of the elements to see if they are consecutive.
3319    for (++i; i != NumLaneElts; ++i) {
3320      int Idx = Mask[i+l];
3321
3322      // Make sure its in this lane
3323      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3324          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3325        return false;
3326
3327      // If not lane 0, then we must match lane 0
3328      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3329        return false;
3330
3331      if (Idx >= (int)NumElts)
3332        Idx -= NumElts - NumLaneElts;
3333
3334      if (!isUndefOrEqual(Idx, Start+i))
3335        return false;
3336
3337    }
3338  }
3339
3340  return true;
3341}
3342
3343/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3344/// the two vector operands have swapped position.
3345static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3346                                     unsigned NumElems) {
3347  for (unsigned i = 0; i != NumElems; ++i) {
3348    int idx = Mask[i];
3349    if (idx < 0)
3350      continue;
3351    else if (idx < (int)NumElems)
3352      Mask[i] = idx + NumElems;
3353    else
3354      Mask[i] = idx - NumElems;
3355  }
3356}
3357
3358/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3359/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3360/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3361/// reverse of what x86 shuffles want.
3362static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3363                        bool Commuted = false) {
3364  if (!HasAVX && VT.getSizeInBits() == 256)
3365    return false;
3366
3367  unsigned NumElems = VT.getVectorNumElements();
3368  unsigned NumLanes = VT.getSizeInBits()/128;
3369  unsigned NumLaneElems = NumElems/NumLanes;
3370
3371  if (NumLaneElems != 2 && NumLaneElems != 4)
3372    return false;
3373
3374  // VSHUFPSY divides the resulting vector into 4 chunks.
3375  // The sources are also splitted into 4 chunks, and each destination
3376  // chunk must come from a different source chunk.
3377  //
3378  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3379  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3380  //
3381  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3382  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3383  //
3384  // VSHUFPDY divides the resulting vector into 4 chunks.
3385  // The sources are also splitted into 4 chunks, and each destination
3386  // chunk must come from a different source chunk.
3387  //
3388  //  SRC1 =>      X3       X2       X1       X0
3389  //  SRC2 =>      Y3       Y2       Y1       Y0
3390  //
3391  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3392  //
3393  unsigned HalfLaneElems = NumLaneElems/2;
3394  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3395    for (unsigned i = 0; i != NumLaneElems; ++i) {
3396      int Idx = Mask[i+l];
3397      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3398      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3399        return false;
3400      // For VSHUFPSY, the mask of the second half must be the same as the
3401      // first but with the appropriate offsets. This works in the same way as
3402      // VPERMILPS works with masks.
3403      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3404        continue;
3405      if (!isUndefOrEqual(Idx, Mask[i]+l))
3406        return false;
3407    }
3408  }
3409
3410  return true;
3411}
3412
3413/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3414/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3415static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3416  if (!VT.is128BitVector())
3417    return false;
3418
3419  unsigned NumElems = VT.getVectorNumElements();
3420
3421  if (NumElems != 4)
3422    return false;
3423
3424  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3425  return isUndefOrEqual(Mask[0], 6) &&
3426         isUndefOrEqual(Mask[1], 7) &&
3427         isUndefOrEqual(Mask[2], 2) &&
3428         isUndefOrEqual(Mask[3], 3);
3429}
3430
3431/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3432/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3433/// <2, 3, 2, 3>
3434static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3435  if (!VT.is128BitVector())
3436    return false;
3437
3438  unsigned NumElems = VT.getVectorNumElements();
3439
3440  if (NumElems != 4)
3441    return false;
3442
3443  return isUndefOrEqual(Mask[0], 2) &&
3444         isUndefOrEqual(Mask[1], 3) &&
3445         isUndefOrEqual(Mask[2], 2) &&
3446         isUndefOrEqual(Mask[3], 3);
3447}
3448
3449/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3450/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3451static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3452  if (!VT.is128BitVector())
3453    return false;
3454
3455  unsigned NumElems = VT.getVectorNumElements();
3456
3457  if (NumElems != 2 && NumElems != 4)
3458    return false;
3459
3460  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3461    if (!isUndefOrEqual(Mask[i], i + NumElems))
3462      return false;
3463
3464  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3465    if (!isUndefOrEqual(Mask[i], i))
3466      return false;
3467
3468  return true;
3469}
3470
3471/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3472/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3473static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3474  if (!VT.is128BitVector())
3475    return false;
3476
3477  unsigned NumElems = VT.getVectorNumElements();
3478
3479  if (NumElems != 2 && NumElems != 4)
3480    return false;
3481
3482  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3483    if (!isUndefOrEqual(Mask[i], i))
3484      return false;
3485
3486  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3487    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3488      return false;
3489
3490  return true;
3491}
3492
3493//
3494// Some special combinations that can be optimized.
3495//
3496static
3497SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3498                               SelectionDAG &DAG) {
3499  EVT VT = SVOp->getValueType(0);
3500  DebugLoc dl = SVOp->getDebugLoc();
3501
3502  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3503    return SDValue();
3504
3505  ArrayRef<int> Mask = SVOp->getMask();
3506
3507  // These are the special masks that may be optimized.
3508  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3509  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3510  bool MatchEvenMask = true;
3511  bool MatchOddMask  = true;
3512  for (int i=0; i<8; ++i) {
3513    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3514      MatchEvenMask = false;
3515    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3516      MatchOddMask = false;
3517  }
3518
3519  if (!MatchEvenMask && !MatchOddMask)
3520    return SDValue();
3521
3522  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3523
3524  SDValue Op0 = SVOp->getOperand(0);
3525  SDValue Op1 = SVOp->getOperand(1);
3526
3527  if (MatchEvenMask) {
3528    // Shift the second operand right to 32 bits.
3529    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3530    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3531  } else {
3532    // Shift the first operand left to 32 bits.
3533    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3534    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3535  }
3536  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3537  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3538}
3539
3540/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3541/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3542static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3543                         bool HasAVX2, bool V2IsSplat = false) {
3544  unsigned NumElts = VT.getVectorNumElements();
3545
3546  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3547         "Unsupported vector type for unpckh");
3548
3549  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3550      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3551    return false;
3552
3553  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3554  // independently on 128-bit lanes.
3555  unsigned NumLanes = VT.getSizeInBits()/128;
3556  unsigned NumLaneElts = NumElts/NumLanes;
3557
3558  for (unsigned l = 0; l != NumLanes; ++l) {
3559    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3560         i != (l+1)*NumLaneElts;
3561         i += 2, ++j) {
3562      int BitI  = Mask[i];
3563      int BitI1 = Mask[i+1];
3564      if (!isUndefOrEqual(BitI, j))
3565        return false;
3566      if (V2IsSplat) {
3567        if (!isUndefOrEqual(BitI1, NumElts))
3568          return false;
3569      } else {
3570        if (!isUndefOrEqual(BitI1, j + NumElts))
3571          return false;
3572      }
3573    }
3574  }
3575
3576  return true;
3577}
3578
3579/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3580/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3581static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3582                         bool HasAVX2, bool V2IsSplat = false) {
3583  unsigned NumElts = VT.getVectorNumElements();
3584
3585  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3586         "Unsupported vector type for unpckh");
3587
3588  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3589      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3590    return false;
3591
3592  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593  // independently on 128-bit lanes.
3594  unsigned NumLanes = VT.getSizeInBits()/128;
3595  unsigned NumLaneElts = NumElts/NumLanes;
3596
3597  for (unsigned l = 0; l != NumLanes; ++l) {
3598    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3599         i != (l+1)*NumLaneElts; i += 2, ++j) {
3600      int BitI  = Mask[i];
3601      int BitI1 = Mask[i+1];
3602      if (!isUndefOrEqual(BitI, j))
3603        return false;
3604      if (V2IsSplat) {
3605        if (isUndefOrEqual(BitI1, NumElts))
3606          return false;
3607      } else {
3608        if (!isUndefOrEqual(BitI1, j+NumElts))
3609          return false;
3610      }
3611    }
3612  }
3613  return true;
3614}
3615
3616/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3617/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3618/// <0, 0, 1, 1>
3619static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3620                                  bool HasAVX2) {
3621  unsigned NumElts = VT.getVectorNumElements();
3622
3623  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3624         "Unsupported vector type for unpckh");
3625
3626  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3627      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3628    return false;
3629
3630  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3631  // FIXME: Need a better way to get rid of this, there's no latency difference
3632  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3633  // the former later. We should also remove the "_undef" special mask.
3634  if (NumElts == 4 && VT.getSizeInBits() == 256)
3635    return false;
3636
3637  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3638  // independently on 128-bit lanes.
3639  unsigned NumLanes = VT.getSizeInBits()/128;
3640  unsigned NumLaneElts = NumElts/NumLanes;
3641
3642  for (unsigned l = 0; l != NumLanes; ++l) {
3643    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3644         i != (l+1)*NumLaneElts;
3645         i += 2, ++j) {
3646      int BitI  = Mask[i];
3647      int BitI1 = Mask[i+1];
3648
3649      if (!isUndefOrEqual(BitI, j))
3650        return false;
3651      if (!isUndefOrEqual(BitI1, j))
3652        return false;
3653    }
3654  }
3655
3656  return true;
3657}
3658
3659/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3660/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3661/// <2, 2, 3, 3>
3662static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3663  unsigned NumElts = VT.getVectorNumElements();
3664
3665  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3666         "Unsupported vector type for unpckh");
3667
3668  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3669      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3670    return false;
3671
3672  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3673  // independently on 128-bit lanes.
3674  unsigned NumLanes = VT.getSizeInBits()/128;
3675  unsigned NumLaneElts = NumElts/NumLanes;
3676
3677  for (unsigned l = 0; l != NumLanes; ++l) {
3678    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3679         i != (l+1)*NumLaneElts; i += 2, ++j) {
3680      int BitI  = Mask[i];
3681      int BitI1 = Mask[i+1];
3682      if (!isUndefOrEqual(BitI, j))
3683        return false;
3684      if (!isUndefOrEqual(BitI1, j))
3685        return false;
3686    }
3687  }
3688  return true;
3689}
3690
3691/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3692/// specifies a shuffle of elements that is suitable for input to MOVSS,
3693/// MOVSD, and MOVD, i.e. setting the lowest element.
3694static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3695  if (VT.getVectorElementType().getSizeInBits() < 32)
3696    return false;
3697  if (!VT.is128BitVector())
3698    return false;
3699
3700  unsigned NumElts = VT.getVectorNumElements();
3701
3702  if (!isUndefOrEqual(Mask[0], NumElts))
3703    return false;
3704
3705  for (unsigned i = 1; i != NumElts; ++i)
3706    if (!isUndefOrEqual(Mask[i], i))
3707      return false;
3708
3709  return true;
3710}
3711
3712/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3713/// as permutations between 128-bit chunks or halves. As an example: this
3714/// shuffle bellow:
3715///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3716/// The first half comes from the second half of V1 and the second half from the
3717/// the second half of V2.
3718static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3719  if (!HasAVX || !VT.is256BitVector())
3720    return false;
3721
3722  // The shuffle result is divided into half A and half B. In total the two
3723  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3724  // B must come from C, D, E or F.
3725  unsigned HalfSize = VT.getVectorNumElements()/2;
3726  bool MatchA = false, MatchB = false;
3727
3728  // Check if A comes from one of C, D, E, F.
3729  for (unsigned Half = 0; Half != 4; ++Half) {
3730    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3731      MatchA = true;
3732      break;
3733    }
3734  }
3735
3736  // Check if B comes from one of C, D, E, F.
3737  for (unsigned Half = 0; Half != 4; ++Half) {
3738    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3739      MatchB = true;
3740      break;
3741    }
3742  }
3743
3744  return MatchA && MatchB;
3745}
3746
3747/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3748/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3749static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3750  EVT VT = SVOp->getValueType(0);
3751
3752  unsigned HalfSize = VT.getVectorNumElements()/2;
3753
3754  unsigned FstHalf = 0, SndHalf = 0;
3755  for (unsigned i = 0; i < HalfSize; ++i) {
3756    if (SVOp->getMaskElt(i) > 0) {
3757      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3758      break;
3759    }
3760  }
3761  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3762    if (SVOp->getMaskElt(i) > 0) {
3763      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3764      break;
3765    }
3766  }
3767
3768  return (FstHalf | (SndHalf << 4));
3769}
3770
3771/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3772/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3773/// Note that VPERMIL mask matching is different depending whether theunderlying
3774/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3775/// to the same elements of the low, but to the higher half of the source.
3776/// In VPERMILPD the two lanes could be shuffled independently of each other
3777/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3778static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3779  if (!HasAVX)
3780    return false;
3781
3782  unsigned NumElts = VT.getVectorNumElements();
3783  // Only match 256-bit with 32/64-bit types
3784  if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3785    return false;
3786
3787  unsigned NumLanes = VT.getSizeInBits()/128;
3788  unsigned LaneSize = NumElts/NumLanes;
3789  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3790    for (unsigned i = 0; i != LaneSize; ++i) {
3791      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3792        return false;
3793      if (NumElts != 8 || l == 0)
3794        continue;
3795      // VPERMILPS handling
3796      if (Mask[i] < 0)
3797        continue;
3798      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3799        return false;
3800    }
3801  }
3802
3803  return true;
3804}
3805
3806/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3807/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3808/// element of vector 2 and the other elements to come from vector 1 in order.
3809static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3810                               bool V2IsSplat = false, bool V2IsUndef = false) {
3811  if (!VT.is128BitVector())
3812    return false;
3813
3814  unsigned NumOps = VT.getVectorNumElements();
3815  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3816    return false;
3817
3818  if (!isUndefOrEqual(Mask[0], 0))
3819    return false;
3820
3821  for (unsigned i = 1; i != NumOps; ++i)
3822    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3823          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3824          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3825      return false;
3826
3827  return true;
3828}
3829
3830/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3831/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3832/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3833static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3834                           const X86Subtarget *Subtarget) {
3835  if (!Subtarget->hasSSE3())
3836    return false;
3837
3838  unsigned NumElems = VT.getVectorNumElements();
3839
3840  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3841      (VT.getSizeInBits() == 256 && NumElems != 8))
3842    return false;
3843
3844  // "i+1" is the value the indexed mask element must have
3845  for (unsigned i = 0; i != NumElems; i += 2)
3846    if (!isUndefOrEqual(Mask[i], i+1) ||
3847        !isUndefOrEqual(Mask[i+1], i+1))
3848      return false;
3849
3850  return true;
3851}
3852
3853/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3854/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3855/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3856static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3857                           const X86Subtarget *Subtarget) {
3858  if (!Subtarget->hasSSE3())
3859    return false;
3860
3861  unsigned NumElems = VT.getVectorNumElements();
3862
3863  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3864      (VT.getSizeInBits() == 256 && NumElems != 8))
3865    return false;
3866
3867  // "i" is the value the indexed mask element must have
3868  for (unsigned i = 0; i != NumElems; i += 2)
3869    if (!isUndefOrEqual(Mask[i], i) ||
3870        !isUndefOrEqual(Mask[i+1], i))
3871      return false;
3872
3873  return true;
3874}
3875
3876/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3877/// specifies a shuffle of elements that is suitable for input to 256-bit
3878/// version of MOVDDUP.
3879static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3880  if (!HasAVX || !VT.is256BitVector())
3881    return false;
3882
3883  unsigned NumElts = VT.getVectorNumElements();
3884  if (NumElts != 4)
3885    return false;
3886
3887  for (unsigned i = 0; i != NumElts/2; ++i)
3888    if (!isUndefOrEqual(Mask[i], 0))
3889      return false;
3890  for (unsigned i = NumElts/2; i != NumElts; ++i)
3891    if (!isUndefOrEqual(Mask[i], NumElts/2))
3892      return false;
3893  return true;
3894}
3895
3896/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3897/// specifies a shuffle of elements that is suitable for input to 128-bit
3898/// version of MOVDDUP.
3899static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3900  if (!VT.is128BitVector())
3901    return false;
3902
3903  unsigned e = VT.getVectorNumElements() / 2;
3904  for (unsigned i = 0; i != e; ++i)
3905    if (!isUndefOrEqual(Mask[i], i))
3906      return false;
3907  for (unsigned i = 0; i != e; ++i)
3908    if (!isUndefOrEqual(Mask[e+i], i))
3909      return false;
3910  return true;
3911}
3912
3913/// isVEXTRACTF128Index - Return true if the specified
3914/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3915/// suitable for input to VEXTRACTF128.
3916bool X86::isVEXTRACTF128Index(SDNode *N) {
3917  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3918    return false;
3919
3920  // The index should be aligned on a 128-bit boundary.
3921  uint64_t Index =
3922    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3923
3924  unsigned VL = N->getValueType(0).getVectorNumElements();
3925  unsigned VBits = N->getValueType(0).getSizeInBits();
3926  unsigned ElSize = VBits / VL;
3927  bool Result = (Index * ElSize) % 128 == 0;
3928
3929  return Result;
3930}
3931
3932/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3933/// operand specifies a subvector insert that is suitable for input to
3934/// VINSERTF128.
3935bool X86::isVINSERTF128Index(SDNode *N) {
3936  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3937    return false;
3938
3939  // The index should be aligned on a 128-bit boundary.
3940  uint64_t Index =
3941    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3942
3943  unsigned VL = N->getValueType(0).getVectorNumElements();
3944  unsigned VBits = N->getValueType(0).getSizeInBits();
3945  unsigned ElSize = VBits / VL;
3946  bool Result = (Index * ElSize) % 128 == 0;
3947
3948  return Result;
3949}
3950
3951/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3952/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3953/// Handles 128-bit and 256-bit.
3954static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3955  EVT VT = N->getValueType(0);
3956
3957  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3958         "Unsupported vector type for PSHUF/SHUFP");
3959
3960  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3961  // independently on 128-bit lanes.
3962  unsigned NumElts = VT.getVectorNumElements();
3963  unsigned NumLanes = VT.getSizeInBits()/128;
3964  unsigned NumLaneElts = NumElts/NumLanes;
3965
3966  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3967         "Only supports 2 or 4 elements per lane");
3968
3969  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3970  unsigned Mask = 0;
3971  for (unsigned i = 0; i != NumElts; ++i) {
3972    int Elt = N->getMaskElt(i);
3973    if (Elt < 0) continue;
3974    Elt &= NumLaneElts - 1;
3975    unsigned ShAmt = (i << Shift) % 8;
3976    Mask |= Elt << ShAmt;
3977  }
3978
3979  return Mask;
3980}
3981
3982/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3983/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3984static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3985  EVT VT = N->getValueType(0);
3986
3987  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3988         "Unsupported vector type for PSHUFHW");
3989
3990  unsigned NumElts = VT.getVectorNumElements();
3991
3992  unsigned Mask = 0;
3993  for (unsigned l = 0; l != NumElts; l += 8) {
3994    // 8 nodes per lane, but we only care about the last 4.
3995    for (unsigned i = 0; i < 4; ++i) {
3996      int Elt = N->getMaskElt(l+i+4);
3997      if (Elt < 0) continue;
3998      Elt &= 0x3; // only 2-bits.
3999      Mask |= Elt << (i * 2);
4000    }
4001  }
4002
4003  return Mask;
4004}
4005
4006/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4007/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4008static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4009  EVT VT = N->getValueType(0);
4010
4011  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4012         "Unsupported vector type for PSHUFHW");
4013
4014  unsigned NumElts = VT.getVectorNumElements();
4015
4016  unsigned Mask = 0;
4017  for (unsigned l = 0; l != NumElts; l += 8) {
4018    // 8 nodes per lane, but we only care about the first 4.
4019    for (unsigned i = 0; i < 4; ++i) {
4020      int Elt = N->getMaskElt(l+i);
4021      if (Elt < 0) continue;
4022      Elt &= 0x3; // only 2-bits
4023      Mask |= Elt << (i * 2);
4024    }
4025  }
4026
4027  return Mask;
4028}
4029
4030/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4031/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4032static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4033  EVT VT = SVOp->getValueType(0);
4034  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4035
4036  unsigned NumElts = VT.getVectorNumElements();
4037  unsigned NumLanes = VT.getSizeInBits()/128;
4038  unsigned NumLaneElts = NumElts/NumLanes;
4039
4040  int Val = 0;
4041  unsigned i;
4042  for (i = 0; i != NumElts; ++i) {
4043    Val = SVOp->getMaskElt(i);
4044    if (Val >= 0)
4045      break;
4046  }
4047  if (Val >= (int)NumElts)
4048    Val -= NumElts - NumLaneElts;
4049
4050  assert(Val - i > 0 && "PALIGNR imm should be positive");
4051  return (Val - i) * EltSize;
4052}
4053
4054/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4055/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4056/// instructions.
4057unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4058  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4059    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4060
4061  uint64_t Index =
4062    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4063
4064  EVT VecVT = N->getOperand(0).getValueType();
4065  EVT ElVT = VecVT.getVectorElementType();
4066
4067  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4068  return Index / NumElemsPerChunk;
4069}
4070
4071/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4072/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4073/// instructions.
4074unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4075  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4077
4078  uint64_t Index =
4079    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080
4081  EVT VecVT = N->getValueType(0);
4082  EVT ElVT = VecVT.getVectorElementType();
4083
4084  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4085  return Index / NumElemsPerChunk;
4086}
4087
4088/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4089/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4090/// Handles 256-bit.
4091static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4092  EVT VT = N->getValueType(0);
4093
4094  unsigned NumElts = VT.getVectorNumElements();
4095
4096  assert((VT.is256BitVector() && NumElts == 4) &&
4097         "Unsupported vector type for VPERMQ/VPERMPD");
4098
4099  unsigned Mask = 0;
4100  for (unsigned i = 0; i != NumElts; ++i) {
4101    int Elt = N->getMaskElt(i);
4102    if (Elt < 0)
4103      continue;
4104    Mask |= Elt << (i*2);
4105  }
4106
4107  return Mask;
4108}
4109/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4110/// constant +0.0.
4111bool X86::isZeroNode(SDValue Elt) {
4112  return ((isa<ConstantSDNode>(Elt) &&
4113           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4114          (isa<ConstantFPSDNode>(Elt) &&
4115           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4116}
4117
4118/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4119/// their permute mask.
4120static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4121                                    SelectionDAG &DAG) {
4122  EVT VT = SVOp->getValueType(0);
4123  unsigned NumElems = VT.getVectorNumElements();
4124  SmallVector<int, 8> MaskVec;
4125
4126  for (unsigned i = 0; i != NumElems; ++i) {
4127    int Idx = SVOp->getMaskElt(i);
4128    if (Idx >= 0) {
4129      if (Idx < (int)NumElems)
4130        Idx += NumElems;
4131      else
4132        Idx -= NumElems;
4133    }
4134    MaskVec.push_back(Idx);
4135  }
4136  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4137                              SVOp->getOperand(0), &MaskVec[0]);
4138}
4139
4140/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4141/// match movhlps. The lower half elements should come from upper half of
4142/// V1 (and in order), and the upper half elements should come from the upper
4143/// half of V2 (and in order).
4144static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4145  if (!VT.is128BitVector())
4146    return false;
4147  if (VT.getVectorNumElements() != 4)
4148    return false;
4149  for (unsigned i = 0, e = 2; i != e; ++i)
4150    if (!isUndefOrEqual(Mask[i], i+2))
4151      return false;
4152  for (unsigned i = 2; i != 4; ++i)
4153    if (!isUndefOrEqual(Mask[i], i+4))
4154      return false;
4155  return true;
4156}
4157
4158/// isScalarLoadToVector - Returns true if the node is a scalar load that
4159/// is promoted to a vector. It also returns the LoadSDNode by reference if
4160/// required.
4161static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4162  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4163    return false;
4164  N = N->getOperand(0).getNode();
4165  if (!ISD::isNON_EXTLoad(N))
4166    return false;
4167  if (LD)
4168    *LD = cast<LoadSDNode>(N);
4169  return true;
4170}
4171
4172// Test whether the given value is a vector value which will be legalized
4173// into a load.
4174static bool WillBeConstantPoolLoad(SDNode *N) {
4175  if (N->getOpcode() != ISD::BUILD_VECTOR)
4176    return false;
4177
4178  // Check for any non-constant elements.
4179  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4180    switch (N->getOperand(i).getNode()->getOpcode()) {
4181    case ISD::UNDEF:
4182    case ISD::ConstantFP:
4183    case ISD::Constant:
4184      break;
4185    default:
4186      return false;
4187    }
4188
4189  // Vectors of all-zeros and all-ones are materialized with special
4190  // instructions rather than being loaded.
4191  return !ISD::isBuildVectorAllZeros(N) &&
4192         !ISD::isBuildVectorAllOnes(N);
4193}
4194
4195/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4196/// match movlp{s|d}. The lower half elements should come from lower half of
4197/// V1 (and in order), and the upper half elements should come from the upper
4198/// half of V2 (and in order). And since V1 will become the source of the
4199/// MOVLP, it must be either a vector load or a scalar load to vector.
4200static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4201                               ArrayRef<int> Mask, EVT VT) {
4202  if (!VT.is128BitVector())
4203    return false;
4204
4205  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4206    return false;
4207  // Is V2 is a vector load, don't do this transformation. We will try to use
4208  // load folding shufps op.
4209  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4210    return false;
4211
4212  unsigned NumElems = VT.getVectorNumElements();
4213
4214  if (NumElems != 2 && NumElems != 4)
4215    return false;
4216  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4217    if (!isUndefOrEqual(Mask[i], i))
4218      return false;
4219  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4220    if (!isUndefOrEqual(Mask[i], i+NumElems))
4221      return false;
4222  return true;
4223}
4224
4225/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4226/// all the same.
4227static bool isSplatVector(SDNode *N) {
4228  if (N->getOpcode() != ISD::BUILD_VECTOR)
4229    return false;
4230
4231  SDValue SplatValue = N->getOperand(0);
4232  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4233    if (N->getOperand(i) != SplatValue)
4234      return false;
4235  return true;
4236}
4237
4238/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4239/// to an zero vector.
4240/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4241static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4242  SDValue V1 = N->getOperand(0);
4243  SDValue V2 = N->getOperand(1);
4244  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4245  for (unsigned i = 0; i != NumElems; ++i) {
4246    int Idx = N->getMaskElt(i);
4247    if (Idx >= (int)NumElems) {
4248      unsigned Opc = V2.getOpcode();
4249      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4250        continue;
4251      if (Opc != ISD::BUILD_VECTOR ||
4252          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4253        return false;
4254    } else if (Idx >= 0) {
4255      unsigned Opc = V1.getOpcode();
4256      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4257        continue;
4258      if (Opc != ISD::BUILD_VECTOR ||
4259          !X86::isZeroNode(V1.getOperand(Idx)))
4260        return false;
4261    }
4262  }
4263  return true;
4264}
4265
4266/// getZeroVector - Returns a vector of specified type with all zero elements.
4267///
4268static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4269                             SelectionDAG &DAG, DebugLoc dl) {
4270  assert(VT.isVector() && "Expected a vector type");
4271  unsigned Size = VT.getSizeInBits();
4272
4273  // Always build SSE zero vectors as <4 x i32> bitcasted
4274  // to their dest type. This ensures they get CSE'd.
4275  SDValue Vec;
4276  if (Size == 128) {  // SSE
4277    if (Subtarget->hasSSE2()) {  // SSE2
4278      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4279      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4280    } else { // SSE1
4281      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4282      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4283    }
4284  } else if (Size == 256) { // AVX
4285    if (Subtarget->hasAVX2()) { // AVX2
4286      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4287      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4288      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4289    } else {
4290      // 256-bit logic and arithmetic instructions in AVX are all
4291      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4292      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4293      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4294      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4295    }
4296  } else
4297    llvm_unreachable("Unexpected vector type");
4298
4299  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4300}
4301
4302/// getOnesVector - Returns a vector of specified type with all bits set.
4303/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4304/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4305/// Then bitcast to their original type, ensuring they get CSE'd.
4306static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4307                             DebugLoc dl) {
4308  assert(VT.isVector() && "Expected a vector type");
4309  unsigned Size = VT.getSizeInBits();
4310
4311  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4312  SDValue Vec;
4313  if (Size == 256) {
4314    if (HasAVX2) { // AVX2
4315      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4316      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4317    } else { // AVX
4318      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4319      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4320    }
4321  } else if (Size == 128) {
4322    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4323  } else
4324    llvm_unreachable("Unexpected vector type");
4325
4326  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4327}
4328
4329/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4330/// that point to V2 points to its first element.
4331static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4332  for (unsigned i = 0; i != NumElems; ++i) {
4333    if (Mask[i] > (int)NumElems) {
4334      Mask[i] = NumElems;
4335    }
4336  }
4337}
4338
4339/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4340/// operation of specified width.
4341static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4342                       SDValue V2) {
4343  unsigned NumElems = VT.getVectorNumElements();
4344  SmallVector<int, 8> Mask;
4345  Mask.push_back(NumElems);
4346  for (unsigned i = 1; i != NumElems; ++i)
4347    Mask.push_back(i);
4348  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4349}
4350
4351/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4352static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4353                          SDValue V2) {
4354  unsigned NumElems = VT.getVectorNumElements();
4355  SmallVector<int, 8> Mask;
4356  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4357    Mask.push_back(i);
4358    Mask.push_back(i + NumElems);
4359  }
4360  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4361}
4362
4363/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4364static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4365                          SDValue V2) {
4366  unsigned NumElems = VT.getVectorNumElements();
4367  SmallVector<int, 8> Mask;
4368  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4369    Mask.push_back(i + Half);
4370    Mask.push_back(i + NumElems + Half);
4371  }
4372  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4373}
4374
4375// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4376// a generic shuffle instruction because the target has no such instructions.
4377// Generate shuffles which repeat i16 and i8 several times until they can be
4378// represented by v4f32 and then be manipulated by target suported shuffles.
4379static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4380  EVT VT = V.getValueType();
4381  int NumElems = VT.getVectorNumElements();
4382  DebugLoc dl = V.getDebugLoc();
4383
4384  while (NumElems > 4) {
4385    if (EltNo < NumElems/2) {
4386      V = getUnpackl(DAG, dl, VT, V, V);
4387    } else {
4388      V = getUnpackh(DAG, dl, VT, V, V);
4389      EltNo -= NumElems/2;
4390    }
4391    NumElems >>= 1;
4392  }
4393  return V;
4394}
4395
4396/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4397static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4398  EVT VT = V.getValueType();
4399  DebugLoc dl = V.getDebugLoc();
4400  unsigned Size = VT.getSizeInBits();
4401
4402  if (Size == 128) {
4403    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4404    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4405    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4406                             &SplatMask[0]);
4407  } else if (Size == 256) {
4408    // To use VPERMILPS to splat scalars, the second half of indicies must
4409    // refer to the higher part, which is a duplication of the lower one,
4410    // because VPERMILPS can only handle in-lane permutations.
4411    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4412                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4413
4414    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4415    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4416                             &SplatMask[0]);
4417  } else
4418    llvm_unreachable("Vector size not supported");
4419
4420  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4421}
4422
4423/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4424static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4425  EVT SrcVT = SV->getValueType(0);
4426  SDValue V1 = SV->getOperand(0);
4427  DebugLoc dl = SV->getDebugLoc();
4428
4429  int EltNo = SV->getSplatIndex();
4430  int NumElems = SrcVT.getVectorNumElements();
4431  unsigned Size = SrcVT.getSizeInBits();
4432
4433  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4434          "Unknown how to promote splat for type");
4435
4436  // Extract the 128-bit part containing the splat element and update
4437  // the splat element index when it refers to the higher register.
4438  if (Size == 256) {
4439    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4440    if (EltNo >= NumElems/2)
4441      EltNo -= NumElems/2;
4442  }
4443
4444  // All i16 and i8 vector types can't be used directly by a generic shuffle
4445  // instruction because the target has no such instruction. Generate shuffles
4446  // which repeat i16 and i8 several times until they fit in i32, and then can
4447  // be manipulated by target suported shuffles.
4448  EVT EltVT = SrcVT.getVectorElementType();
4449  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4450    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4451
4452  // Recreate the 256-bit vector and place the same 128-bit vector
4453  // into the low and high part. This is necessary because we want
4454  // to use VPERM* to shuffle the vectors
4455  if (Size == 256) {
4456    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4457  }
4458
4459  return getLegalSplat(DAG, V1, EltNo);
4460}
4461
4462/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4463/// vector of zero or undef vector.  This produces a shuffle where the low
4464/// element of V2 is swizzled into the zero/undef vector, landing at element
4465/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4466static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4467                                           bool IsZero,
4468                                           const X86Subtarget *Subtarget,
4469                                           SelectionDAG &DAG) {
4470  EVT VT = V2.getValueType();
4471  SDValue V1 = IsZero
4472    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4473  unsigned NumElems = VT.getVectorNumElements();
4474  SmallVector<int, 16> MaskVec;
4475  for (unsigned i = 0; i != NumElems; ++i)
4476    // If this is the insertion idx, put the low elt of V2 here.
4477    MaskVec.push_back(i == Idx ? NumElems : i);
4478  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4479}
4480
4481/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4482/// target specific opcode. Returns true if the Mask could be calculated.
4483/// Sets IsUnary to true if only uses one source.
4484static bool getTargetShuffleMask(SDNode *N, MVT VT,
4485                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4486  unsigned NumElems = VT.getVectorNumElements();
4487  SDValue ImmN;
4488
4489  IsUnary = false;
4490  switch(N->getOpcode()) {
4491  case X86ISD::SHUFP:
4492    ImmN = N->getOperand(N->getNumOperands()-1);
4493    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494    break;
4495  case X86ISD::UNPCKH:
4496    DecodeUNPCKHMask(VT, Mask);
4497    break;
4498  case X86ISD::UNPCKL:
4499    DecodeUNPCKLMask(VT, Mask);
4500    break;
4501  case X86ISD::MOVHLPS:
4502    DecodeMOVHLPSMask(NumElems, Mask);
4503    break;
4504  case X86ISD::MOVLHPS:
4505    DecodeMOVLHPSMask(NumElems, Mask);
4506    break;
4507  case X86ISD::PSHUFD:
4508  case X86ISD::VPERMILP:
4509    ImmN = N->getOperand(N->getNumOperands()-1);
4510    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511    IsUnary = true;
4512    break;
4513  case X86ISD::PSHUFHW:
4514    ImmN = N->getOperand(N->getNumOperands()-1);
4515    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516    IsUnary = true;
4517    break;
4518  case X86ISD::PSHUFLW:
4519    ImmN = N->getOperand(N->getNumOperands()-1);
4520    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521    IsUnary = true;
4522    break;
4523  case X86ISD::VPERMI:
4524    ImmN = N->getOperand(N->getNumOperands()-1);
4525    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526    IsUnary = true;
4527    break;
4528  case X86ISD::MOVSS:
4529  case X86ISD::MOVSD: {
4530    // The index 0 always comes from the first element of the second source,
4531    // this is why MOVSS and MOVSD are used in the first place. The other
4532    // elements come from the other positions of the first source vector
4533    Mask.push_back(NumElems);
4534    for (unsigned i = 1; i != NumElems; ++i) {
4535      Mask.push_back(i);
4536    }
4537    break;
4538  }
4539  case X86ISD::VPERM2X128:
4540    ImmN = N->getOperand(N->getNumOperands()-1);
4541    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4542    if (Mask.empty()) return false;
4543    break;
4544  case X86ISD::MOVDDUP:
4545  case X86ISD::MOVLHPD:
4546  case X86ISD::MOVLPD:
4547  case X86ISD::MOVLPS:
4548  case X86ISD::MOVSHDUP:
4549  case X86ISD::MOVSLDUP:
4550  case X86ISD::PALIGN:
4551    // Not yet implemented
4552    return false;
4553  default: llvm_unreachable("unknown target shuffle node");
4554  }
4555
4556  return true;
4557}
4558
4559/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4560/// element of the result of the vector shuffle.
4561static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4562                                   unsigned Depth) {
4563  if (Depth == 6)
4564    return SDValue();  // Limit search depth.
4565
4566  SDValue V = SDValue(N, 0);
4567  EVT VT = V.getValueType();
4568  unsigned Opcode = V.getOpcode();
4569
4570  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4571  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4572    int Elt = SV->getMaskElt(Index);
4573
4574    if (Elt < 0)
4575      return DAG.getUNDEF(VT.getVectorElementType());
4576
4577    unsigned NumElems = VT.getVectorNumElements();
4578    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4579                                         : SV->getOperand(1);
4580    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4581  }
4582
4583  // Recurse into target specific vector shuffles to find scalars.
4584  if (isTargetShuffle(Opcode)) {
4585    MVT ShufVT = V.getValueType().getSimpleVT();
4586    unsigned NumElems = ShufVT.getVectorNumElements();
4587    SmallVector<int, 16> ShuffleMask;
4588    SDValue ImmN;
4589    bool IsUnary;
4590
4591    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4592      return SDValue();
4593
4594    int Elt = ShuffleMask[Index];
4595    if (Elt < 0)
4596      return DAG.getUNDEF(ShufVT.getVectorElementType());
4597
4598    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4599                                         : N->getOperand(1);
4600    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4601                               Depth+1);
4602  }
4603
4604  // Actual nodes that may contain scalar elements
4605  if (Opcode == ISD::BITCAST) {
4606    V = V.getOperand(0);
4607    EVT SrcVT = V.getValueType();
4608    unsigned NumElems = VT.getVectorNumElements();
4609
4610    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4611      return SDValue();
4612  }
4613
4614  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4615    return (Index == 0) ? V.getOperand(0)
4616                        : DAG.getUNDEF(VT.getVectorElementType());
4617
4618  if (V.getOpcode() == ISD::BUILD_VECTOR)
4619    return V.getOperand(Index);
4620
4621  return SDValue();
4622}
4623
4624/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4625/// shuffle operation which come from a consecutively from a zero. The
4626/// search can start in two different directions, from left or right.
4627static
4628unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4629                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4630  unsigned i;
4631  for (i = 0; i != NumElems; ++i) {
4632    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4633    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4634    if (!(Elt.getNode() &&
4635         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4636      break;
4637  }
4638
4639  return i;
4640}
4641
4642/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4643/// correspond consecutively to elements from one of the vector operands,
4644/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4645static
4646bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4647                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4648                              unsigned NumElems, unsigned &OpNum) {
4649  bool SeenV1 = false;
4650  bool SeenV2 = false;
4651
4652  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4653    int Idx = SVOp->getMaskElt(i);
4654    // Ignore undef indicies
4655    if (Idx < 0)
4656      continue;
4657
4658    if (Idx < (int)NumElems)
4659      SeenV1 = true;
4660    else
4661      SeenV2 = true;
4662
4663    // Only accept consecutive elements from the same vector
4664    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4665      return false;
4666  }
4667
4668  OpNum = SeenV1 ? 0 : 1;
4669  return true;
4670}
4671
4672/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4673/// logical left shift of a vector.
4674static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4675                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4676  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4677  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4678              false /* check zeros from right */, DAG);
4679  unsigned OpSrc;
4680
4681  if (!NumZeros)
4682    return false;
4683
4684  // Considering the elements in the mask that are not consecutive zeros,
4685  // check if they consecutively come from only one of the source vectors.
4686  //
4687  //               V1 = {X, A, B, C}     0
4688  //                         \  \  \    /
4689  //   vector_shuffle V1, V2 <1, 2, 3, X>
4690  //
4691  if (!isShuffleMaskConsecutive(SVOp,
4692            0,                   // Mask Start Index
4693            NumElems-NumZeros,   // Mask End Index(exclusive)
4694            NumZeros,            // Where to start looking in the src vector
4695            NumElems,            // Number of elements in vector
4696            OpSrc))              // Which source operand ?
4697    return false;
4698
4699  isLeft = false;
4700  ShAmt = NumZeros;
4701  ShVal = SVOp->getOperand(OpSrc);
4702  return true;
4703}
4704
4705/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4706/// logical left shift of a vector.
4707static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4708                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4709  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4710  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4711              true /* check zeros from left */, DAG);
4712  unsigned OpSrc;
4713
4714  if (!NumZeros)
4715    return false;
4716
4717  // Considering the elements in the mask that are not consecutive zeros,
4718  // check if they consecutively come from only one of the source vectors.
4719  //
4720  //                           0    { A, B, X, X } = V2
4721  //                          / \    /  /
4722  //   vector_shuffle V1, V2 <X, X, 4, 5>
4723  //
4724  if (!isShuffleMaskConsecutive(SVOp,
4725            NumZeros,     // Mask Start Index
4726            NumElems,     // Mask End Index(exclusive)
4727            0,            // Where to start looking in the src vector
4728            NumElems,     // Number of elements in vector
4729            OpSrc))       // Which source operand ?
4730    return false;
4731
4732  isLeft = true;
4733  ShAmt = NumZeros;
4734  ShVal = SVOp->getOperand(OpSrc);
4735  return true;
4736}
4737
4738/// isVectorShift - Returns true if the shuffle can be implemented as a
4739/// logical left or right shift of a vector.
4740static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4741                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4742  // Although the logic below support any bitwidth size, there are no
4743  // shift instructions which handle more than 128-bit vectors.
4744  if (!SVOp->getValueType(0).is128BitVector())
4745    return false;
4746
4747  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4748      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4749    return true;
4750
4751  return false;
4752}
4753
4754/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4755///
4756static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4757                                       unsigned NumNonZero, unsigned NumZero,
4758                                       SelectionDAG &DAG,
4759                                       const X86Subtarget* Subtarget,
4760                                       const TargetLowering &TLI) {
4761  if (NumNonZero > 8)
4762    return SDValue();
4763
4764  DebugLoc dl = Op.getDebugLoc();
4765  SDValue V(0, 0);
4766  bool First = true;
4767  for (unsigned i = 0; i < 16; ++i) {
4768    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4769    if (ThisIsNonZero && First) {
4770      if (NumZero)
4771        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4772      else
4773        V = DAG.getUNDEF(MVT::v8i16);
4774      First = false;
4775    }
4776
4777    if ((i & 1) != 0) {
4778      SDValue ThisElt(0, 0), LastElt(0, 0);
4779      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4780      if (LastIsNonZero) {
4781        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4782                              MVT::i16, Op.getOperand(i-1));
4783      }
4784      if (ThisIsNonZero) {
4785        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4786        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4787                              ThisElt, DAG.getConstant(8, MVT::i8));
4788        if (LastIsNonZero)
4789          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4790      } else
4791        ThisElt = LastElt;
4792
4793      if (ThisElt.getNode())
4794        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4795                        DAG.getIntPtrConstant(i/2));
4796    }
4797  }
4798
4799  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4800}
4801
4802/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4803///
4804static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4805                                     unsigned NumNonZero, unsigned NumZero,
4806                                     SelectionDAG &DAG,
4807                                     const X86Subtarget* Subtarget,
4808                                     const TargetLowering &TLI) {
4809  if (NumNonZero > 4)
4810    return SDValue();
4811
4812  DebugLoc dl = Op.getDebugLoc();
4813  SDValue V(0, 0);
4814  bool First = true;
4815  for (unsigned i = 0; i < 8; ++i) {
4816    bool isNonZero = (NonZeros & (1 << i)) != 0;
4817    if (isNonZero) {
4818      if (First) {
4819        if (NumZero)
4820          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4821        else
4822          V = DAG.getUNDEF(MVT::v8i16);
4823        First = false;
4824      }
4825      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4826                      MVT::v8i16, V, Op.getOperand(i),
4827                      DAG.getIntPtrConstant(i));
4828    }
4829  }
4830
4831  return V;
4832}
4833
4834/// getVShift - Return a vector logical shift node.
4835///
4836static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4837                         unsigned NumBits, SelectionDAG &DAG,
4838                         const TargetLowering &TLI, DebugLoc dl) {
4839  assert(VT.is128BitVector() && "Unknown type for VShift");
4840  EVT ShVT = MVT::v2i64;
4841  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4842  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4843  return DAG.getNode(ISD::BITCAST, dl, VT,
4844                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4845                             DAG.getConstant(NumBits,
4846                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4847}
4848
4849SDValue
4850X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4851                                          SelectionDAG &DAG) const {
4852
4853  // Check if the scalar load can be widened into a vector load. And if
4854  // the address is "base + cst" see if the cst can be "absorbed" into
4855  // the shuffle mask.
4856  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4857    SDValue Ptr = LD->getBasePtr();
4858    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4859      return SDValue();
4860    EVT PVT = LD->getValueType(0);
4861    if (PVT != MVT::i32 && PVT != MVT::f32)
4862      return SDValue();
4863
4864    int FI = -1;
4865    int64_t Offset = 0;
4866    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4867      FI = FINode->getIndex();
4868      Offset = 0;
4869    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4870               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4871      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4872      Offset = Ptr.getConstantOperandVal(1);
4873      Ptr = Ptr.getOperand(0);
4874    } else {
4875      return SDValue();
4876    }
4877
4878    // FIXME: 256-bit vector instructions don't require a strict alignment,
4879    // improve this code to support it better.
4880    unsigned RequiredAlign = VT.getSizeInBits()/8;
4881    SDValue Chain = LD->getChain();
4882    // Make sure the stack object alignment is at least 16 or 32.
4883    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4884    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4885      if (MFI->isFixedObjectIndex(FI)) {
4886        // Can't change the alignment. FIXME: It's possible to compute
4887        // the exact stack offset and reference FI + adjust offset instead.
4888        // If someone *really* cares about this. That's the way to implement it.
4889        return SDValue();
4890      } else {
4891        MFI->setObjectAlignment(FI, RequiredAlign);
4892      }
4893    }
4894
4895    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4896    // Ptr + (Offset & ~15).
4897    if (Offset < 0)
4898      return SDValue();
4899    if ((Offset % RequiredAlign) & 3)
4900      return SDValue();
4901    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4902    if (StartOffset)
4903      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4904                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4905
4906    int EltNo = (Offset - StartOffset) >> 2;
4907    unsigned NumElems = VT.getVectorNumElements();
4908
4909    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4910    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4911                             LD->getPointerInfo().getWithOffset(StartOffset),
4912                             false, false, false, 0);
4913
4914    SmallVector<int, 8> Mask;
4915    for (unsigned i = 0; i != NumElems; ++i)
4916      Mask.push_back(EltNo);
4917
4918    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4919  }
4920
4921  return SDValue();
4922}
4923
4924/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4925/// vector of type 'VT', see if the elements can be replaced by a single large
4926/// load which has the same value as a build_vector whose operands are 'elts'.
4927///
4928/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4929///
4930/// FIXME: we'd also like to handle the case where the last elements are zero
4931/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4932/// There's even a handy isZeroNode for that purpose.
4933static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4934                                        DebugLoc &DL, SelectionDAG &DAG) {
4935  EVT EltVT = VT.getVectorElementType();
4936  unsigned NumElems = Elts.size();
4937
4938  LoadSDNode *LDBase = NULL;
4939  unsigned LastLoadedElt = -1U;
4940
4941  // For each element in the initializer, see if we've found a load or an undef.
4942  // If we don't find an initial load element, or later load elements are
4943  // non-consecutive, bail out.
4944  for (unsigned i = 0; i < NumElems; ++i) {
4945    SDValue Elt = Elts[i];
4946
4947    if (!Elt.getNode() ||
4948        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4949      return SDValue();
4950    if (!LDBase) {
4951      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4952        return SDValue();
4953      LDBase = cast<LoadSDNode>(Elt.getNode());
4954      LastLoadedElt = i;
4955      continue;
4956    }
4957    if (Elt.getOpcode() == ISD::UNDEF)
4958      continue;
4959
4960    LoadSDNode *LD = cast<LoadSDNode>(Elt);
4961    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4962      return SDValue();
4963    LastLoadedElt = i;
4964  }
4965
4966  // If we have found an entire vector of loads and undefs, then return a large
4967  // load of the entire vector width starting at the base pointer.  If we found
4968  // consecutive loads for the low half, generate a vzext_load node.
4969  if (LastLoadedElt == NumElems - 1) {
4970    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4971      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4972                         LDBase->getPointerInfo(),
4973                         LDBase->isVolatile(), LDBase->isNonTemporal(),
4974                         LDBase->isInvariant(), 0);
4975    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4976                       LDBase->getPointerInfo(),
4977                       LDBase->isVolatile(), LDBase->isNonTemporal(),
4978                       LDBase->isInvariant(), LDBase->getAlignment());
4979  }
4980  if (NumElems == 4 && LastLoadedElt == 1 &&
4981      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4982    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4983    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4984    SDValue ResNode =
4985        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4986                                LDBase->getPointerInfo(),
4987                                LDBase->getAlignment(),
4988                                false/*isVolatile*/, true/*ReadMem*/,
4989                                false/*WriteMem*/);
4990
4991    // Make sure the newly-created LOAD is in the same position as LDBase in
4992    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4993    // update uses of LDBase's output chain to use the TokenFactor.
4994    if (LDBase->hasAnyUseOfValue(1)) {
4995      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4996                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4997      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4998      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4999                             SDValue(ResNode.getNode(), 1));
5000    }
5001
5002    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5003  }
5004  return SDValue();
5005}
5006
5007/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5008/// to generate a splat value for the following cases:
5009/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5010/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5011/// a scalar load, or a constant.
5012/// The VBROADCAST node is returned when a pattern is found,
5013/// or SDValue() otherwise.
5014SDValue
5015X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5016  if (!Subtarget->hasAVX())
5017    return SDValue();
5018
5019  EVT VT = Op.getValueType();
5020  DebugLoc dl = Op.getDebugLoc();
5021
5022  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5023         "Unsupported vector type for broadcast.");
5024
5025  SDValue Ld;
5026  bool ConstSplatVal;
5027
5028  switch (Op.getOpcode()) {
5029    default:
5030      // Unknown pattern found.
5031      return SDValue();
5032
5033    case ISD::BUILD_VECTOR: {
5034      // The BUILD_VECTOR node must be a splat.
5035      if (!isSplatVector(Op.getNode()))
5036        return SDValue();
5037
5038      Ld = Op.getOperand(0);
5039      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5040                     Ld.getOpcode() == ISD::ConstantFP);
5041
5042      // The suspected load node has several users. Make sure that all
5043      // of its users are from the BUILD_VECTOR node.
5044      // Constants may have multiple users.
5045      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5046        return SDValue();
5047      break;
5048    }
5049
5050    case ISD::VECTOR_SHUFFLE: {
5051      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5052
5053      // Shuffles must have a splat mask where the first element is
5054      // broadcasted.
5055      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5056        return SDValue();
5057
5058      SDValue Sc = Op.getOperand(0);
5059      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5060          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5061
5062        if (!Subtarget->hasAVX2())
5063          return SDValue();
5064
5065        // Use the register form of the broadcast instruction available on AVX2.
5066        if (VT.is256BitVector())
5067          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5068        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5069      }
5070
5071      Ld = Sc.getOperand(0);
5072      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5073                       Ld.getOpcode() == ISD::ConstantFP);
5074
5075      // The scalar_to_vector node and the suspected
5076      // load node must have exactly one user.
5077      // Constants may have multiple users.
5078      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5079        return SDValue();
5080      break;
5081    }
5082  }
5083
5084  bool Is256 = VT.is256BitVector();
5085
5086  // Handle the broadcasting a single constant scalar from the constant pool
5087  // into a vector. On Sandybridge it is still better to load a constant vector
5088  // from the constant pool and not to broadcast it from a scalar.
5089  if (ConstSplatVal && Subtarget->hasAVX2()) {
5090    EVT CVT = Ld.getValueType();
5091    assert(!CVT.isVector() && "Must not broadcast a vector type");
5092    unsigned ScalarSize = CVT.getSizeInBits();
5093
5094    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5095      const Constant *C = 0;
5096      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5097        C = CI->getConstantIntValue();
5098      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5099        C = CF->getConstantFPValue();
5100
5101      assert(C && "Invalid constant type");
5102
5103      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5104      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5105      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5106                       MachinePointerInfo::getConstantPool(),
5107                       false, false, false, Alignment);
5108
5109      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110    }
5111  }
5112
5113  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5114  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5115
5116  // Handle AVX2 in-register broadcasts.
5117  if (!IsLoad && Subtarget->hasAVX2() &&
5118      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5119    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5120
5121  // The scalar source must be a normal load.
5122  if (!IsLoad)
5123    return SDValue();
5124
5125  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5126    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5127
5128  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5129  // double since there is no vbroadcastsd xmm
5130  if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5131    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5132      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5133  }
5134
5135  // Unsupported broadcast.
5136  return SDValue();
5137}
5138
5139// LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5140// and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5141// constraint of matching input/output vector elements.
5142SDValue
5143X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5144  DebugLoc DL = Op.getDebugLoc();
5145  SDNode *N = Op.getNode();
5146  EVT VT = Op.getValueType();
5147  unsigned NumElts = Op.getNumOperands();
5148
5149  // Check supported types and sub-targets.
5150  //
5151  // Only v2f32 -> v2f64 needs special handling.
5152  if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5153    return SDValue();
5154
5155  SDValue VecIn;
5156  EVT VecInVT;
5157  SmallVector<int, 8> Mask;
5158  EVT SrcVT = MVT::Other;
5159
5160  // Check the patterns could be translated into X86vfpext.
5161  for (unsigned i = 0; i < NumElts; ++i) {
5162    SDValue In = N->getOperand(i);
5163    unsigned Opcode = In.getOpcode();
5164
5165    // Skip if the element is undefined.
5166    if (Opcode == ISD::UNDEF) {
5167      Mask.push_back(-1);
5168      continue;
5169    }
5170
5171    // Quit if one of the elements is not defined from 'fpext'.
5172    if (Opcode != ISD::FP_EXTEND)
5173      return SDValue();
5174
5175    // Check how the source of 'fpext' is defined.
5176    SDValue L2In = In.getOperand(0);
5177    EVT L2InVT = L2In.getValueType();
5178
5179    // Check the original type
5180    if (SrcVT == MVT::Other)
5181      SrcVT = L2InVT;
5182    else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5183      return SDValue();
5184
5185    // Check whether the value being 'fpext'ed is extracted from the same
5186    // source.
5187    Opcode = L2In.getOpcode();
5188
5189    // Quit if it's not extracted with a constant index.
5190    if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5191        !isa<ConstantSDNode>(L2In.getOperand(1)))
5192      return SDValue();
5193
5194    SDValue ExtractedFromVec = L2In.getOperand(0);
5195
5196    if (VecIn.getNode() == 0) {
5197      VecIn = ExtractedFromVec;
5198      VecInVT = ExtractedFromVec.getValueType();
5199    } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5200      return SDValue();
5201
5202    Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5203  }
5204
5205  // Quit if all operands of BUILD_VECTOR are undefined.
5206  if (!VecIn.getNode())
5207    return SDValue();
5208
5209  // Fill the remaining mask as undef.
5210  for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5211    Mask.push_back(-1);
5212
5213  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5214                     DAG.getVectorShuffle(VecInVT, DL,
5215                                          VecIn, DAG.getUNDEF(VecInVT),
5216                                          &Mask[0]));
5217}
5218
5219SDValue
5220X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5221  DebugLoc dl = Op.getDebugLoc();
5222
5223  EVT VT = Op.getValueType();
5224  EVT ExtVT = VT.getVectorElementType();
5225  unsigned NumElems = Op.getNumOperands();
5226
5227  // Vectors containing all zeros can be matched by pxor and xorps later
5228  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5229    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5230    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5231    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5232      return Op;
5233
5234    return getZeroVector(VT, Subtarget, DAG, dl);
5235  }
5236
5237  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5238  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5239  // vpcmpeqd on 256-bit vectors.
5240  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5241    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5242      return Op;
5243
5244    return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5245  }
5246
5247  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5248  if (Broadcast.getNode())
5249    return Broadcast;
5250
5251  SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5252  if (FpExt.getNode())
5253    return FpExt;
5254
5255  unsigned EVTBits = ExtVT.getSizeInBits();
5256
5257  unsigned NumZero  = 0;
5258  unsigned NumNonZero = 0;
5259  unsigned NonZeros = 0;
5260  bool IsAllConstants = true;
5261  SmallSet<SDValue, 8> Values;
5262  for (unsigned i = 0; i < NumElems; ++i) {
5263    SDValue Elt = Op.getOperand(i);
5264    if (Elt.getOpcode() == ISD::UNDEF)
5265      continue;
5266    Values.insert(Elt);
5267    if (Elt.getOpcode() != ISD::Constant &&
5268        Elt.getOpcode() != ISD::ConstantFP)
5269      IsAllConstants = false;
5270    if (X86::isZeroNode(Elt))
5271      NumZero++;
5272    else {
5273      NonZeros |= (1 << i);
5274      NumNonZero++;
5275    }
5276  }
5277
5278  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5279  if (NumNonZero == 0)
5280    return DAG.getUNDEF(VT);
5281
5282  // Special case for single non-zero, non-undef, element.
5283  if (NumNonZero == 1) {
5284    unsigned Idx = CountTrailingZeros_32(NonZeros);
5285    SDValue Item = Op.getOperand(Idx);
5286
5287    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5288    // the value are obviously zero, truncate the value to i32 and do the
5289    // insertion that way.  Only do this if the value is non-constant or if the
5290    // value is a constant being inserted into element 0.  It is cheaper to do
5291    // a constant pool load than it is to do a movd + shuffle.
5292    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5293        (!IsAllConstants || Idx == 0)) {
5294      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5295        // Handle SSE only.
5296        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5297        EVT VecVT = MVT::v4i32;
5298        unsigned VecElts = 4;
5299
5300        // Truncate the value (which may itself be a constant) to i32, and
5301        // convert it to a vector with movd (S2V+shuffle to zero extend).
5302        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5303        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5304        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5305
5306        // Now we have our 32-bit value zero extended in the low element of
5307        // a vector.  If Idx != 0, swizzle it into place.
5308        if (Idx != 0) {
5309          SmallVector<int, 4> Mask;
5310          Mask.push_back(Idx);
5311          for (unsigned i = 1; i != VecElts; ++i)
5312            Mask.push_back(i);
5313          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5314                                      &Mask[0]);
5315        }
5316        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5317      }
5318    }
5319
5320    // If we have a constant or non-constant insertion into the low element of
5321    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5322    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5323    // depending on what the source datatype is.
5324    if (Idx == 0) {
5325      if (NumZero == 0)
5326        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5327
5328      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5329          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5330        if (VT.is256BitVector()) {
5331          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5332          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5333                             Item, DAG.getIntPtrConstant(0));
5334        }
5335        assert(VT.is128BitVector() && "Expected an SSE value type!");
5336        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5337        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5338        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5339      }
5340
5341      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5342        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5343        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5344        if (VT.is256BitVector()) {
5345          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5346          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5347        } else {
5348          assert(VT.is128BitVector() && "Expected an SSE value type!");
5349          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5350        }
5351        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5352      }
5353    }
5354
5355    // Is it a vector logical left shift?
5356    if (NumElems == 2 && Idx == 1 &&
5357        X86::isZeroNode(Op.getOperand(0)) &&
5358        !X86::isZeroNode(Op.getOperand(1))) {
5359      unsigned NumBits = VT.getSizeInBits();
5360      return getVShift(true, VT,
5361                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5362                                   VT, Op.getOperand(1)),
5363                       NumBits/2, DAG, *this, dl);
5364    }
5365
5366    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5367      return SDValue();
5368
5369    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5370    // is a non-constant being inserted into an element other than the low one,
5371    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5372    // movd/movss) to move this into the low element, then shuffle it into
5373    // place.
5374    if (EVTBits == 32) {
5375      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5376
5377      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5378      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5379      SmallVector<int, 8> MaskVec;
5380      for (unsigned i = 0; i != NumElems; ++i)
5381        MaskVec.push_back(i == Idx ? 0 : 1);
5382      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5383    }
5384  }
5385
5386  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5387  if (Values.size() == 1) {
5388    if (EVTBits == 32) {
5389      // Instead of a shuffle like this:
5390      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5391      // Check if it's possible to issue this instead.
5392      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5393      unsigned Idx = CountTrailingZeros_32(NonZeros);
5394      SDValue Item = Op.getOperand(Idx);
5395      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5396        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5397    }
5398    return SDValue();
5399  }
5400
5401  // A vector full of immediates; various special cases are already
5402  // handled, so this is best done with a single constant-pool load.
5403  if (IsAllConstants)
5404    return SDValue();
5405
5406  // For AVX-length vectors, build the individual 128-bit pieces and use
5407  // shuffles to put them in place.
5408  if (VT.is256BitVector()) {
5409    SmallVector<SDValue, 32> V;
5410    for (unsigned i = 0; i != NumElems; ++i)
5411      V.push_back(Op.getOperand(i));
5412
5413    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5414
5415    // Build both the lower and upper subvector.
5416    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5417    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5418                                NumElems/2);
5419
5420    // Recreate the wider vector with the lower and upper part.
5421    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5422  }
5423
5424  // Let legalizer expand 2-wide build_vectors.
5425  if (EVTBits == 64) {
5426    if (NumNonZero == 1) {
5427      // One half is zero or undef.
5428      unsigned Idx = CountTrailingZeros_32(NonZeros);
5429      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5430                                 Op.getOperand(Idx));
5431      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5432    }
5433    return SDValue();
5434  }
5435
5436  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5437  if (EVTBits == 8 && NumElems == 16) {
5438    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5439                                        Subtarget, *this);
5440    if (V.getNode()) return V;
5441  }
5442
5443  if (EVTBits == 16 && NumElems == 8) {
5444    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5445                                      Subtarget, *this);
5446    if (V.getNode()) return V;
5447  }
5448
5449  // If element VT is == 32 bits, turn it into a number of shuffles.
5450  SmallVector<SDValue, 8> V(NumElems);
5451  if (NumElems == 4 && NumZero > 0) {
5452    for (unsigned i = 0; i < 4; ++i) {
5453      bool isZero = !(NonZeros & (1 << i));
5454      if (isZero)
5455        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5456      else
5457        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5458    }
5459
5460    for (unsigned i = 0; i < 2; ++i) {
5461      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5462        default: break;
5463        case 0:
5464          V[i] = V[i*2];  // Must be a zero vector.
5465          break;
5466        case 1:
5467          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5468          break;
5469        case 2:
5470          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5471          break;
5472        case 3:
5473          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5474          break;
5475      }
5476    }
5477
5478    bool Reverse1 = (NonZeros & 0x3) == 2;
5479    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5480    int MaskVec[] = {
5481      Reverse1 ? 1 : 0,
5482      Reverse1 ? 0 : 1,
5483      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5484      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5485    };
5486    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5487  }
5488
5489  if (Values.size() > 1 && VT.is128BitVector()) {
5490    // Check for a build vector of consecutive loads.
5491    for (unsigned i = 0; i < NumElems; ++i)
5492      V[i] = Op.getOperand(i);
5493
5494    // Check for elements which are consecutive loads.
5495    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5496    if (LD.getNode())
5497      return LD;
5498
5499    // For SSE 4.1, use insertps to put the high elements into the low element.
5500    if (getSubtarget()->hasSSE41()) {
5501      SDValue Result;
5502      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5503        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5504      else
5505        Result = DAG.getUNDEF(VT);
5506
5507      for (unsigned i = 1; i < NumElems; ++i) {
5508        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5509        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5510                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5511      }
5512      return Result;
5513    }
5514
5515    // Otherwise, expand into a number of unpckl*, start by extending each of
5516    // our (non-undef) elements to the full vector width with the element in the
5517    // bottom slot of the vector (which generates no code for SSE).
5518    for (unsigned i = 0; i < NumElems; ++i) {
5519      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5520        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5521      else
5522        V[i] = DAG.getUNDEF(VT);
5523    }
5524
5525    // Next, we iteratively mix elements, e.g. for v4f32:
5526    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5527    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5528    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5529    unsigned EltStride = NumElems >> 1;
5530    while (EltStride != 0) {
5531      for (unsigned i = 0; i < EltStride; ++i) {
5532        // If V[i+EltStride] is undef and this is the first round of mixing,
5533        // then it is safe to just drop this shuffle: V[i] is already in the
5534        // right place, the one element (since it's the first round) being
5535        // inserted as undef can be dropped.  This isn't safe for successive
5536        // rounds because they will permute elements within both vectors.
5537        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5538            EltStride == NumElems/2)
5539          continue;
5540
5541        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5542      }
5543      EltStride >>= 1;
5544    }
5545    return V[0];
5546  }
5547  return SDValue();
5548}
5549
5550// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5551// to create 256-bit vectors from two other 128-bit ones.
5552static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5553  DebugLoc dl = Op.getDebugLoc();
5554  EVT ResVT = Op.getValueType();
5555
5556  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5557
5558  SDValue V1 = Op.getOperand(0);
5559  SDValue V2 = Op.getOperand(1);
5560  unsigned NumElems = ResVT.getVectorNumElements();
5561
5562  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5563}
5564
5565SDValue
5566X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5567  assert(Op.getNumOperands() == 2);
5568
5569  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5570  // from two other 128-bit ones.
5571  return LowerAVXCONCAT_VECTORS(Op, DAG);
5572}
5573
5574// Try to lower a shuffle node into a simple blend instruction.
5575static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5576                                          const X86Subtarget *Subtarget,
5577                                          SelectionDAG &DAG) {
5578  SDValue V1 = SVOp->getOperand(0);
5579  SDValue V2 = SVOp->getOperand(1);
5580  DebugLoc dl = SVOp->getDebugLoc();
5581  MVT VT = SVOp->getValueType(0).getSimpleVT();
5582  unsigned NumElems = VT.getVectorNumElements();
5583
5584  if (!Subtarget->hasSSE41())
5585    return SDValue();
5586
5587  unsigned ISDNo = 0;
5588  MVT OpTy;
5589
5590  switch (VT.SimpleTy) {
5591  default: return SDValue();
5592  case MVT::v8i16:
5593    ISDNo = X86ISD::BLENDPW;
5594    OpTy = MVT::v8i16;
5595    break;
5596  case MVT::v4i32:
5597  case MVT::v4f32:
5598    ISDNo = X86ISD::BLENDPS;
5599    OpTy = MVT::v4f32;
5600    break;
5601  case MVT::v2i64:
5602  case MVT::v2f64:
5603    ISDNo = X86ISD::BLENDPD;
5604    OpTy = MVT::v2f64;
5605    break;
5606  case MVT::v8i32:
5607  case MVT::v8f32:
5608    if (!Subtarget->hasAVX())
5609      return SDValue();
5610    ISDNo = X86ISD::BLENDPS;
5611    OpTy = MVT::v8f32;
5612    break;
5613  case MVT::v4i64:
5614  case MVT::v4f64:
5615    if (!Subtarget->hasAVX())
5616      return SDValue();
5617    ISDNo = X86ISD::BLENDPD;
5618    OpTy = MVT::v4f64;
5619    break;
5620  }
5621  assert(ISDNo && "Invalid Op Number");
5622
5623  unsigned MaskVals = 0;
5624
5625  for (unsigned i = 0; i != NumElems; ++i) {
5626    int EltIdx = SVOp->getMaskElt(i);
5627    if (EltIdx == (int)i || EltIdx < 0)
5628      MaskVals |= (1<<i);
5629    else if (EltIdx == (int)(i + NumElems))
5630      continue; // Bit is set to zero;
5631    else
5632      return SDValue();
5633  }
5634
5635  V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5636  V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5637  SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5638                             DAG.getConstant(MaskVals, MVT::i32));
5639  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5640}
5641
5642// v8i16 shuffles - Prefer shuffles in the following order:
5643// 1. [all]   pshuflw, pshufhw, optional move
5644// 2. [ssse3] 1 x pshufb
5645// 3. [ssse3] 2 x pshufb + 1 x por
5646// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5647SDValue
5648X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5649                                            SelectionDAG &DAG) const {
5650  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5651  SDValue V1 = SVOp->getOperand(0);
5652  SDValue V2 = SVOp->getOperand(1);
5653  DebugLoc dl = SVOp->getDebugLoc();
5654  SmallVector<int, 8> MaskVals;
5655
5656  // Determine if more than 1 of the words in each of the low and high quadwords
5657  // of the result come from the same quadword of one of the two inputs.  Undef
5658  // mask values count as coming from any quadword, for better codegen.
5659  unsigned LoQuad[] = { 0, 0, 0, 0 };
5660  unsigned HiQuad[] = { 0, 0, 0, 0 };
5661  std::bitset<4> InputQuads;
5662  for (unsigned i = 0; i < 8; ++i) {
5663    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5664    int EltIdx = SVOp->getMaskElt(i);
5665    MaskVals.push_back(EltIdx);
5666    if (EltIdx < 0) {
5667      ++Quad[0];
5668      ++Quad[1];
5669      ++Quad[2];
5670      ++Quad[3];
5671      continue;
5672    }
5673    ++Quad[EltIdx / 4];
5674    InputQuads.set(EltIdx / 4);
5675  }
5676
5677  int BestLoQuad = -1;
5678  unsigned MaxQuad = 1;
5679  for (unsigned i = 0; i < 4; ++i) {
5680    if (LoQuad[i] > MaxQuad) {
5681      BestLoQuad = i;
5682      MaxQuad = LoQuad[i];
5683    }
5684  }
5685
5686  int BestHiQuad = -1;
5687  MaxQuad = 1;
5688  for (unsigned i = 0; i < 4; ++i) {
5689    if (HiQuad[i] > MaxQuad) {
5690      BestHiQuad = i;
5691      MaxQuad = HiQuad[i];
5692    }
5693  }
5694
5695  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5696  // of the two input vectors, shuffle them into one input vector so only a
5697  // single pshufb instruction is necessary. If There are more than 2 input
5698  // quads, disable the next transformation since it does not help SSSE3.
5699  bool V1Used = InputQuads[0] || InputQuads[1];
5700  bool V2Used = InputQuads[2] || InputQuads[3];
5701  if (Subtarget->hasSSSE3()) {
5702    if (InputQuads.count() == 2 && V1Used && V2Used) {
5703      BestLoQuad = InputQuads[0] ? 0 : 1;
5704      BestHiQuad = InputQuads[2] ? 2 : 3;
5705    }
5706    if (InputQuads.count() > 2) {
5707      BestLoQuad = -1;
5708      BestHiQuad = -1;
5709    }
5710  }
5711
5712  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5713  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5714  // words from all 4 input quadwords.
5715  SDValue NewV;
5716  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5717    int MaskV[] = {
5718      BestLoQuad < 0 ? 0 : BestLoQuad,
5719      BestHiQuad < 0 ? 1 : BestHiQuad
5720    };
5721    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5722                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5723                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5724    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5725
5726    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5727    // source words for the shuffle, to aid later transformations.
5728    bool AllWordsInNewV = true;
5729    bool InOrder[2] = { true, true };
5730    for (unsigned i = 0; i != 8; ++i) {
5731      int idx = MaskVals[i];
5732      if (idx != (int)i)
5733        InOrder[i/4] = false;
5734      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5735        continue;
5736      AllWordsInNewV = false;
5737      break;
5738    }
5739
5740    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5741    if (AllWordsInNewV) {
5742      for (int i = 0; i != 8; ++i) {
5743        int idx = MaskVals[i];
5744        if (idx < 0)
5745          continue;
5746        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5747        if ((idx != i) && idx < 4)
5748          pshufhw = false;
5749        if ((idx != i) && idx > 3)
5750          pshuflw = false;
5751      }
5752      V1 = NewV;
5753      V2Used = false;
5754      BestLoQuad = 0;
5755      BestHiQuad = 1;
5756    }
5757
5758    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5759    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5760    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5761      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5762      unsigned TargetMask = 0;
5763      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5764                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5765      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5766      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5767                             getShufflePSHUFLWImmediate(SVOp);
5768      V1 = NewV.getOperand(0);
5769      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5770    }
5771  }
5772
5773  // If we have SSSE3, and all words of the result are from 1 input vector,
5774  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5775  // is present, fall back to case 4.
5776  if (Subtarget->hasSSSE3()) {
5777    SmallVector<SDValue,16> pshufbMask;
5778
5779    // If we have elements from both input vectors, set the high bit of the
5780    // shuffle mask element to zero out elements that come from V2 in the V1
5781    // mask, and elements that come from V1 in the V2 mask, so that the two
5782    // results can be OR'd together.
5783    bool TwoInputs = V1Used && V2Used;
5784    for (unsigned i = 0; i != 8; ++i) {
5785      int EltIdx = MaskVals[i] * 2;
5786      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5787      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5788      pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5789      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5790    }
5791    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5792    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5793                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5794                                 MVT::v16i8, &pshufbMask[0], 16));
5795    if (!TwoInputs)
5796      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5797
5798    // Calculate the shuffle mask for the second input, shuffle it, and
5799    // OR it with the first shuffled input.
5800    pshufbMask.clear();
5801    for (unsigned i = 0; i != 8; ++i) {
5802      int EltIdx = MaskVals[i] * 2;
5803      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5804      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5805      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5806      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5807    }
5808    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5809    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5810                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5811                                 MVT::v16i8, &pshufbMask[0], 16));
5812    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5813    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5814  }
5815
5816  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5817  // and update MaskVals with new element order.
5818  std::bitset<8> InOrder;
5819  if (BestLoQuad >= 0) {
5820    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5821    for (int i = 0; i != 4; ++i) {
5822      int idx = MaskVals[i];
5823      if (idx < 0) {
5824        InOrder.set(i);
5825      } else if ((idx / 4) == BestLoQuad) {
5826        MaskV[i] = idx & 3;
5827        InOrder.set(i);
5828      }
5829    }
5830    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5831                                &MaskV[0]);
5832
5833    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5834      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5835      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5836                                  NewV.getOperand(0),
5837                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5838    }
5839  }
5840
5841  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5842  // and update MaskVals with the new element order.
5843  if (BestHiQuad >= 0) {
5844    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5845    for (unsigned i = 4; i != 8; ++i) {
5846      int idx = MaskVals[i];
5847      if (idx < 0) {
5848        InOrder.set(i);
5849      } else if ((idx / 4) == BestHiQuad) {
5850        MaskV[i] = (idx & 3) + 4;
5851        InOrder.set(i);
5852      }
5853    }
5854    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5855                                &MaskV[0]);
5856
5857    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5858      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5859      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5860                                  NewV.getOperand(0),
5861                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5862    }
5863  }
5864
5865  // In case BestHi & BestLo were both -1, which means each quadword has a word
5866  // from each of the four input quadwords, calculate the InOrder bitvector now
5867  // before falling through to the insert/extract cleanup.
5868  if (BestLoQuad == -1 && BestHiQuad == -1) {
5869    NewV = V1;
5870    for (int i = 0; i != 8; ++i)
5871      if (MaskVals[i] < 0 || MaskVals[i] == i)
5872        InOrder.set(i);
5873  }
5874
5875  // The other elements are put in the right place using pextrw and pinsrw.
5876  for (unsigned i = 0; i != 8; ++i) {
5877    if (InOrder[i])
5878      continue;
5879    int EltIdx = MaskVals[i];
5880    if (EltIdx < 0)
5881      continue;
5882    SDValue ExtOp = (EltIdx < 8) ?
5883      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5884                  DAG.getIntPtrConstant(EltIdx)) :
5885      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5886                  DAG.getIntPtrConstant(EltIdx - 8));
5887    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5888                       DAG.getIntPtrConstant(i));
5889  }
5890  return NewV;
5891}
5892
5893// v16i8 shuffles - Prefer shuffles in the following order:
5894// 1. [ssse3] 1 x pshufb
5895// 2. [ssse3] 2 x pshufb + 1 x por
5896// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5897static
5898SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5899                                 SelectionDAG &DAG,
5900                                 const X86TargetLowering &TLI) {
5901  SDValue V1 = SVOp->getOperand(0);
5902  SDValue V2 = SVOp->getOperand(1);
5903  DebugLoc dl = SVOp->getDebugLoc();
5904  ArrayRef<int> MaskVals = SVOp->getMask();
5905
5906  // If we have SSSE3, case 1 is generated when all result bytes come from
5907  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5908  // present, fall back to case 3.
5909
5910  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5911  if (TLI.getSubtarget()->hasSSSE3()) {
5912    SmallVector<SDValue,16> pshufbMask;
5913
5914    // If all result elements are from one input vector, then only translate
5915    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5916    //
5917    // Otherwise, we have elements from both input vectors, and must zero out
5918    // elements that come from V2 in the first mask, and V1 in the second mask
5919    // so that we can OR them together.
5920    for (unsigned i = 0; i != 16; ++i) {
5921      int EltIdx = MaskVals[i];
5922      if (EltIdx < 0 || EltIdx >= 16)
5923        EltIdx = 0x80;
5924      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5925    }
5926    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5927                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5928                                 MVT::v16i8, &pshufbMask[0], 16));
5929
5930    // As PSHUFB will zero elements with negative indices, it's safe to ignore
5931    // the 2nd operand if it's undefined or zero.
5932    if (V2.getOpcode() == ISD::UNDEF ||
5933        ISD::isBuildVectorAllZeros(V2.getNode()))
5934      return V1;
5935
5936    // Calculate the shuffle mask for the second input, shuffle it, and
5937    // OR it with the first shuffled input.
5938    pshufbMask.clear();
5939    for (unsigned i = 0; i != 16; ++i) {
5940      int EltIdx = MaskVals[i];
5941      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5942      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5943    }
5944    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5945                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5946                                 MVT::v16i8, &pshufbMask[0], 16));
5947    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5948  }
5949
5950  // No SSSE3 - Calculate in place words and then fix all out of place words
5951  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5952  // the 16 different words that comprise the two doublequadword input vectors.
5953  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5954  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5955  SDValue NewV = V1;
5956  for (int i = 0; i != 8; ++i) {
5957    int Elt0 = MaskVals[i*2];
5958    int Elt1 = MaskVals[i*2+1];
5959
5960    // This word of the result is all undef, skip it.
5961    if (Elt0 < 0 && Elt1 < 0)
5962      continue;
5963
5964    // This word of the result is already in the correct place, skip it.
5965    if ((Elt0 == i*2) && (Elt1 == i*2+1))
5966      continue;
5967
5968    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5969    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5970    SDValue InsElt;
5971
5972    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5973    // using a single extract together, load it and store it.
5974    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5975      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5976                           DAG.getIntPtrConstant(Elt1 / 2));
5977      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5978                        DAG.getIntPtrConstant(i));
5979      continue;
5980    }
5981
5982    // If Elt1 is defined, extract it from the appropriate source.  If the
5983    // source byte is not also odd, shift the extracted word left 8 bits
5984    // otherwise clear the bottom 8 bits if we need to do an or.
5985    if (Elt1 >= 0) {
5986      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5987                           DAG.getIntPtrConstant(Elt1 / 2));
5988      if ((Elt1 & 1) == 0)
5989        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5990                             DAG.getConstant(8,
5991                                  TLI.getShiftAmountTy(InsElt.getValueType())));
5992      else if (Elt0 >= 0)
5993        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5994                             DAG.getConstant(0xFF00, MVT::i16));
5995    }
5996    // If Elt0 is defined, extract it from the appropriate source.  If the
5997    // source byte is not also even, shift the extracted word right 8 bits. If
5998    // Elt1 was also defined, OR the extracted values together before
5999    // inserting them in the result.
6000    if (Elt0 >= 0) {
6001      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6002                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6003      if ((Elt0 & 1) != 0)
6004        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6005                              DAG.getConstant(8,
6006                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6007      else if (Elt1 >= 0)
6008        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6009                             DAG.getConstant(0x00FF, MVT::i16));
6010      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6011                         : InsElt0;
6012    }
6013    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6014                       DAG.getIntPtrConstant(i));
6015  }
6016  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6017}
6018
6019// v32i8 shuffles - Translate to VPSHUFB if possible.
6020static
6021SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6022                                 SelectionDAG &DAG,
6023                                 const X86TargetLowering &TLI) {
6024  EVT VT = SVOp->getValueType(0);
6025  SDValue V1 = SVOp->getOperand(0);
6026  SDValue V2 = SVOp->getOperand(1);
6027  DebugLoc dl = SVOp->getDebugLoc();
6028  ArrayRef<int> MaskVals = SVOp->getMask();
6029
6030  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6031
6032  if (VT != MVT::v32i8 || !TLI.getSubtarget()->hasAVX2() || !V2IsUndef)
6033    return SDValue();
6034
6035  SmallVector<SDValue,32> pshufbMask;
6036  for (unsigned i = 0; i != 32; i++) {
6037    int EltIdx = MaskVals[i];
6038    if (EltIdx < 0 || EltIdx >= 32)
6039      EltIdx = 0x80;
6040    else {
6041      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6042        // Cross lane is not allowed.
6043        return SDValue();
6044      EltIdx &= 0xf;
6045    }
6046    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6047  }
6048  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6049                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6050                                  MVT::v32i8, &pshufbMask[0], 32));
6051}
6052
6053/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6054/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6055/// done when every pair / quad of shuffle mask elements point to elements in
6056/// the right sequence. e.g.
6057/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6058static
6059SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6060                                 SelectionDAG &DAG, DebugLoc dl) {
6061  MVT VT = SVOp->getValueType(0).getSimpleVT();
6062  unsigned NumElems = VT.getVectorNumElements();
6063  MVT NewVT;
6064  unsigned Scale;
6065  switch (VT.SimpleTy) {
6066  default: llvm_unreachable("Unexpected!");
6067  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6068  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6069  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6070  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6071  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6072  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6073  }
6074
6075  SmallVector<int, 8> MaskVec;
6076  for (unsigned i = 0; i != NumElems; i += Scale) {
6077    int StartIdx = -1;
6078    for (unsigned j = 0; j != Scale; ++j) {
6079      int EltIdx = SVOp->getMaskElt(i+j);
6080      if (EltIdx < 0)
6081        continue;
6082      if (StartIdx < 0)
6083        StartIdx = (EltIdx / Scale);
6084      if (EltIdx != (int)(StartIdx*Scale + j))
6085        return SDValue();
6086    }
6087    MaskVec.push_back(StartIdx);
6088  }
6089
6090  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6091  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6092  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6093}
6094
6095/// getVZextMovL - Return a zero-extending vector move low node.
6096///
6097static SDValue getVZextMovL(EVT VT, EVT OpVT,
6098                            SDValue SrcOp, SelectionDAG &DAG,
6099                            const X86Subtarget *Subtarget, DebugLoc dl) {
6100  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6101    LoadSDNode *LD = NULL;
6102    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6103      LD = dyn_cast<LoadSDNode>(SrcOp);
6104    if (!LD) {
6105      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6106      // instead.
6107      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6108      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6109          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6110          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6111          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6112        // PR2108
6113        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6114        return DAG.getNode(ISD::BITCAST, dl, VT,
6115                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6116                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6117                                                   OpVT,
6118                                                   SrcOp.getOperand(0)
6119                                                          .getOperand(0))));
6120      }
6121    }
6122  }
6123
6124  return DAG.getNode(ISD::BITCAST, dl, VT,
6125                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6126                                 DAG.getNode(ISD::BITCAST, dl,
6127                                             OpVT, SrcOp)));
6128}
6129
6130/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6131/// which could not be matched by any known target speficic shuffle
6132static SDValue
6133LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6134
6135  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6136  if (NewOp.getNode())
6137    return NewOp;
6138
6139  EVT VT = SVOp->getValueType(0);
6140
6141  unsigned NumElems = VT.getVectorNumElements();
6142  unsigned NumLaneElems = NumElems / 2;
6143
6144  DebugLoc dl = SVOp->getDebugLoc();
6145  MVT EltVT = VT.getVectorElementType().getSimpleVT();
6146  EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6147  SDValue Output[2];
6148
6149  SmallVector<int, 16> Mask;
6150  for (unsigned l = 0; l < 2; ++l) {
6151    // Build a shuffle mask for the output, discovering on the fly which
6152    // input vectors to use as shuffle operands (recorded in InputUsed).
6153    // If building a suitable shuffle vector proves too hard, then bail
6154    // out with UseBuildVector set.
6155    bool UseBuildVector = false;
6156    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6157    unsigned LaneStart = l * NumLaneElems;
6158    for (unsigned i = 0; i != NumLaneElems; ++i) {
6159      // The mask element.  This indexes into the input.
6160      int Idx = SVOp->getMaskElt(i+LaneStart);
6161      if (Idx < 0) {
6162        // the mask element does not index into any input vector.
6163        Mask.push_back(-1);
6164        continue;
6165      }
6166
6167      // The input vector this mask element indexes into.
6168      int Input = Idx / NumLaneElems;
6169
6170      // Turn the index into an offset from the start of the input vector.
6171      Idx -= Input * NumLaneElems;
6172
6173      // Find or create a shuffle vector operand to hold this input.
6174      unsigned OpNo;
6175      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6176        if (InputUsed[OpNo] == Input)
6177          // This input vector is already an operand.
6178          break;
6179        if (InputUsed[OpNo] < 0) {
6180          // Create a new operand for this input vector.
6181          InputUsed[OpNo] = Input;
6182          break;
6183        }
6184      }
6185
6186      if (OpNo >= array_lengthof(InputUsed)) {
6187        // More than two input vectors used!  Give up on trying to create a
6188        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6189        UseBuildVector = true;
6190        break;
6191      }
6192
6193      // Add the mask index for the new shuffle vector.
6194      Mask.push_back(Idx + OpNo * NumLaneElems);
6195    }
6196
6197    if (UseBuildVector) {
6198      SmallVector<SDValue, 16> SVOps;
6199      for (unsigned i = 0; i != NumLaneElems; ++i) {
6200        // The mask element.  This indexes into the input.
6201        int Idx = SVOp->getMaskElt(i+LaneStart);
6202        if (Idx < 0) {
6203          SVOps.push_back(DAG.getUNDEF(EltVT));
6204          continue;
6205        }
6206
6207        // The input vector this mask element indexes into.
6208        int Input = Idx / NumElems;
6209
6210        // Turn the index into an offset from the start of the input vector.
6211        Idx -= Input * NumElems;
6212
6213        // Extract the vector element by hand.
6214        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6215                                    SVOp->getOperand(Input),
6216                                    DAG.getIntPtrConstant(Idx)));
6217      }
6218
6219      // Construct the output using a BUILD_VECTOR.
6220      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6221                              SVOps.size());
6222    } else if (InputUsed[0] < 0) {
6223      // No input vectors were used! The result is undefined.
6224      Output[l] = DAG.getUNDEF(NVT);
6225    } else {
6226      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6227                                        (InputUsed[0] % 2) * NumLaneElems,
6228                                        DAG, dl);
6229      // If only one input was used, use an undefined vector for the other.
6230      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6231        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6232                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6233      // At least one input vector was used. Create a new shuffle vector.
6234      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6235    }
6236
6237    Mask.clear();
6238  }
6239
6240  // Concatenate the result back
6241  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6242}
6243
6244/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6245/// 4 elements, and match them with several different shuffle types.
6246static SDValue
6247LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6248  SDValue V1 = SVOp->getOperand(0);
6249  SDValue V2 = SVOp->getOperand(1);
6250  DebugLoc dl = SVOp->getDebugLoc();
6251  EVT VT = SVOp->getValueType(0);
6252
6253  assert(VT.is128BitVector() && "Unsupported vector size");
6254
6255  std::pair<int, int> Locs[4];
6256  int Mask1[] = { -1, -1, -1, -1 };
6257  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6258
6259  unsigned NumHi = 0;
6260  unsigned NumLo = 0;
6261  for (unsigned i = 0; i != 4; ++i) {
6262    int Idx = PermMask[i];
6263    if (Idx < 0) {
6264      Locs[i] = std::make_pair(-1, -1);
6265    } else {
6266      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6267      if (Idx < 4) {
6268        Locs[i] = std::make_pair(0, NumLo);
6269        Mask1[NumLo] = Idx;
6270        NumLo++;
6271      } else {
6272        Locs[i] = std::make_pair(1, NumHi);
6273        if (2+NumHi < 4)
6274          Mask1[2+NumHi] = Idx;
6275        NumHi++;
6276      }
6277    }
6278  }
6279
6280  if (NumLo <= 2 && NumHi <= 2) {
6281    // If no more than two elements come from either vector. This can be
6282    // implemented with two shuffles. First shuffle gather the elements.
6283    // The second shuffle, which takes the first shuffle as both of its
6284    // vector operands, put the elements into the right order.
6285    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6286
6287    int Mask2[] = { -1, -1, -1, -1 };
6288
6289    for (unsigned i = 0; i != 4; ++i)
6290      if (Locs[i].first != -1) {
6291        unsigned Idx = (i < 2) ? 0 : 4;
6292        Idx += Locs[i].first * 2 + Locs[i].second;
6293        Mask2[i] = Idx;
6294      }
6295
6296    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6297  }
6298
6299  if (NumLo == 3 || NumHi == 3) {
6300    // Otherwise, we must have three elements from one vector, call it X, and
6301    // one element from the other, call it Y.  First, use a shufps to build an
6302    // intermediate vector with the one element from Y and the element from X
6303    // that will be in the same half in the final destination (the indexes don't
6304    // matter). Then, use a shufps to build the final vector, taking the half
6305    // containing the element from Y from the intermediate, and the other half
6306    // from X.
6307    if (NumHi == 3) {
6308      // Normalize it so the 3 elements come from V1.
6309      CommuteVectorShuffleMask(PermMask, 4);
6310      std::swap(V1, V2);
6311    }
6312
6313    // Find the element from V2.
6314    unsigned HiIndex;
6315    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6316      int Val = PermMask[HiIndex];
6317      if (Val < 0)
6318        continue;
6319      if (Val >= 4)
6320        break;
6321    }
6322
6323    Mask1[0] = PermMask[HiIndex];
6324    Mask1[1] = -1;
6325    Mask1[2] = PermMask[HiIndex^1];
6326    Mask1[3] = -1;
6327    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6328
6329    if (HiIndex >= 2) {
6330      Mask1[0] = PermMask[0];
6331      Mask1[1] = PermMask[1];
6332      Mask1[2] = HiIndex & 1 ? 6 : 4;
6333      Mask1[3] = HiIndex & 1 ? 4 : 6;
6334      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6335    }
6336
6337    Mask1[0] = HiIndex & 1 ? 2 : 0;
6338    Mask1[1] = HiIndex & 1 ? 0 : 2;
6339    Mask1[2] = PermMask[2];
6340    Mask1[3] = PermMask[3];
6341    if (Mask1[2] >= 0)
6342      Mask1[2] += 4;
6343    if (Mask1[3] >= 0)
6344      Mask1[3] += 4;
6345    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6346  }
6347
6348  // Break it into (shuffle shuffle_hi, shuffle_lo).
6349  int LoMask[] = { -1, -1, -1, -1 };
6350  int HiMask[] = { -1, -1, -1, -1 };
6351
6352  int *MaskPtr = LoMask;
6353  unsigned MaskIdx = 0;
6354  unsigned LoIdx = 0;
6355  unsigned HiIdx = 2;
6356  for (unsigned i = 0; i != 4; ++i) {
6357    if (i == 2) {
6358      MaskPtr = HiMask;
6359      MaskIdx = 1;
6360      LoIdx = 0;
6361      HiIdx = 2;
6362    }
6363    int Idx = PermMask[i];
6364    if (Idx < 0) {
6365      Locs[i] = std::make_pair(-1, -1);
6366    } else if (Idx < 4) {
6367      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6368      MaskPtr[LoIdx] = Idx;
6369      LoIdx++;
6370    } else {
6371      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6372      MaskPtr[HiIdx] = Idx;
6373      HiIdx++;
6374    }
6375  }
6376
6377  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6378  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6379  int MaskOps[] = { -1, -1, -1, -1 };
6380  for (unsigned i = 0; i != 4; ++i)
6381    if (Locs[i].first != -1)
6382      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6383  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6384}
6385
6386static bool MayFoldVectorLoad(SDValue V) {
6387  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6388    V = V.getOperand(0);
6389  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6390    V = V.getOperand(0);
6391  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6392      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6393    // BUILD_VECTOR (load), undef
6394    V = V.getOperand(0);
6395  if (MayFoldLoad(V))
6396    return true;
6397  return false;
6398}
6399
6400// FIXME: the version above should always be used. Since there's
6401// a bug where several vector shuffles can't be folded because the
6402// DAG is not updated during lowering and a node claims to have two
6403// uses while it only has one, use this version, and let isel match
6404// another instruction if the load really happens to have more than
6405// one use. Remove this version after this bug get fixed.
6406// rdar://8434668, PR8156
6407static bool RelaxedMayFoldVectorLoad(SDValue V) {
6408  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6409    V = V.getOperand(0);
6410  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6411    V = V.getOperand(0);
6412  if (ISD::isNormalLoad(V.getNode()))
6413    return true;
6414  return false;
6415}
6416
6417static
6418SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6419  EVT VT = Op.getValueType();
6420
6421  // Canonizalize to v2f64.
6422  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6423  return DAG.getNode(ISD::BITCAST, dl, VT,
6424                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6425                                          V1, DAG));
6426}
6427
6428static
6429SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6430                        bool HasSSE2) {
6431  SDValue V1 = Op.getOperand(0);
6432  SDValue V2 = Op.getOperand(1);
6433  EVT VT = Op.getValueType();
6434
6435  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6436
6437  if (HasSSE2 && VT == MVT::v2f64)
6438    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6439
6440  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6441  return DAG.getNode(ISD::BITCAST, dl, VT,
6442                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6443                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6444                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6445}
6446
6447static
6448SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6449  SDValue V1 = Op.getOperand(0);
6450  SDValue V2 = Op.getOperand(1);
6451  EVT VT = Op.getValueType();
6452
6453  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6454         "unsupported shuffle type");
6455
6456  if (V2.getOpcode() == ISD::UNDEF)
6457    V2 = V1;
6458
6459  // v4i32 or v4f32
6460  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6461}
6462
6463static
6464SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6465  SDValue V1 = Op.getOperand(0);
6466  SDValue V2 = Op.getOperand(1);
6467  EVT VT = Op.getValueType();
6468  unsigned NumElems = VT.getVectorNumElements();
6469
6470  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6471  // operand of these instructions is only memory, so check if there's a
6472  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6473  // same masks.
6474  bool CanFoldLoad = false;
6475
6476  // Trivial case, when V2 comes from a load.
6477  if (MayFoldVectorLoad(V2))
6478    CanFoldLoad = true;
6479
6480  // When V1 is a load, it can be folded later into a store in isel, example:
6481  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6482  //    turns into:
6483  //  (MOVLPSmr addr:$src1, VR128:$src2)
6484  // So, recognize this potential and also use MOVLPS or MOVLPD
6485  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6486    CanFoldLoad = true;
6487
6488  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6489  if (CanFoldLoad) {
6490    if (HasSSE2 && NumElems == 2)
6491      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6492
6493    if (NumElems == 4)
6494      // If we don't care about the second element, proceed to use movss.
6495      if (SVOp->getMaskElt(1) != -1)
6496        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6497  }
6498
6499  // movl and movlp will both match v2i64, but v2i64 is never matched by
6500  // movl earlier because we make it strict to avoid messing with the movlp load
6501  // folding logic (see the code above getMOVLP call). Match it here then,
6502  // this is horrible, but will stay like this until we move all shuffle
6503  // matching to x86 specific nodes. Note that for the 1st condition all
6504  // types are matched with movsd.
6505  if (HasSSE2) {
6506    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6507    // as to remove this logic from here, as much as possible
6508    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6509      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6510    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6511  }
6512
6513  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6514
6515  // Invert the operand order and use SHUFPS to match it.
6516  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6517                              getShuffleSHUFImmediate(SVOp), DAG);
6518}
6519
6520SDValue
6521X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6522  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6523  EVT VT = Op.getValueType();
6524  DebugLoc dl = Op.getDebugLoc();
6525  SDValue V1 = Op.getOperand(0);
6526  SDValue V2 = Op.getOperand(1);
6527
6528  if (isZeroShuffle(SVOp))
6529    return getZeroVector(VT, Subtarget, DAG, dl);
6530
6531  // Handle splat operations
6532  if (SVOp->isSplat()) {
6533    unsigned NumElem = VT.getVectorNumElements();
6534    int Size = VT.getSizeInBits();
6535
6536    // Use vbroadcast whenever the splat comes from a foldable load
6537    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6538    if (Broadcast.getNode())
6539      return Broadcast;
6540
6541    // Handle splats by matching through known shuffle masks
6542    if ((Size == 128 && NumElem <= 4) ||
6543        (Size == 256 && NumElem < 8))
6544      return SDValue();
6545
6546    // All remaning splats are promoted to target supported vector shuffles.
6547    return PromoteSplat(SVOp, DAG);
6548  }
6549
6550  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6551  // do it!
6552  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6553      VT == MVT::v16i16 || VT == MVT::v32i8) {
6554    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6555    if (NewOp.getNode())
6556      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6557  } else if ((VT == MVT::v4i32 ||
6558             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6559    // FIXME: Figure out a cleaner way to do this.
6560    // Try to make use of movq to zero out the top part.
6561    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6562      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6563      if (NewOp.getNode()) {
6564        EVT NewVT = NewOp.getValueType();
6565        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6566                               NewVT, true, false))
6567          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6568                              DAG, Subtarget, dl);
6569      }
6570    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6571      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6572      if (NewOp.getNode()) {
6573        EVT NewVT = NewOp.getValueType();
6574        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6575          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6576                              DAG, Subtarget, dl);
6577      }
6578    }
6579  }
6580  return SDValue();
6581}
6582
6583SDValue
6584X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6585  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6586  SDValue V1 = Op.getOperand(0);
6587  SDValue V2 = Op.getOperand(1);
6588  EVT VT = Op.getValueType();
6589  DebugLoc dl = Op.getDebugLoc();
6590  unsigned NumElems = VT.getVectorNumElements();
6591  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6592  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6593  bool V1IsSplat = false;
6594  bool V2IsSplat = false;
6595  bool HasSSE2 = Subtarget->hasSSE2();
6596  bool HasAVX    = Subtarget->hasAVX();
6597  bool HasAVX2   = Subtarget->hasAVX2();
6598  MachineFunction &MF = DAG.getMachineFunction();
6599  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6600
6601  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6602
6603  if (V1IsUndef && V2IsUndef)
6604    return DAG.getUNDEF(VT);
6605
6606  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6607
6608  // Vector shuffle lowering takes 3 steps:
6609  //
6610  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6611  //    narrowing and commutation of operands should be handled.
6612  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6613  //    shuffle nodes.
6614  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6615  //    so the shuffle can be broken into other shuffles and the legalizer can
6616  //    try the lowering again.
6617  //
6618  // The general idea is that no vector_shuffle operation should be left to
6619  // be matched during isel, all of them must be converted to a target specific
6620  // node here.
6621
6622  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6623  // narrowing and commutation of operands should be handled. The actual code
6624  // doesn't include all of those, work in progress...
6625  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6626  if (NewOp.getNode())
6627    return NewOp;
6628
6629  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6630
6631  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6632  // unpckh_undef). Only use pshufd if speed is more important than size.
6633  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6634    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6635  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6636    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6637
6638  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6639      V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6640    return getMOVDDup(Op, dl, V1, DAG);
6641
6642  if (isMOVHLPS_v_undef_Mask(M, VT))
6643    return getMOVHighToLow(Op, dl, DAG);
6644
6645  // Use to match splats
6646  if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6647      (VT == MVT::v2f64 || VT == MVT::v2i64))
6648    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6649
6650  if (isPSHUFDMask(M, VT)) {
6651    // The actual implementation will match the mask in the if above and then
6652    // during isel it can match several different instructions, not only pshufd
6653    // as its name says, sad but true, emulate the behavior for now...
6654    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6655      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6656
6657    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6658
6659    if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6660      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6661
6662    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6663      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6664
6665    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6666                                TargetMask, DAG);
6667  }
6668
6669  // Check if this can be converted into a logical shift.
6670  bool isLeft = false;
6671  unsigned ShAmt = 0;
6672  SDValue ShVal;
6673  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6674  if (isShift && ShVal.hasOneUse()) {
6675    // If the shifted value has multiple uses, it may be cheaper to use
6676    // v_set0 + movlhps or movhlps, etc.
6677    EVT EltVT = VT.getVectorElementType();
6678    ShAmt *= EltVT.getSizeInBits();
6679    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6680  }
6681
6682  if (isMOVLMask(M, VT)) {
6683    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6684      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6685    if (!isMOVLPMask(M, VT)) {
6686      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6687        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6688
6689      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6690        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6691    }
6692  }
6693
6694  // FIXME: fold these into legal mask.
6695  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6696    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6697
6698  if (isMOVHLPSMask(M, VT))
6699    return getMOVHighToLow(Op, dl, DAG);
6700
6701  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6702    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6703
6704  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6705    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6706
6707  if (isMOVLPMask(M, VT))
6708    return getMOVLP(Op, dl, DAG, HasSSE2);
6709
6710  if (ShouldXformToMOVHLPS(M, VT) ||
6711      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6712    return CommuteVectorShuffle(SVOp, DAG);
6713
6714  if (isShift) {
6715    // No better options. Use a vshldq / vsrldq.
6716    EVT EltVT = VT.getVectorElementType();
6717    ShAmt *= EltVT.getSizeInBits();
6718    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6719  }
6720
6721  bool Commuted = false;
6722  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6723  // 1,1,1,1 -> v8i16 though.
6724  V1IsSplat = isSplatVector(V1.getNode());
6725  V2IsSplat = isSplatVector(V2.getNode());
6726
6727  // Canonicalize the splat or undef, if present, to be on the RHS.
6728  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6729    CommuteVectorShuffleMask(M, NumElems);
6730    std::swap(V1, V2);
6731    std::swap(V1IsSplat, V2IsSplat);
6732    Commuted = true;
6733  }
6734
6735  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6736    // Shuffling low element of v1 into undef, just return v1.
6737    if (V2IsUndef)
6738      return V1;
6739    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6740    // the instruction selector will not match, so get a canonical MOVL with
6741    // swapped operands to undo the commute.
6742    return getMOVL(DAG, dl, VT, V2, V1);
6743  }
6744
6745  if (isUNPCKLMask(M, VT, HasAVX2))
6746    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6747
6748  if (isUNPCKHMask(M, VT, HasAVX2))
6749    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6750
6751  if (V2IsSplat) {
6752    // Normalize mask so all entries that point to V2 points to its first
6753    // element then try to match unpck{h|l} again. If match, return a
6754    // new vector_shuffle with the corrected mask.p
6755    SmallVector<int, 8> NewMask(M.begin(), M.end());
6756    NormalizeMask(NewMask, NumElems);
6757    if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6758      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6759    if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6760      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6761  }
6762
6763  if (Commuted) {
6764    // Commute is back and try unpck* again.
6765    // FIXME: this seems wrong.
6766    CommuteVectorShuffleMask(M, NumElems);
6767    std::swap(V1, V2);
6768    std::swap(V1IsSplat, V2IsSplat);
6769    Commuted = false;
6770
6771    if (isUNPCKLMask(M, VT, HasAVX2))
6772      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6773
6774    if (isUNPCKHMask(M, VT, HasAVX2))
6775      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6776  }
6777
6778  // Normalize the node to match x86 shuffle ops if needed
6779  if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6780    return CommuteVectorShuffle(SVOp, DAG);
6781
6782  // The checks below are all present in isShuffleMaskLegal, but they are
6783  // inlined here right now to enable us to directly emit target specific
6784  // nodes, and remove one by one until they don't return Op anymore.
6785
6786  if (isPALIGNRMask(M, VT, Subtarget))
6787    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6788                                getShufflePALIGNRImmediate(SVOp),
6789                                DAG);
6790
6791  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6792      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6793    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6794      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6795  }
6796
6797  if (isPSHUFHWMask(M, VT, HasAVX2))
6798    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6799                                getShufflePSHUFHWImmediate(SVOp),
6800                                DAG);
6801
6802  if (isPSHUFLWMask(M, VT, HasAVX2))
6803    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6804                                getShufflePSHUFLWImmediate(SVOp),
6805                                DAG);
6806
6807  if (isSHUFPMask(M, VT, HasAVX))
6808    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6809                                getShuffleSHUFImmediate(SVOp), DAG);
6810
6811  if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6812    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6813  if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6814    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6815
6816  //===--------------------------------------------------------------------===//
6817  // Generate target specific nodes for 128 or 256-bit shuffles only
6818  // supported in the AVX instruction set.
6819  //
6820
6821  // Handle VMOVDDUPY permutations
6822  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6823    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6824
6825  // Handle VPERMILPS/D* permutations
6826  if (isVPERMILPMask(M, VT, HasAVX)) {
6827    if (HasAVX2 && VT == MVT::v8i32)
6828      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6829                                  getShuffleSHUFImmediate(SVOp), DAG);
6830    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6831                                getShuffleSHUFImmediate(SVOp), DAG);
6832  }
6833
6834  // Handle VPERM2F128/VPERM2I128 permutations
6835  if (isVPERM2X128Mask(M, VT, HasAVX))
6836    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6837                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6838
6839  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6840  if (BlendOp.getNode())
6841    return BlendOp;
6842
6843  if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6844    SmallVector<SDValue, 8> permclMask;
6845    for (unsigned i = 0; i != 8; ++i) {
6846      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6847    }
6848    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6849                               &permclMask[0], 8);
6850    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6851    return DAG.getNode(X86ISD::VPERMV, dl, VT,
6852                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6853  }
6854
6855  if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6856    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6857                                getShuffleCLImmediate(SVOp), DAG);
6858
6859
6860  //===--------------------------------------------------------------------===//
6861  // Since no target specific shuffle was selected for this generic one,
6862  // lower it into other known shuffles. FIXME: this isn't true yet, but
6863  // this is the plan.
6864  //
6865
6866  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6867  if (VT == MVT::v8i16) {
6868    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6869    if (NewOp.getNode())
6870      return NewOp;
6871  }
6872
6873  if (VT == MVT::v16i8) {
6874    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6875    if (NewOp.getNode())
6876      return NewOp;
6877  }
6878
6879  if (VT == MVT::v32i8) {
6880    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, DAG, *this);
6881    if (NewOp.getNode())
6882      return NewOp;
6883  }
6884
6885  // Handle all 128-bit wide vectors with 4 elements, and match them with
6886  // several different shuffle types.
6887  if (NumElems == 4 && VT.is128BitVector())
6888    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6889
6890  // Handle general 256-bit shuffles
6891  if (VT.is256BitVector())
6892    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6893
6894  return SDValue();
6895}
6896
6897SDValue
6898X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6899                                                SelectionDAG &DAG) const {
6900  EVT VT = Op.getValueType();
6901  DebugLoc dl = Op.getDebugLoc();
6902
6903  if (!Op.getOperand(0).getValueType().is128BitVector())
6904    return SDValue();
6905
6906  if (VT.getSizeInBits() == 8) {
6907    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6908                                    Op.getOperand(0), Op.getOperand(1));
6909    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6910                                    DAG.getValueType(VT));
6911    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6912  }
6913
6914  if (VT.getSizeInBits() == 16) {
6915    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6916    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6917    if (Idx == 0)
6918      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6919                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6920                                     DAG.getNode(ISD::BITCAST, dl,
6921                                                 MVT::v4i32,
6922                                                 Op.getOperand(0)),
6923                                     Op.getOperand(1)));
6924    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6925                                    Op.getOperand(0), Op.getOperand(1));
6926    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6927                                    DAG.getValueType(VT));
6928    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6929  }
6930
6931  if (VT == MVT::f32) {
6932    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6933    // the result back to FR32 register. It's only worth matching if the
6934    // result has a single use which is a store or a bitcast to i32.  And in
6935    // the case of a store, it's not worth it if the index is a constant 0,
6936    // because a MOVSSmr can be used instead, which is smaller and faster.
6937    if (!Op.hasOneUse())
6938      return SDValue();
6939    SDNode *User = *Op.getNode()->use_begin();
6940    if ((User->getOpcode() != ISD::STORE ||
6941         (isa<ConstantSDNode>(Op.getOperand(1)) &&
6942          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6943        (User->getOpcode() != ISD::BITCAST ||
6944         User->getValueType(0) != MVT::i32))
6945      return SDValue();
6946    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6947                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6948                                              Op.getOperand(0)),
6949                                              Op.getOperand(1));
6950    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6951  }
6952
6953  if (VT == MVT::i32 || VT == MVT::i64) {
6954    // ExtractPS/pextrq works with constant index.
6955    if (isa<ConstantSDNode>(Op.getOperand(1)))
6956      return Op;
6957  }
6958  return SDValue();
6959}
6960
6961
6962SDValue
6963X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6964                                           SelectionDAG &DAG) const {
6965  if (!isa<ConstantSDNode>(Op.getOperand(1)))
6966    return SDValue();
6967
6968  SDValue Vec = Op.getOperand(0);
6969  EVT VecVT = Vec.getValueType();
6970
6971  // If this is a 256-bit vector result, first extract the 128-bit vector and
6972  // then extract the element from the 128-bit vector.
6973  if (VecVT.is256BitVector()) {
6974    DebugLoc dl = Op.getNode()->getDebugLoc();
6975    unsigned NumElems = VecVT.getVectorNumElements();
6976    SDValue Idx = Op.getOperand(1);
6977    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6978
6979    // Get the 128-bit vector.
6980    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6981
6982    if (IdxVal >= NumElems/2)
6983      IdxVal -= NumElems/2;
6984    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6985                       DAG.getConstant(IdxVal, MVT::i32));
6986  }
6987
6988  assert(VecVT.is128BitVector() && "Unexpected vector length");
6989
6990  if (Subtarget->hasSSE41()) {
6991    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6992    if (Res.getNode())
6993      return Res;
6994  }
6995
6996  EVT VT = Op.getValueType();
6997  DebugLoc dl = Op.getDebugLoc();
6998  // TODO: handle v16i8.
6999  if (VT.getSizeInBits() == 16) {
7000    SDValue Vec = Op.getOperand(0);
7001    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7002    if (Idx == 0)
7003      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7004                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7005                                     DAG.getNode(ISD::BITCAST, dl,
7006                                                 MVT::v4i32, Vec),
7007                                     Op.getOperand(1)));
7008    // Transform it so it match pextrw which produces a 32-bit result.
7009    EVT EltVT = MVT::i32;
7010    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7011                                    Op.getOperand(0), Op.getOperand(1));
7012    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7013                                    DAG.getValueType(VT));
7014    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7015  }
7016
7017  if (VT.getSizeInBits() == 32) {
7018    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7019    if (Idx == 0)
7020      return Op;
7021
7022    // SHUFPS the element to the lowest double word, then movss.
7023    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7024    EVT VVT = Op.getOperand(0).getValueType();
7025    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7026                                       DAG.getUNDEF(VVT), Mask);
7027    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7028                       DAG.getIntPtrConstant(0));
7029  }
7030
7031  if (VT.getSizeInBits() == 64) {
7032    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7033    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7034    //        to match extract_elt for f64.
7035    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7036    if (Idx == 0)
7037      return Op;
7038
7039    // UNPCKHPD the element to the lowest double word, then movsd.
7040    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7041    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7042    int Mask[2] = { 1, -1 };
7043    EVT VVT = Op.getOperand(0).getValueType();
7044    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7045                                       DAG.getUNDEF(VVT), Mask);
7046    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7047                       DAG.getIntPtrConstant(0));
7048  }
7049
7050  return SDValue();
7051}
7052
7053SDValue
7054X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7055                                               SelectionDAG &DAG) const {
7056  EVT VT = Op.getValueType();
7057  EVT EltVT = VT.getVectorElementType();
7058  DebugLoc dl = Op.getDebugLoc();
7059
7060  SDValue N0 = Op.getOperand(0);
7061  SDValue N1 = Op.getOperand(1);
7062  SDValue N2 = Op.getOperand(2);
7063
7064  if (!VT.is128BitVector())
7065    return SDValue();
7066
7067  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7068      isa<ConstantSDNode>(N2)) {
7069    unsigned Opc;
7070    if (VT == MVT::v8i16)
7071      Opc = X86ISD::PINSRW;
7072    else if (VT == MVT::v16i8)
7073      Opc = X86ISD::PINSRB;
7074    else
7075      Opc = X86ISD::PINSRB;
7076
7077    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7078    // argument.
7079    if (N1.getValueType() != MVT::i32)
7080      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7081    if (N2.getValueType() != MVT::i32)
7082      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7083    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7084  }
7085
7086  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7087    // Bits [7:6] of the constant are the source select.  This will always be
7088    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7089    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7090    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7091    // Bits [5:4] of the constant are the destination select.  This is the
7092    //  value of the incoming immediate.
7093    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7094    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7095    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7096    // Create this as a scalar to vector..
7097    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7098    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7099  }
7100
7101  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7102    // PINSR* works with constant index.
7103    return Op;
7104  }
7105  return SDValue();
7106}
7107
7108SDValue
7109X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7110  EVT VT = Op.getValueType();
7111  EVT EltVT = VT.getVectorElementType();
7112
7113  DebugLoc dl = Op.getDebugLoc();
7114  SDValue N0 = Op.getOperand(0);
7115  SDValue N1 = Op.getOperand(1);
7116  SDValue N2 = Op.getOperand(2);
7117
7118  // If this is a 256-bit vector result, first extract the 128-bit vector,
7119  // insert the element into the extracted half and then place it back.
7120  if (VT.is256BitVector()) {
7121    if (!isa<ConstantSDNode>(N2))
7122      return SDValue();
7123
7124    // Get the desired 128-bit vector half.
7125    unsigned NumElems = VT.getVectorNumElements();
7126    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7127    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7128
7129    // Insert the element into the desired half.
7130    bool Upper = IdxVal >= NumElems/2;
7131    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7132                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7133
7134    // Insert the changed part back to the 256-bit vector
7135    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7136  }
7137
7138  if (Subtarget->hasSSE41())
7139    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7140
7141  if (EltVT == MVT::i8)
7142    return SDValue();
7143
7144  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7145    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7146    // as its second argument.
7147    if (N1.getValueType() != MVT::i32)
7148      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7149    if (N2.getValueType() != MVT::i32)
7150      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7151    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7152  }
7153  return SDValue();
7154}
7155
7156SDValue
7157X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7158  LLVMContext *Context = DAG.getContext();
7159  DebugLoc dl = Op.getDebugLoc();
7160  EVT OpVT = Op.getValueType();
7161
7162  // If this is a 256-bit vector result, first insert into a 128-bit
7163  // vector and then insert into the 256-bit vector.
7164  if (!OpVT.is128BitVector()) {
7165    // Insert into a 128-bit vector.
7166    EVT VT128 = EVT::getVectorVT(*Context,
7167                                 OpVT.getVectorElementType(),
7168                                 OpVT.getVectorNumElements() / 2);
7169
7170    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7171
7172    // Insert the 128-bit vector.
7173    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7174  }
7175
7176  if (OpVT == MVT::v1i64 &&
7177      Op.getOperand(0).getValueType() == MVT::i64)
7178    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7179
7180  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7181  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7182  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7183                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7184}
7185
7186// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7187// a simple subregister reference or explicit instructions to grab
7188// upper bits of a vector.
7189SDValue
7190X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7191  if (Subtarget->hasAVX()) {
7192    DebugLoc dl = Op.getNode()->getDebugLoc();
7193    SDValue Vec = Op.getNode()->getOperand(0);
7194    SDValue Idx = Op.getNode()->getOperand(1);
7195
7196    if (Op.getNode()->getValueType(0).is128BitVector() &&
7197        Vec.getNode()->getValueType(0).is256BitVector() &&
7198        isa<ConstantSDNode>(Idx)) {
7199      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7200      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7201    }
7202  }
7203  return SDValue();
7204}
7205
7206// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7207// simple superregister reference or explicit instructions to insert
7208// the upper bits of a vector.
7209SDValue
7210X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7211  if (Subtarget->hasAVX()) {
7212    DebugLoc dl = Op.getNode()->getDebugLoc();
7213    SDValue Vec = Op.getNode()->getOperand(0);
7214    SDValue SubVec = Op.getNode()->getOperand(1);
7215    SDValue Idx = Op.getNode()->getOperand(2);
7216
7217    if (Op.getNode()->getValueType(0).is256BitVector() &&
7218        SubVec.getNode()->getValueType(0).is128BitVector() &&
7219        isa<ConstantSDNode>(Idx)) {
7220      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7221      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7222    }
7223  }
7224  return SDValue();
7225}
7226
7227// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7228// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7229// one of the above mentioned nodes. It has to be wrapped because otherwise
7230// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7231// be used to form addressing mode. These wrapped nodes will be selected
7232// into MOV32ri.
7233SDValue
7234X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7235  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7236
7237  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7238  // global base reg.
7239  unsigned char OpFlag = 0;
7240  unsigned WrapperKind = X86ISD::Wrapper;
7241  CodeModel::Model M = getTargetMachine().getCodeModel();
7242
7243  if (Subtarget->isPICStyleRIPRel() &&
7244      (M == CodeModel::Small || M == CodeModel::Kernel))
7245    WrapperKind = X86ISD::WrapperRIP;
7246  else if (Subtarget->isPICStyleGOT())
7247    OpFlag = X86II::MO_GOTOFF;
7248  else if (Subtarget->isPICStyleStubPIC())
7249    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7250
7251  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7252                                             CP->getAlignment(),
7253                                             CP->getOffset(), OpFlag);
7254  DebugLoc DL = CP->getDebugLoc();
7255  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7256  // With PIC, the address is actually $g + Offset.
7257  if (OpFlag) {
7258    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7259                         DAG.getNode(X86ISD::GlobalBaseReg,
7260                                     DebugLoc(), getPointerTy()),
7261                         Result);
7262  }
7263
7264  return Result;
7265}
7266
7267SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7268  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7269
7270  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7271  // global base reg.
7272  unsigned char OpFlag = 0;
7273  unsigned WrapperKind = X86ISD::Wrapper;
7274  CodeModel::Model M = getTargetMachine().getCodeModel();
7275
7276  if (Subtarget->isPICStyleRIPRel() &&
7277      (M == CodeModel::Small || M == CodeModel::Kernel))
7278    WrapperKind = X86ISD::WrapperRIP;
7279  else if (Subtarget->isPICStyleGOT())
7280    OpFlag = X86II::MO_GOTOFF;
7281  else if (Subtarget->isPICStyleStubPIC())
7282    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7283
7284  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7285                                          OpFlag);
7286  DebugLoc DL = JT->getDebugLoc();
7287  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7288
7289  // With PIC, the address is actually $g + Offset.
7290  if (OpFlag)
7291    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7292                         DAG.getNode(X86ISD::GlobalBaseReg,
7293                                     DebugLoc(), getPointerTy()),
7294                         Result);
7295
7296  return Result;
7297}
7298
7299SDValue
7300X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7301  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7302
7303  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7304  // global base reg.
7305  unsigned char OpFlag = 0;
7306  unsigned WrapperKind = X86ISD::Wrapper;
7307  CodeModel::Model M = getTargetMachine().getCodeModel();
7308
7309  if (Subtarget->isPICStyleRIPRel() &&
7310      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7311    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7312      OpFlag = X86II::MO_GOTPCREL;
7313    WrapperKind = X86ISD::WrapperRIP;
7314  } else if (Subtarget->isPICStyleGOT()) {
7315    OpFlag = X86II::MO_GOT;
7316  } else if (Subtarget->isPICStyleStubPIC()) {
7317    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7318  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7319    OpFlag = X86II::MO_DARWIN_NONLAZY;
7320  }
7321
7322  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7323
7324  DebugLoc DL = Op.getDebugLoc();
7325  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7326
7327
7328  // With PIC, the address is actually $g + Offset.
7329  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7330      !Subtarget->is64Bit()) {
7331    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7332                         DAG.getNode(X86ISD::GlobalBaseReg,
7333                                     DebugLoc(), getPointerTy()),
7334                         Result);
7335  }
7336
7337  // For symbols that require a load from a stub to get the address, emit the
7338  // load.
7339  if (isGlobalStubReference(OpFlag))
7340    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7341                         MachinePointerInfo::getGOT(), false, false, false, 0);
7342
7343  return Result;
7344}
7345
7346SDValue
7347X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7348  // Create the TargetBlockAddressAddress node.
7349  unsigned char OpFlags =
7350    Subtarget->ClassifyBlockAddressReference();
7351  CodeModel::Model M = getTargetMachine().getCodeModel();
7352  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7353  DebugLoc dl = Op.getDebugLoc();
7354  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7355                                       /*isTarget=*/true, OpFlags);
7356
7357  if (Subtarget->isPICStyleRIPRel() &&
7358      (M == CodeModel::Small || M == CodeModel::Kernel))
7359    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7360  else
7361    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7362
7363  // With PIC, the address is actually $g + Offset.
7364  if (isGlobalRelativeToPICBase(OpFlags)) {
7365    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7366                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7367                         Result);
7368  }
7369
7370  return Result;
7371}
7372
7373SDValue
7374X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7375                                      int64_t Offset,
7376                                      SelectionDAG &DAG) const {
7377  // Create the TargetGlobalAddress node, folding in the constant
7378  // offset if it is legal.
7379  unsigned char OpFlags =
7380    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7381  CodeModel::Model M = getTargetMachine().getCodeModel();
7382  SDValue Result;
7383  if (OpFlags == X86II::MO_NO_FLAG &&
7384      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7385    // A direct static reference to a global.
7386    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7387    Offset = 0;
7388  } else {
7389    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7390  }
7391
7392  if (Subtarget->isPICStyleRIPRel() &&
7393      (M == CodeModel::Small || M == CodeModel::Kernel))
7394    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7395  else
7396    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7397
7398  // With PIC, the address is actually $g + Offset.
7399  if (isGlobalRelativeToPICBase(OpFlags)) {
7400    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7401                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7402                         Result);
7403  }
7404
7405  // For globals that require a load from a stub to get the address, emit the
7406  // load.
7407  if (isGlobalStubReference(OpFlags))
7408    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7409                         MachinePointerInfo::getGOT(), false, false, false, 0);
7410
7411  // If there was a non-zero offset that we didn't fold, create an explicit
7412  // addition for it.
7413  if (Offset != 0)
7414    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7415                         DAG.getConstant(Offset, getPointerTy()));
7416
7417  return Result;
7418}
7419
7420SDValue
7421X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7422  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7423  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7424  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7425}
7426
7427static SDValue
7428GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7429           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7430           unsigned char OperandFlags, bool LocalDynamic = false) {
7431  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7432  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7433  DebugLoc dl = GA->getDebugLoc();
7434  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7435                                           GA->getValueType(0),
7436                                           GA->getOffset(),
7437                                           OperandFlags);
7438
7439  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7440                                           : X86ISD::TLSADDR;
7441
7442  if (InFlag) {
7443    SDValue Ops[] = { Chain,  TGA, *InFlag };
7444    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7445  } else {
7446    SDValue Ops[]  = { Chain, TGA };
7447    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7448  }
7449
7450  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7451  MFI->setAdjustsStack(true);
7452
7453  SDValue Flag = Chain.getValue(1);
7454  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7455}
7456
7457// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7458static SDValue
7459LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7460                                const EVT PtrVT) {
7461  SDValue InFlag;
7462  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7463  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7464                                     DAG.getNode(X86ISD::GlobalBaseReg,
7465                                                 DebugLoc(), PtrVT), InFlag);
7466  InFlag = Chain.getValue(1);
7467
7468  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7469}
7470
7471// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7472static SDValue
7473LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7474                                const EVT PtrVT) {
7475  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7476                    X86::RAX, X86II::MO_TLSGD);
7477}
7478
7479static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7480                                           SelectionDAG &DAG,
7481                                           const EVT PtrVT,
7482                                           bool is64Bit) {
7483  DebugLoc dl = GA->getDebugLoc();
7484
7485  // Get the start address of the TLS block for this module.
7486  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7487      .getInfo<X86MachineFunctionInfo>();
7488  MFI->incNumLocalDynamicTLSAccesses();
7489
7490  SDValue Base;
7491  if (is64Bit) {
7492    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7493                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7494  } else {
7495    SDValue InFlag;
7496    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7497        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7498    InFlag = Chain.getValue(1);
7499    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7500                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7501  }
7502
7503  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7504  // of Base.
7505
7506  // Build x@dtpoff.
7507  unsigned char OperandFlags = X86II::MO_DTPOFF;
7508  unsigned WrapperKind = X86ISD::Wrapper;
7509  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7510                                           GA->getValueType(0),
7511                                           GA->getOffset(), OperandFlags);
7512  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7513
7514  // Add x@dtpoff with the base.
7515  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7516}
7517
7518// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7519static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7520                                   const EVT PtrVT, TLSModel::Model model,
7521                                   bool is64Bit, bool isPIC) {
7522  DebugLoc dl = GA->getDebugLoc();
7523
7524  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7525  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7526                                                         is64Bit ? 257 : 256));
7527
7528  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7529                                      DAG.getIntPtrConstant(0),
7530                                      MachinePointerInfo(Ptr),
7531                                      false, false, false, 0);
7532
7533  unsigned char OperandFlags = 0;
7534  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7535  // initialexec.
7536  unsigned WrapperKind = X86ISD::Wrapper;
7537  if (model == TLSModel::LocalExec) {
7538    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7539  } else if (model == TLSModel::InitialExec) {
7540    if (is64Bit) {
7541      OperandFlags = X86II::MO_GOTTPOFF;
7542      WrapperKind = X86ISD::WrapperRIP;
7543    } else {
7544      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7545    }
7546  } else {
7547    llvm_unreachable("Unexpected model");
7548  }
7549
7550  // emit "addl x@ntpoff,%eax" (local exec)
7551  // or "addl x@indntpoff,%eax" (initial exec)
7552  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7553  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7554                                           GA->getValueType(0),
7555                                           GA->getOffset(), OperandFlags);
7556  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7557
7558  if (model == TLSModel::InitialExec) {
7559    if (isPIC && !is64Bit) {
7560      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7561                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7562                           Offset);
7563    }
7564
7565    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7566                         MachinePointerInfo::getGOT(), false, false, false,
7567                         0);
7568  }
7569
7570  // The address of the thread local variable is the add of the thread
7571  // pointer with the offset of the variable.
7572  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7573}
7574
7575SDValue
7576X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7577
7578  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7579  const GlobalValue *GV = GA->getGlobal();
7580
7581  if (Subtarget->isTargetELF()) {
7582    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7583
7584    switch (model) {
7585      case TLSModel::GeneralDynamic:
7586        if (Subtarget->is64Bit())
7587          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7588        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7589      case TLSModel::LocalDynamic:
7590        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7591                                           Subtarget->is64Bit());
7592      case TLSModel::InitialExec:
7593      case TLSModel::LocalExec:
7594        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7595                                   Subtarget->is64Bit(),
7596                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7597    }
7598    llvm_unreachable("Unknown TLS model.");
7599  }
7600
7601  if (Subtarget->isTargetDarwin()) {
7602    // Darwin only has one model of TLS.  Lower to that.
7603    unsigned char OpFlag = 0;
7604    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7605                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7606
7607    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7608    // global base reg.
7609    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7610                  !Subtarget->is64Bit();
7611    if (PIC32)
7612      OpFlag = X86II::MO_TLVP_PIC_BASE;
7613    else
7614      OpFlag = X86II::MO_TLVP;
7615    DebugLoc DL = Op.getDebugLoc();
7616    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7617                                                GA->getValueType(0),
7618                                                GA->getOffset(), OpFlag);
7619    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7620
7621    // With PIC32, the address is actually $g + Offset.
7622    if (PIC32)
7623      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7624                           DAG.getNode(X86ISD::GlobalBaseReg,
7625                                       DebugLoc(), getPointerTy()),
7626                           Offset);
7627
7628    // Lowering the machine isd will make sure everything is in the right
7629    // location.
7630    SDValue Chain = DAG.getEntryNode();
7631    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7632    SDValue Args[] = { Chain, Offset };
7633    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7634
7635    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7636    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7637    MFI->setAdjustsStack(true);
7638
7639    // And our return value (tls address) is in the standard call return value
7640    // location.
7641    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7642    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7643                              Chain.getValue(1));
7644  }
7645
7646  if (Subtarget->isTargetWindows()) {
7647    // Just use the implicit TLS architecture
7648    // Need to generate someting similar to:
7649    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7650    //                                  ; from TEB
7651    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7652    //   mov     rcx, qword [rdx+rcx*8]
7653    //   mov     eax, .tls$:tlsvar
7654    //   [rax+rcx] contains the address
7655    // Windows 64bit: gs:0x58
7656    // Windows 32bit: fs:__tls_array
7657
7658    // If GV is an alias then use the aliasee for determining
7659    // thread-localness.
7660    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7661      GV = GA->resolveAliasedGlobal(false);
7662    DebugLoc dl = GA->getDebugLoc();
7663    SDValue Chain = DAG.getEntryNode();
7664
7665    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7666    // %gs:0x58 (64-bit).
7667    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7668                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7669                                                             256)
7670                                        : Type::getInt32PtrTy(*DAG.getContext(),
7671                                                              257));
7672
7673    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7674                                        Subtarget->is64Bit()
7675                                        ? DAG.getIntPtrConstant(0x58)
7676                                        : DAG.getExternalSymbol("_tls_array",
7677                                                                getPointerTy()),
7678                                        MachinePointerInfo(Ptr),
7679                                        false, false, false, 0);
7680
7681    // Load the _tls_index variable
7682    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7683    if (Subtarget->is64Bit())
7684      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7685                           IDX, MachinePointerInfo(), MVT::i32,
7686                           false, false, 0);
7687    else
7688      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7689                        false, false, false, 0);
7690
7691    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7692                                    getPointerTy());
7693    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7694
7695    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7696    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7697                      false, false, false, 0);
7698
7699    // Get the offset of start of .tls section
7700    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7701                                             GA->getValueType(0),
7702                                             GA->getOffset(), X86II::MO_SECREL);
7703    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7704
7705    // The address of the thread local variable is the add of the thread
7706    // pointer with the offset of the variable.
7707    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7708  }
7709
7710  llvm_unreachable("TLS not implemented for this target.");
7711}
7712
7713
7714/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7715/// and take a 2 x i32 value to shift plus a shift amount.
7716SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7717  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7718  EVT VT = Op.getValueType();
7719  unsigned VTBits = VT.getSizeInBits();
7720  DebugLoc dl = Op.getDebugLoc();
7721  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7722  SDValue ShOpLo = Op.getOperand(0);
7723  SDValue ShOpHi = Op.getOperand(1);
7724  SDValue ShAmt  = Op.getOperand(2);
7725  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7726                                     DAG.getConstant(VTBits - 1, MVT::i8))
7727                       : DAG.getConstant(0, VT);
7728
7729  SDValue Tmp2, Tmp3;
7730  if (Op.getOpcode() == ISD::SHL_PARTS) {
7731    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7732    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7733  } else {
7734    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7735    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7736  }
7737
7738  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7739                                DAG.getConstant(VTBits, MVT::i8));
7740  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7741                             AndNode, DAG.getConstant(0, MVT::i8));
7742
7743  SDValue Hi, Lo;
7744  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7745  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7746  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7747
7748  if (Op.getOpcode() == ISD::SHL_PARTS) {
7749    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7750    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7751  } else {
7752    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7753    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7754  }
7755
7756  SDValue Ops[2] = { Lo, Hi };
7757  return DAG.getMergeValues(Ops, 2, dl);
7758}
7759
7760SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7761                                           SelectionDAG &DAG) const {
7762  EVT SrcVT = Op.getOperand(0).getValueType();
7763
7764  if (SrcVT.isVector())
7765    return SDValue();
7766
7767  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7768         "Unknown SINT_TO_FP to lower!");
7769
7770  // These are really Legal; return the operand so the caller accepts it as
7771  // Legal.
7772  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7773    return Op;
7774  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7775      Subtarget->is64Bit()) {
7776    return Op;
7777  }
7778
7779  DebugLoc dl = Op.getDebugLoc();
7780  unsigned Size = SrcVT.getSizeInBits()/8;
7781  MachineFunction &MF = DAG.getMachineFunction();
7782  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7783  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7784  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7785                               StackSlot,
7786                               MachinePointerInfo::getFixedStack(SSFI),
7787                               false, false, 0);
7788  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7789}
7790
7791SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7792                                     SDValue StackSlot,
7793                                     SelectionDAG &DAG) const {
7794  // Build the FILD
7795  DebugLoc DL = Op.getDebugLoc();
7796  SDVTList Tys;
7797  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7798  if (useSSE)
7799    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7800  else
7801    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7802
7803  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7804
7805  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7806  MachineMemOperand *MMO;
7807  if (FI) {
7808    int SSFI = FI->getIndex();
7809    MMO =
7810      DAG.getMachineFunction()
7811      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7812                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7813  } else {
7814    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7815    StackSlot = StackSlot.getOperand(1);
7816  }
7817  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7818  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7819                                           X86ISD::FILD, DL,
7820                                           Tys, Ops, array_lengthof(Ops),
7821                                           SrcVT, MMO);
7822
7823  if (useSSE) {
7824    Chain = Result.getValue(1);
7825    SDValue InFlag = Result.getValue(2);
7826
7827    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7828    // shouldn't be necessary except that RFP cannot be live across
7829    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7830    MachineFunction &MF = DAG.getMachineFunction();
7831    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7832    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7833    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7834    Tys = DAG.getVTList(MVT::Other);
7835    SDValue Ops[] = {
7836      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7837    };
7838    MachineMemOperand *MMO =
7839      DAG.getMachineFunction()
7840      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7841                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7842
7843    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7844                                    Ops, array_lengthof(Ops),
7845                                    Op.getValueType(), MMO);
7846    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7847                         MachinePointerInfo::getFixedStack(SSFI),
7848                         false, false, false, 0);
7849  }
7850
7851  return Result;
7852}
7853
7854// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7855SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7856                                               SelectionDAG &DAG) const {
7857  // This algorithm is not obvious. Here it is what we're trying to output:
7858  /*
7859     movq       %rax,  %xmm0
7860     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7861     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7862     #ifdef __SSE3__
7863       haddpd   %xmm0, %xmm0
7864     #else
7865       pshufd   $0x4e, %xmm0, %xmm1
7866       addpd    %xmm1, %xmm0
7867     #endif
7868  */
7869
7870  DebugLoc dl = Op.getDebugLoc();
7871  LLVMContext *Context = DAG.getContext();
7872
7873  // Build some magic constants.
7874  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7875  Constant *C0 = ConstantDataVector::get(*Context, CV0);
7876  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7877
7878  SmallVector<Constant*,2> CV1;
7879  CV1.push_back(
7880        ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7881  CV1.push_back(
7882        ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7883  Constant *C1 = ConstantVector::get(CV1);
7884  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7885
7886  // Load the 64-bit value into an XMM register.
7887  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7888                            Op.getOperand(0));
7889  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7890                              MachinePointerInfo::getConstantPool(),
7891                              false, false, false, 16);
7892  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7893                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7894                              CLod0);
7895
7896  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7897                              MachinePointerInfo::getConstantPool(),
7898                              false, false, false, 16);
7899  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7900  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7901  SDValue Result;
7902
7903  if (Subtarget->hasSSE3()) {
7904    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7905    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7906  } else {
7907    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7908    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7909                                           S2F, 0x4E, DAG);
7910    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7911                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7912                         Sub);
7913  }
7914
7915  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7916                     DAG.getIntPtrConstant(0));
7917}
7918
7919// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7920SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7921                                               SelectionDAG &DAG) const {
7922  DebugLoc dl = Op.getDebugLoc();
7923  // FP constant to bias correct the final result.
7924  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7925                                   MVT::f64);
7926
7927  // Load the 32-bit value into an XMM register.
7928  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7929                             Op.getOperand(0));
7930
7931  // Zero out the upper parts of the register.
7932  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7933
7934  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7935                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7936                     DAG.getIntPtrConstant(0));
7937
7938  // Or the load with the bias.
7939  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7940                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7941                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7942                                                   MVT::v2f64, Load)),
7943                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7944                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7945                                                   MVT::v2f64, Bias)));
7946  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7947                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7948                   DAG.getIntPtrConstant(0));
7949
7950  // Subtract the bias.
7951  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7952
7953  // Handle final rounding.
7954  EVT DestVT = Op.getValueType();
7955
7956  if (DestVT.bitsLT(MVT::f64))
7957    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7958                       DAG.getIntPtrConstant(0));
7959  if (DestVT.bitsGT(MVT::f64))
7960    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7961
7962  // Handle final rounding.
7963  return Sub;
7964}
7965
7966SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7967                                           SelectionDAG &DAG) const {
7968  SDValue N0 = Op.getOperand(0);
7969  DebugLoc dl = Op.getDebugLoc();
7970
7971  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7972  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7973  // the optimization here.
7974  if (DAG.SignBitIsZero(N0))
7975    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7976
7977  EVT SrcVT = N0.getValueType();
7978  EVT DstVT = Op.getValueType();
7979  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7980    return LowerUINT_TO_FP_i64(Op, DAG);
7981  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7982    return LowerUINT_TO_FP_i32(Op, DAG);
7983  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7984    return SDValue();
7985
7986  // Make a 64-bit buffer, and use it to build an FILD.
7987  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7988  if (SrcVT == MVT::i32) {
7989    SDValue WordOff = DAG.getConstant(4, getPointerTy());
7990    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7991                                     getPointerTy(), StackSlot, WordOff);
7992    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7993                                  StackSlot, MachinePointerInfo(),
7994                                  false, false, 0);
7995    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7996                                  OffsetSlot, MachinePointerInfo(),
7997                                  false, false, 0);
7998    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7999    return Fild;
8000  }
8001
8002  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8003  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8004                               StackSlot, MachinePointerInfo(),
8005                               false, false, 0);
8006  // For i64 source, we need to add the appropriate power of 2 if the input
8007  // was negative.  This is the same as the optimization in
8008  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8009  // we must be careful to do the computation in x87 extended precision, not
8010  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8011  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8012  MachineMemOperand *MMO =
8013    DAG.getMachineFunction()
8014    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8015                          MachineMemOperand::MOLoad, 8, 8);
8016
8017  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8018  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8019  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8020                                         MVT::i64, MMO);
8021
8022  APInt FF(32, 0x5F800000ULL);
8023
8024  // Check whether the sign bit is set.
8025  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8026                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8027                                 ISD::SETLT);
8028
8029  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8030  SDValue FudgePtr = DAG.getConstantPool(
8031                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8032                                         getPointerTy());
8033
8034  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8035  SDValue Zero = DAG.getIntPtrConstant(0);
8036  SDValue Four = DAG.getIntPtrConstant(4);
8037  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8038                               Zero, Four);
8039  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8040
8041  // Load the value out, extending it from f32 to f80.
8042  // FIXME: Avoid the extend by constructing the right constant pool?
8043  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8044                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8045                                 MVT::f32, false, false, 4);
8046  // Extend everything to 80 bits to force it to be done on x87.
8047  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8048  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8049}
8050
8051std::pair<SDValue,SDValue> X86TargetLowering::
8052FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8053  DebugLoc DL = Op.getDebugLoc();
8054
8055  EVT DstTy = Op.getValueType();
8056
8057  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8058    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8059    DstTy = MVT::i64;
8060  }
8061
8062  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8063         DstTy.getSimpleVT() >= MVT::i16 &&
8064         "Unknown FP_TO_INT to lower!");
8065
8066  // These are really Legal.
8067  if (DstTy == MVT::i32 &&
8068      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8069    return std::make_pair(SDValue(), SDValue());
8070  if (Subtarget->is64Bit() &&
8071      DstTy == MVT::i64 &&
8072      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8073    return std::make_pair(SDValue(), SDValue());
8074
8075  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8076  // stack slot, or into the FTOL runtime function.
8077  MachineFunction &MF = DAG.getMachineFunction();
8078  unsigned MemSize = DstTy.getSizeInBits()/8;
8079  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8080  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8081
8082  unsigned Opc;
8083  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8084    Opc = X86ISD::WIN_FTOL;
8085  else
8086    switch (DstTy.getSimpleVT().SimpleTy) {
8087    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8088    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8089    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8090    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8091    }
8092
8093  SDValue Chain = DAG.getEntryNode();
8094  SDValue Value = Op.getOperand(0);
8095  EVT TheVT = Op.getOperand(0).getValueType();
8096  // FIXME This causes a redundant load/store if the SSE-class value is already
8097  // in memory, such as if it is on the callstack.
8098  if (isScalarFPTypeInSSEReg(TheVT)) {
8099    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8100    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8101                         MachinePointerInfo::getFixedStack(SSFI),
8102                         false, false, 0);
8103    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8104    SDValue Ops[] = {
8105      Chain, StackSlot, DAG.getValueType(TheVT)
8106    };
8107
8108    MachineMemOperand *MMO =
8109      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8110                              MachineMemOperand::MOLoad, MemSize, MemSize);
8111    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8112                                    DstTy, MMO);
8113    Chain = Value.getValue(1);
8114    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8115    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8116  }
8117
8118  MachineMemOperand *MMO =
8119    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8120                            MachineMemOperand::MOStore, MemSize, MemSize);
8121
8122  if (Opc != X86ISD::WIN_FTOL) {
8123    // Build the FP_TO_INT*_IN_MEM
8124    SDValue Ops[] = { Chain, Value, StackSlot };
8125    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8126                                           Ops, 3, DstTy, MMO);
8127    return std::make_pair(FIST, StackSlot);
8128  } else {
8129    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8130      DAG.getVTList(MVT::Other, MVT::Glue),
8131      Chain, Value);
8132    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8133      MVT::i32, ftol.getValue(1));
8134    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8135      MVT::i32, eax.getValue(2));
8136    SDValue Ops[] = { eax, edx };
8137    SDValue pair = IsReplace
8138      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8139      : DAG.getMergeValues(Ops, 2, DL);
8140    return std::make_pair(pair, SDValue());
8141  }
8142}
8143
8144SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8145                                           SelectionDAG &DAG) const {
8146  if (Op.getValueType().isVector())
8147    return SDValue();
8148
8149  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8150    /*IsSigned=*/ true, /*IsReplace=*/ false);
8151  SDValue FIST = Vals.first, StackSlot = Vals.second;
8152  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8153  if (FIST.getNode() == 0) return Op;
8154
8155  if (StackSlot.getNode())
8156    // Load the result.
8157    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8158                       FIST, StackSlot, MachinePointerInfo(),
8159                       false, false, false, 0);
8160
8161  // The node is the result.
8162  return FIST;
8163}
8164
8165SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8166                                           SelectionDAG &DAG) const {
8167  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8168    /*IsSigned=*/ false, /*IsReplace=*/ false);
8169  SDValue FIST = Vals.first, StackSlot = Vals.second;
8170  assert(FIST.getNode() && "Unexpected failure");
8171
8172  if (StackSlot.getNode())
8173    // Load the result.
8174    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8175                       FIST, StackSlot, MachinePointerInfo(),
8176                       false, false, false, 0);
8177
8178  // The node is the result.
8179  return FIST;
8180}
8181
8182SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8183  LLVMContext *Context = DAG.getContext();
8184  DebugLoc dl = Op.getDebugLoc();
8185  EVT VT = Op.getValueType();
8186  EVT EltVT = VT;
8187  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8188  if (VT.isVector()) {
8189    EltVT = VT.getVectorElementType();
8190    NumElts = VT.getVectorNumElements();
8191  }
8192  Constant *C;
8193  if (EltVT == MVT::f64)
8194    C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8195  else
8196    C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8197  C = ConstantVector::getSplat(NumElts, C);
8198  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8199  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8200  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8201                             MachinePointerInfo::getConstantPool(),
8202                             false, false, false, Alignment);
8203  if (VT.isVector()) {
8204    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8205    return DAG.getNode(ISD::BITCAST, dl, VT,
8206                       DAG.getNode(ISD::AND, dl, ANDVT,
8207                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8208                                               Op.getOperand(0)),
8209                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8210  }
8211  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8212}
8213
8214SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8215  LLVMContext *Context = DAG.getContext();
8216  DebugLoc dl = Op.getDebugLoc();
8217  EVT VT = Op.getValueType();
8218  EVT EltVT = VT;
8219  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8220  if (VT.isVector()) {
8221    EltVT = VT.getVectorElementType();
8222    NumElts = VT.getVectorNumElements();
8223  }
8224  Constant *C;
8225  if (EltVT == MVT::f64)
8226    C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8227  else
8228    C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8229  C = ConstantVector::getSplat(NumElts, C);
8230  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8231  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8232                             MachinePointerInfo::getConstantPool(),
8233                             false, false, false, 16);
8234  if (VT.isVector()) {
8235    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8236    return DAG.getNode(ISD::BITCAST, dl, VT,
8237                       DAG.getNode(ISD::XOR, dl, XORVT,
8238                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8239                                               Op.getOperand(0)),
8240                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8241  }
8242
8243  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8244}
8245
8246SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8247  LLVMContext *Context = DAG.getContext();
8248  SDValue Op0 = Op.getOperand(0);
8249  SDValue Op1 = Op.getOperand(1);
8250  DebugLoc dl = Op.getDebugLoc();
8251  EVT VT = Op.getValueType();
8252  EVT SrcVT = Op1.getValueType();
8253
8254  // If second operand is smaller, extend it first.
8255  if (SrcVT.bitsLT(VT)) {
8256    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8257    SrcVT = VT;
8258  }
8259  // And if it is bigger, shrink it first.
8260  if (SrcVT.bitsGT(VT)) {
8261    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8262    SrcVT = VT;
8263  }
8264
8265  // At this point the operands and the result should have the same
8266  // type, and that won't be f80 since that is not custom lowered.
8267
8268  // First get the sign bit of second operand.
8269  SmallVector<Constant*,4> CV;
8270  if (SrcVT == MVT::f64) {
8271    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8272    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8273  } else {
8274    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8275    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8276    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8277    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8278  }
8279  Constant *C = ConstantVector::get(CV);
8280  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8281  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8282                              MachinePointerInfo::getConstantPool(),
8283                              false, false, false, 16);
8284  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8285
8286  // Shift sign bit right or left if the two operands have different types.
8287  if (SrcVT.bitsGT(VT)) {
8288    // Op0 is MVT::f32, Op1 is MVT::f64.
8289    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8290    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8291                          DAG.getConstant(32, MVT::i32));
8292    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8293    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8294                          DAG.getIntPtrConstant(0));
8295  }
8296
8297  // Clear first operand sign bit.
8298  CV.clear();
8299  if (VT == MVT::f64) {
8300    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8301    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8302  } else {
8303    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8304    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8305    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8306    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8307  }
8308  C = ConstantVector::get(CV);
8309  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8310  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8311                              MachinePointerInfo::getConstantPool(),
8312                              false, false, false, 16);
8313  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8314
8315  // Or the value with the sign bit.
8316  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8317}
8318
8319SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8320  SDValue N0 = Op.getOperand(0);
8321  DebugLoc dl = Op.getDebugLoc();
8322  EVT VT = Op.getValueType();
8323
8324  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8325  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8326                                  DAG.getConstant(1, VT));
8327  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8328}
8329
8330/// Emit nodes that will be selected as "test Op0,Op0", or something
8331/// equivalent.
8332SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8333                                    SelectionDAG &DAG) const {
8334  DebugLoc dl = Op.getDebugLoc();
8335
8336  // CF and OF aren't always set the way we want. Determine which
8337  // of these we need.
8338  bool NeedCF = false;
8339  bool NeedOF = false;
8340  switch (X86CC) {
8341  default: break;
8342  case X86::COND_A: case X86::COND_AE:
8343  case X86::COND_B: case X86::COND_BE:
8344    NeedCF = true;
8345    break;
8346  case X86::COND_G: case X86::COND_GE:
8347  case X86::COND_L: case X86::COND_LE:
8348  case X86::COND_O: case X86::COND_NO:
8349    NeedOF = true;
8350    break;
8351  }
8352
8353  // See if we can use the EFLAGS value from the operand instead of
8354  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8355  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8356  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8357    // Emit a CMP with 0, which is the TEST pattern.
8358    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8359                       DAG.getConstant(0, Op.getValueType()));
8360
8361  unsigned Opcode = 0;
8362  unsigned NumOperands = 0;
8363
8364  // Truncate operations may prevent the merge of the SETCC instruction
8365  // and the arithmetic intruction before it. Attempt to truncate the operands
8366  // of the arithmetic instruction and use a reduced bit-width instruction.
8367  bool NeedTruncation = false;
8368  SDValue ArithOp = Op;
8369  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8370    SDValue Arith = Op->getOperand(0);
8371    // Both the trunc and the arithmetic op need to have one user each.
8372    if (Arith->hasOneUse())
8373      switch (Arith.getOpcode()) {
8374        default: break;
8375        case ISD::ADD:
8376        case ISD::SUB:
8377        case ISD::AND:
8378        case ISD::OR:
8379        case ISD::XOR: {
8380          NeedTruncation = true;
8381          ArithOp = Arith;
8382        }
8383      }
8384  }
8385
8386  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8387  // which may be the result of a CAST.  We use the variable 'Op', which is the
8388  // non-casted variable when we check for possible users.
8389  switch (ArithOp.getOpcode()) {
8390  case ISD::ADD:
8391    // Due to an isel shortcoming, be conservative if this add is likely to be
8392    // selected as part of a load-modify-store instruction. When the root node
8393    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8394    // uses of other nodes in the match, such as the ADD in this case. This
8395    // leads to the ADD being left around and reselected, with the result being
8396    // two adds in the output.  Alas, even if none our users are stores, that
8397    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8398    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8399    // climbing the DAG back to the root, and it doesn't seem to be worth the
8400    // effort.
8401    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8402         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8403      if (UI->getOpcode() != ISD::CopyToReg &&
8404          UI->getOpcode() != ISD::SETCC &&
8405          UI->getOpcode() != ISD::STORE)
8406        goto default_case;
8407
8408    if (ConstantSDNode *C =
8409        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8410      // An add of one will be selected as an INC.
8411      if (C->getAPIntValue() == 1) {
8412        Opcode = X86ISD::INC;
8413        NumOperands = 1;
8414        break;
8415      }
8416
8417      // An add of negative one (subtract of one) will be selected as a DEC.
8418      if (C->getAPIntValue().isAllOnesValue()) {
8419        Opcode = X86ISD::DEC;
8420        NumOperands = 1;
8421        break;
8422      }
8423    }
8424
8425    // Otherwise use a regular EFLAGS-setting add.
8426    Opcode = X86ISD::ADD;
8427    NumOperands = 2;
8428    break;
8429  case ISD::AND: {
8430    // If the primary and result isn't used, don't bother using X86ISD::AND,
8431    // because a TEST instruction will be better.
8432    bool NonFlagUse = false;
8433    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8434           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8435      SDNode *User = *UI;
8436      unsigned UOpNo = UI.getOperandNo();
8437      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8438        // Look pass truncate.
8439        UOpNo = User->use_begin().getOperandNo();
8440        User = *User->use_begin();
8441      }
8442
8443      if (User->getOpcode() != ISD::BRCOND &&
8444          User->getOpcode() != ISD::SETCC &&
8445          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8446        NonFlagUse = true;
8447        break;
8448      }
8449    }
8450
8451    if (!NonFlagUse)
8452      break;
8453  }
8454    // FALL THROUGH
8455  case ISD::SUB:
8456  case ISD::OR:
8457  case ISD::XOR:
8458    // Due to the ISEL shortcoming noted above, be conservative if this op is
8459    // likely to be selected as part of a load-modify-store instruction.
8460    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8461           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8462      if (UI->getOpcode() == ISD::STORE)
8463        goto default_case;
8464
8465    // Otherwise use a regular EFLAGS-setting instruction.
8466    switch (ArithOp.getOpcode()) {
8467    default: llvm_unreachable("unexpected operator!");
8468    case ISD::SUB: Opcode = X86ISD::SUB; break;
8469    case ISD::OR:  Opcode = X86ISD::OR;  break;
8470    case ISD::XOR: Opcode = X86ISD::XOR; break;
8471    case ISD::AND: Opcode = X86ISD::AND; break;
8472    }
8473
8474    NumOperands = 2;
8475    break;
8476  case X86ISD::ADD:
8477  case X86ISD::SUB:
8478  case X86ISD::INC:
8479  case X86ISD::DEC:
8480  case X86ISD::OR:
8481  case X86ISD::XOR:
8482  case X86ISD::AND:
8483    return SDValue(Op.getNode(), 1);
8484  default:
8485  default_case:
8486    break;
8487  }
8488
8489  // If we found that truncation is beneficial, perform the truncation and
8490  // update 'Op'.
8491  if (NeedTruncation) {
8492    EVT VT = Op.getValueType();
8493    SDValue WideVal = Op->getOperand(0);
8494    EVT WideVT = WideVal.getValueType();
8495    unsigned ConvertedOp = 0;
8496    // Use a target machine opcode to prevent further DAGCombine
8497    // optimizations that may separate the arithmetic operations
8498    // from the setcc node.
8499    switch (WideVal.getOpcode()) {
8500      default: break;
8501      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8502      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8503      case ISD::AND: ConvertedOp = X86ISD::AND; break;
8504      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8505      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8506    }
8507
8508    if (ConvertedOp) {
8509      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8510      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8511        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8512        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8513        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8514      }
8515    }
8516  }
8517
8518  if (Opcode == 0)
8519    // Emit a CMP with 0, which is the TEST pattern.
8520    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8521                       DAG.getConstant(0, Op.getValueType()));
8522
8523  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8524  SmallVector<SDValue, 4> Ops;
8525  for (unsigned i = 0; i != NumOperands; ++i)
8526    Ops.push_back(Op.getOperand(i));
8527
8528  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8529  DAG.ReplaceAllUsesWith(Op, New);
8530  return SDValue(New.getNode(), 1);
8531}
8532
8533/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8534/// equivalent.
8535SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8536                                   SelectionDAG &DAG) const {
8537  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8538    if (C->getAPIntValue() == 0)
8539      return EmitTest(Op0, X86CC, DAG);
8540
8541  DebugLoc dl = Op0.getDebugLoc();
8542  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8543       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8544    // Use SUB instead of CMP to enable CSE between SUB and CMP.
8545    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8546    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8547                              Op0, Op1);
8548    return SDValue(Sub.getNode(), 1);
8549  }
8550  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8551}
8552
8553/// Convert a comparison if required by the subtarget.
8554SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8555                                                 SelectionDAG &DAG) const {
8556  // If the subtarget does not support the FUCOMI instruction, floating-point
8557  // comparisons have to be converted.
8558  if (Subtarget->hasCMov() ||
8559      Cmp.getOpcode() != X86ISD::CMP ||
8560      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8561      !Cmp.getOperand(1).getValueType().isFloatingPoint())
8562    return Cmp;
8563
8564  // The instruction selector will select an FUCOM instruction instead of
8565  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8566  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8567  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8568  DebugLoc dl = Cmp.getDebugLoc();
8569  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8570  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8571  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8572                            DAG.getConstant(8, MVT::i8));
8573  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8574  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8575}
8576
8577/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8578/// if it's possible.
8579SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8580                                     DebugLoc dl, SelectionDAG &DAG) const {
8581  SDValue Op0 = And.getOperand(0);
8582  SDValue Op1 = And.getOperand(1);
8583  if (Op0.getOpcode() == ISD::TRUNCATE)
8584    Op0 = Op0.getOperand(0);
8585  if (Op1.getOpcode() == ISD::TRUNCATE)
8586    Op1 = Op1.getOperand(0);
8587
8588  SDValue LHS, RHS;
8589  if (Op1.getOpcode() == ISD::SHL)
8590    std::swap(Op0, Op1);
8591  if (Op0.getOpcode() == ISD::SHL) {
8592    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8593      if (And00C->getZExtValue() == 1) {
8594        // If we looked past a truncate, check that it's only truncating away
8595        // known zeros.
8596        unsigned BitWidth = Op0.getValueSizeInBits();
8597        unsigned AndBitWidth = And.getValueSizeInBits();
8598        if (BitWidth > AndBitWidth) {
8599          APInt Zeros, Ones;
8600          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8601          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8602            return SDValue();
8603        }
8604        LHS = Op1;
8605        RHS = Op0.getOperand(1);
8606      }
8607  } else if (Op1.getOpcode() == ISD::Constant) {
8608    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8609    uint64_t AndRHSVal = AndRHS->getZExtValue();
8610    SDValue AndLHS = Op0;
8611
8612    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8613      LHS = AndLHS.getOperand(0);
8614      RHS = AndLHS.getOperand(1);
8615    }
8616
8617    // Use BT if the immediate can't be encoded in a TEST instruction.
8618    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8619      LHS = AndLHS;
8620      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8621    }
8622  }
8623
8624  if (LHS.getNode()) {
8625    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8626    // instruction.  Since the shift amount is in-range-or-undefined, we know
8627    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8628    // the encoding for the i16 version is larger than the i32 version.
8629    // Also promote i16 to i32 for performance / code size reason.
8630    if (LHS.getValueType() == MVT::i8 ||
8631        LHS.getValueType() == MVT::i16)
8632      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8633
8634    // If the operand types disagree, extend the shift amount to match.  Since
8635    // BT ignores high bits (like shifts) we can use anyextend.
8636    if (LHS.getValueType() != RHS.getValueType())
8637      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8638
8639    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8640    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8641    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8642                       DAG.getConstant(Cond, MVT::i8), BT);
8643  }
8644
8645  return SDValue();
8646}
8647
8648SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8649
8650  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8651
8652  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8653  SDValue Op0 = Op.getOperand(0);
8654  SDValue Op1 = Op.getOperand(1);
8655  DebugLoc dl = Op.getDebugLoc();
8656  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8657
8658  // Optimize to BT if possible.
8659  // Lower (X & (1 << N)) == 0 to BT(X, N).
8660  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8661  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8662  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8663      Op1.getOpcode() == ISD::Constant &&
8664      cast<ConstantSDNode>(Op1)->isNullValue() &&
8665      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8666    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8667    if (NewSetCC.getNode())
8668      return NewSetCC;
8669  }
8670
8671  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8672  // these.
8673  if (Op1.getOpcode() == ISD::Constant &&
8674      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8675       cast<ConstantSDNode>(Op1)->isNullValue()) &&
8676      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8677
8678    // If the input is a setcc, then reuse the input setcc or use a new one with
8679    // the inverted condition.
8680    if (Op0.getOpcode() == X86ISD::SETCC) {
8681      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8682      bool Invert = (CC == ISD::SETNE) ^
8683        cast<ConstantSDNode>(Op1)->isNullValue();
8684      if (!Invert) return Op0;
8685
8686      CCode = X86::GetOppositeBranchCondition(CCode);
8687      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8688                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8689    }
8690  }
8691
8692  bool isFP = Op1.getValueType().isFloatingPoint();
8693  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8694  if (X86CC == X86::COND_INVALID)
8695    return SDValue();
8696
8697  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8698  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8699  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8700                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8701}
8702
8703// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8704// ones, and then concatenate the result back.
8705static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8706  EVT VT = Op.getValueType();
8707
8708  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8709         "Unsupported value type for operation");
8710
8711  unsigned NumElems = VT.getVectorNumElements();
8712  DebugLoc dl = Op.getDebugLoc();
8713  SDValue CC = Op.getOperand(2);
8714
8715  // Extract the LHS vectors
8716  SDValue LHS = Op.getOperand(0);
8717  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8718  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8719
8720  // Extract the RHS vectors
8721  SDValue RHS = Op.getOperand(1);
8722  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8723  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8724
8725  // Issue the operation on the smaller types and concatenate the result back
8726  MVT EltVT = VT.getVectorElementType().getSimpleVT();
8727  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8728  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8729                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8730                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8731}
8732
8733
8734SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8735  SDValue Cond;
8736  SDValue Op0 = Op.getOperand(0);
8737  SDValue Op1 = Op.getOperand(1);
8738  SDValue CC = Op.getOperand(2);
8739  EVT VT = Op.getValueType();
8740  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8741  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8742  DebugLoc dl = Op.getDebugLoc();
8743
8744  if (isFP) {
8745#ifndef NDEBUG
8746    EVT EltVT = Op0.getValueType().getVectorElementType();
8747    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8748#endif
8749
8750    unsigned SSECC;
8751    bool Swap = false;
8752
8753    // SSE Condition code mapping:
8754    //  0 - EQ
8755    //  1 - LT
8756    //  2 - LE
8757    //  3 - UNORD
8758    //  4 - NEQ
8759    //  5 - NLT
8760    //  6 - NLE
8761    //  7 - ORD
8762    switch (SetCCOpcode) {
8763    default: llvm_unreachable("Unexpected SETCC condition");
8764    case ISD::SETOEQ:
8765    case ISD::SETEQ:  SSECC = 0; break;
8766    case ISD::SETOGT:
8767    case ISD::SETGT: Swap = true; // Fallthrough
8768    case ISD::SETLT:
8769    case ISD::SETOLT: SSECC = 1; break;
8770    case ISD::SETOGE:
8771    case ISD::SETGE: Swap = true; // Fallthrough
8772    case ISD::SETLE:
8773    case ISD::SETOLE: SSECC = 2; break;
8774    case ISD::SETUO:  SSECC = 3; break;
8775    case ISD::SETUNE:
8776    case ISD::SETNE:  SSECC = 4; break;
8777    case ISD::SETULE: Swap = true; // Fallthrough
8778    case ISD::SETUGE: SSECC = 5; break;
8779    case ISD::SETULT: Swap = true; // Fallthrough
8780    case ISD::SETUGT: SSECC = 6; break;
8781    case ISD::SETO:   SSECC = 7; break;
8782    case ISD::SETUEQ:
8783    case ISD::SETONE: SSECC = 8; break;
8784    }
8785    if (Swap)
8786      std::swap(Op0, Op1);
8787
8788    // In the two special cases we can't handle, emit two comparisons.
8789    if (SSECC == 8) {
8790      unsigned CC0, CC1;
8791      unsigned CombineOpc;
8792      if (SetCCOpcode == ISD::SETUEQ) {
8793        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8794      } else {
8795        assert(SetCCOpcode == ISD::SETONE);
8796        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8797      }
8798
8799      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8800                                 DAG.getConstant(CC0, MVT::i8));
8801      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8802                                 DAG.getConstant(CC1, MVT::i8));
8803      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8804    }
8805    // Handle all other FP comparisons here.
8806    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8807                       DAG.getConstant(SSECC, MVT::i8));
8808  }
8809
8810  // Break 256-bit integer vector compare into smaller ones.
8811  if (VT.is256BitVector() && !Subtarget->hasAVX2())
8812    return Lower256IntVSETCC(Op, DAG);
8813
8814  // We are handling one of the integer comparisons here.  Since SSE only has
8815  // GT and EQ comparisons for integer, swapping operands and multiple
8816  // operations may be required for some comparisons.
8817  unsigned Opc;
8818  bool Swap = false, Invert = false, FlipSigns = false;
8819
8820  switch (SetCCOpcode) {
8821  default: llvm_unreachable("Unexpected SETCC condition");
8822  case ISD::SETNE:  Invert = true;
8823  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8824  case ISD::SETLT:  Swap = true;
8825  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8826  case ISD::SETGE:  Swap = true;
8827  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8828  case ISD::SETULT: Swap = true;
8829  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8830  case ISD::SETUGE: Swap = true;
8831  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8832  }
8833  if (Swap)
8834    std::swap(Op0, Op1);
8835
8836  // Check that the operation in question is available (most are plain SSE2,
8837  // but PCMPGTQ and PCMPEQQ have different requirements).
8838  if (VT == MVT::v2i64) {
8839    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8840      return SDValue();
8841    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8842      return SDValue();
8843  }
8844
8845  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8846  // bits of the inputs before performing those operations.
8847  if (FlipSigns) {
8848    EVT EltVT = VT.getVectorElementType();
8849    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8850                                      EltVT);
8851    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8852    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8853                                    SignBits.size());
8854    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8855    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8856  }
8857
8858  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8859
8860  // If the logical-not of the result is required, perform that now.
8861  if (Invert)
8862    Result = DAG.getNOT(dl, Result, VT);
8863
8864  return Result;
8865}
8866
8867// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8868static bool isX86LogicalCmp(SDValue Op) {
8869  unsigned Opc = Op.getNode()->getOpcode();
8870  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8871      Opc == X86ISD::SAHF)
8872    return true;
8873  if (Op.getResNo() == 1 &&
8874      (Opc == X86ISD::ADD ||
8875       Opc == X86ISD::SUB ||
8876       Opc == X86ISD::ADC ||
8877       Opc == X86ISD::SBB ||
8878       Opc == X86ISD::SMUL ||
8879       Opc == X86ISD::UMUL ||
8880       Opc == X86ISD::INC ||
8881       Opc == X86ISD::DEC ||
8882       Opc == X86ISD::OR ||
8883       Opc == X86ISD::XOR ||
8884       Opc == X86ISD::AND))
8885    return true;
8886
8887  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8888    return true;
8889
8890  return false;
8891}
8892
8893static bool isZero(SDValue V) {
8894  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8895  return C && C->isNullValue();
8896}
8897
8898static bool isAllOnes(SDValue V) {
8899  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8900  return C && C->isAllOnesValue();
8901}
8902
8903static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8904  if (V.getOpcode() != ISD::TRUNCATE)
8905    return false;
8906
8907  SDValue VOp0 = V.getOperand(0);
8908  unsigned InBits = VOp0.getValueSizeInBits();
8909  unsigned Bits = V.getValueSizeInBits();
8910  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8911}
8912
8913SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8914  bool addTest = true;
8915  SDValue Cond  = Op.getOperand(0);
8916  SDValue Op1 = Op.getOperand(1);
8917  SDValue Op2 = Op.getOperand(2);
8918  DebugLoc DL = Op.getDebugLoc();
8919  SDValue CC;
8920
8921  if (Cond.getOpcode() == ISD::SETCC) {
8922    SDValue NewCond = LowerSETCC(Cond, DAG);
8923    if (NewCond.getNode())
8924      Cond = NewCond;
8925  }
8926
8927  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8928  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8929  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8930  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8931  if (Cond.getOpcode() == X86ISD::SETCC &&
8932      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8933      isZero(Cond.getOperand(1).getOperand(1))) {
8934    SDValue Cmp = Cond.getOperand(1);
8935
8936    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8937
8938    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8939        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8940      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8941
8942      SDValue CmpOp0 = Cmp.getOperand(0);
8943      // Apply further optimizations for special cases
8944      // (select (x != 0), -1, 0) -> neg & sbb
8945      // (select (x == 0), 0, -1) -> neg & sbb
8946      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8947        if (YC->isNullValue() &&
8948            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8949          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8950          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8951                                    DAG.getConstant(0, CmpOp0.getValueType()),
8952                                    CmpOp0);
8953          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8954                                    DAG.getConstant(X86::COND_B, MVT::i8),
8955                                    SDValue(Neg.getNode(), 1));
8956          return Res;
8957        }
8958
8959      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8960                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8961      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8962
8963      SDValue Res =   // Res = 0 or -1.
8964        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8965                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8966
8967      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8968        Res = DAG.getNOT(DL, Res, Res.getValueType());
8969
8970      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8971      if (N2C == 0 || !N2C->isNullValue())
8972        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8973      return Res;
8974    }
8975  }
8976
8977  // Look past (and (setcc_carry (cmp ...)), 1).
8978  if (Cond.getOpcode() == ISD::AND &&
8979      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8980    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8981    if (C && C->getAPIntValue() == 1)
8982      Cond = Cond.getOperand(0);
8983  }
8984
8985  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8986  // setting operand in place of the X86ISD::SETCC.
8987  unsigned CondOpcode = Cond.getOpcode();
8988  if (CondOpcode == X86ISD::SETCC ||
8989      CondOpcode == X86ISD::SETCC_CARRY) {
8990    CC = Cond.getOperand(0);
8991
8992    SDValue Cmp = Cond.getOperand(1);
8993    unsigned Opc = Cmp.getOpcode();
8994    EVT VT = Op.getValueType();
8995
8996    bool IllegalFPCMov = false;
8997    if (VT.isFloatingPoint() && !VT.isVector() &&
8998        !isScalarFPTypeInSSEReg(VT))  // FPStack?
8999      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9000
9001    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9002        Opc == X86ISD::BT) { // FIXME
9003      Cond = Cmp;
9004      addTest = false;
9005    }
9006  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9007             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9008             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9009              Cond.getOperand(0).getValueType() != MVT::i8)) {
9010    SDValue LHS = Cond.getOperand(0);
9011    SDValue RHS = Cond.getOperand(1);
9012    unsigned X86Opcode;
9013    unsigned X86Cond;
9014    SDVTList VTs;
9015    switch (CondOpcode) {
9016    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9017    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9018    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9019    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9020    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9021    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9022    default: llvm_unreachable("unexpected overflowing operator");
9023    }
9024    if (CondOpcode == ISD::UMULO)
9025      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9026                          MVT::i32);
9027    else
9028      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9029
9030    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9031
9032    if (CondOpcode == ISD::UMULO)
9033      Cond = X86Op.getValue(2);
9034    else
9035      Cond = X86Op.getValue(1);
9036
9037    CC = DAG.getConstant(X86Cond, MVT::i8);
9038    addTest = false;
9039  }
9040
9041  if (addTest) {
9042    // Look pass the truncate if the high bits are known zero.
9043    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9044        Cond = Cond.getOperand(0);
9045
9046    // We know the result of AND is compared against zero. Try to match
9047    // it to BT.
9048    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9049      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9050      if (NewSetCC.getNode()) {
9051        CC = NewSetCC.getOperand(0);
9052        Cond = NewSetCC.getOperand(1);
9053        addTest = false;
9054      }
9055    }
9056  }
9057
9058  if (addTest) {
9059    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9060    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9061  }
9062
9063  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9064  // a <  b ?  0 : -1 -> RES = setcc_carry
9065  // a >= b ? -1 :  0 -> RES = setcc_carry
9066  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9067  if (Cond.getOpcode() == X86ISD::SUB) {
9068    Cond = ConvertCmpIfNecessary(Cond, DAG);
9069    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9070
9071    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9072        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9073      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9074                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9075      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9076        return DAG.getNOT(DL, Res, Res.getValueType());
9077      return Res;
9078    }
9079  }
9080
9081  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9082  // condition is true.
9083  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9084  SDValue Ops[] = { Op2, Op1, CC, Cond };
9085  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9086}
9087
9088// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9089// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9090// from the AND / OR.
9091static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9092  Opc = Op.getOpcode();
9093  if (Opc != ISD::OR && Opc != ISD::AND)
9094    return false;
9095  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9096          Op.getOperand(0).hasOneUse() &&
9097          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9098          Op.getOperand(1).hasOneUse());
9099}
9100
9101// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9102// 1 and that the SETCC node has a single use.
9103static bool isXor1OfSetCC(SDValue Op) {
9104  if (Op.getOpcode() != ISD::XOR)
9105    return false;
9106  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9107  if (N1C && N1C->getAPIntValue() == 1) {
9108    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9109      Op.getOperand(0).hasOneUse();
9110  }
9111  return false;
9112}
9113
9114SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9115  bool addTest = true;
9116  SDValue Chain = Op.getOperand(0);
9117  SDValue Cond  = Op.getOperand(1);
9118  SDValue Dest  = Op.getOperand(2);
9119  DebugLoc dl = Op.getDebugLoc();
9120  SDValue CC;
9121  bool Inverted = false;
9122
9123  if (Cond.getOpcode() == ISD::SETCC) {
9124    // Check for setcc([su]{add,sub,mul}o == 0).
9125    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9126        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9127        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9128        Cond.getOperand(0).getResNo() == 1 &&
9129        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9130         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9131         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9132         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9133         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9134         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9135      Inverted = true;
9136      Cond = Cond.getOperand(0);
9137    } else {
9138      SDValue NewCond = LowerSETCC(Cond, DAG);
9139      if (NewCond.getNode())
9140        Cond = NewCond;
9141    }
9142  }
9143#if 0
9144  // FIXME: LowerXALUO doesn't handle these!!
9145  else if (Cond.getOpcode() == X86ISD::ADD  ||
9146           Cond.getOpcode() == X86ISD::SUB  ||
9147           Cond.getOpcode() == X86ISD::SMUL ||
9148           Cond.getOpcode() == X86ISD::UMUL)
9149    Cond = LowerXALUO(Cond, DAG);
9150#endif
9151
9152  // Look pass (and (setcc_carry (cmp ...)), 1).
9153  if (Cond.getOpcode() == ISD::AND &&
9154      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9155    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9156    if (C && C->getAPIntValue() == 1)
9157      Cond = Cond.getOperand(0);
9158  }
9159
9160  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9161  // setting operand in place of the X86ISD::SETCC.
9162  unsigned CondOpcode = Cond.getOpcode();
9163  if (CondOpcode == X86ISD::SETCC ||
9164      CondOpcode == X86ISD::SETCC_CARRY) {
9165    CC = Cond.getOperand(0);
9166
9167    SDValue Cmp = Cond.getOperand(1);
9168    unsigned Opc = Cmp.getOpcode();
9169    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9170    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9171      Cond = Cmp;
9172      addTest = false;
9173    } else {
9174      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9175      default: break;
9176      case X86::COND_O:
9177      case X86::COND_B:
9178        // These can only come from an arithmetic instruction with overflow,
9179        // e.g. SADDO, UADDO.
9180        Cond = Cond.getNode()->getOperand(1);
9181        addTest = false;
9182        break;
9183      }
9184    }
9185  }
9186  CondOpcode = Cond.getOpcode();
9187  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9188      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9189      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9190       Cond.getOperand(0).getValueType() != MVT::i8)) {
9191    SDValue LHS = Cond.getOperand(0);
9192    SDValue RHS = Cond.getOperand(1);
9193    unsigned X86Opcode;
9194    unsigned X86Cond;
9195    SDVTList VTs;
9196    switch (CondOpcode) {
9197    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9198    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9199    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9200    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9201    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9202    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9203    default: llvm_unreachable("unexpected overflowing operator");
9204    }
9205    if (Inverted)
9206      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9207    if (CondOpcode == ISD::UMULO)
9208      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9209                          MVT::i32);
9210    else
9211      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9212
9213    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9214
9215    if (CondOpcode == ISD::UMULO)
9216      Cond = X86Op.getValue(2);
9217    else
9218      Cond = X86Op.getValue(1);
9219
9220    CC = DAG.getConstant(X86Cond, MVT::i8);
9221    addTest = false;
9222  } else {
9223    unsigned CondOpc;
9224    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9225      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9226      if (CondOpc == ISD::OR) {
9227        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9228        // two branches instead of an explicit OR instruction with a
9229        // separate test.
9230        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9231            isX86LogicalCmp(Cmp)) {
9232          CC = Cond.getOperand(0).getOperand(0);
9233          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9234                              Chain, Dest, CC, Cmp);
9235          CC = Cond.getOperand(1).getOperand(0);
9236          Cond = Cmp;
9237          addTest = false;
9238        }
9239      } else { // ISD::AND
9240        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9241        // two branches instead of an explicit AND instruction with a
9242        // separate test. However, we only do this if this block doesn't
9243        // have a fall-through edge, because this requires an explicit
9244        // jmp when the condition is false.
9245        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9246            isX86LogicalCmp(Cmp) &&
9247            Op.getNode()->hasOneUse()) {
9248          X86::CondCode CCode =
9249            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9250          CCode = X86::GetOppositeBranchCondition(CCode);
9251          CC = DAG.getConstant(CCode, MVT::i8);
9252          SDNode *User = *Op.getNode()->use_begin();
9253          // Look for an unconditional branch following this conditional branch.
9254          // We need this because we need to reverse the successors in order
9255          // to implement FCMP_OEQ.
9256          if (User->getOpcode() == ISD::BR) {
9257            SDValue FalseBB = User->getOperand(1);
9258            SDNode *NewBR =
9259              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9260            assert(NewBR == User);
9261            (void)NewBR;
9262            Dest = FalseBB;
9263
9264            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9265                                Chain, Dest, CC, Cmp);
9266            X86::CondCode CCode =
9267              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9268            CCode = X86::GetOppositeBranchCondition(CCode);
9269            CC = DAG.getConstant(CCode, MVT::i8);
9270            Cond = Cmp;
9271            addTest = false;
9272          }
9273        }
9274      }
9275    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9276      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9277      // It should be transformed during dag combiner except when the condition
9278      // is set by a arithmetics with overflow node.
9279      X86::CondCode CCode =
9280        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9281      CCode = X86::GetOppositeBranchCondition(CCode);
9282      CC = DAG.getConstant(CCode, MVT::i8);
9283      Cond = Cond.getOperand(0).getOperand(1);
9284      addTest = false;
9285    } else if (Cond.getOpcode() == ISD::SETCC &&
9286               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9287      // For FCMP_OEQ, we can emit
9288      // two branches instead of an explicit AND instruction with a
9289      // separate test. However, we only do this if this block doesn't
9290      // have a fall-through edge, because this requires an explicit
9291      // jmp when the condition is false.
9292      if (Op.getNode()->hasOneUse()) {
9293        SDNode *User = *Op.getNode()->use_begin();
9294        // Look for an unconditional branch following this conditional branch.
9295        // We need this because we need to reverse the successors in order
9296        // to implement FCMP_OEQ.
9297        if (User->getOpcode() == ISD::BR) {
9298          SDValue FalseBB = User->getOperand(1);
9299          SDNode *NewBR =
9300            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9301          assert(NewBR == User);
9302          (void)NewBR;
9303          Dest = FalseBB;
9304
9305          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9306                                    Cond.getOperand(0), Cond.getOperand(1));
9307          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9308          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9309          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9310                              Chain, Dest, CC, Cmp);
9311          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9312          Cond = Cmp;
9313          addTest = false;
9314        }
9315      }
9316    } else if (Cond.getOpcode() == ISD::SETCC &&
9317               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9318      // For FCMP_UNE, we can emit
9319      // two branches instead of an explicit AND instruction with a
9320      // separate test. However, we only do this if this block doesn't
9321      // have a fall-through edge, because this requires an explicit
9322      // jmp when the condition is false.
9323      if (Op.getNode()->hasOneUse()) {
9324        SDNode *User = *Op.getNode()->use_begin();
9325        // Look for an unconditional branch following this conditional branch.
9326        // We need this because we need to reverse the successors in order
9327        // to implement FCMP_UNE.
9328        if (User->getOpcode() == ISD::BR) {
9329          SDValue FalseBB = User->getOperand(1);
9330          SDNode *NewBR =
9331            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9332          assert(NewBR == User);
9333          (void)NewBR;
9334
9335          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9336                                    Cond.getOperand(0), Cond.getOperand(1));
9337          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9338          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9339          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9340                              Chain, Dest, CC, Cmp);
9341          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9342          Cond = Cmp;
9343          addTest = false;
9344          Dest = FalseBB;
9345        }
9346      }
9347    }
9348  }
9349
9350  if (addTest) {
9351    // Look pass the truncate if the high bits are known zero.
9352    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9353        Cond = Cond.getOperand(0);
9354
9355    // We know the result of AND is compared against zero. Try to match
9356    // it to BT.
9357    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9358      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9359      if (NewSetCC.getNode()) {
9360        CC = NewSetCC.getOperand(0);
9361        Cond = NewSetCC.getOperand(1);
9362        addTest = false;
9363      }
9364    }
9365  }
9366
9367  if (addTest) {
9368    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9369    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9370  }
9371  Cond = ConvertCmpIfNecessary(Cond, DAG);
9372  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9373                     Chain, Dest, CC, Cond);
9374}
9375
9376
9377// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9378// Calls to _alloca is needed to probe the stack when allocating more than 4k
9379// bytes in one go. Touching the stack at 4K increments is necessary to ensure
9380// that the guard pages used by the OS virtual memory manager are allocated in
9381// correct sequence.
9382SDValue
9383X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9384                                           SelectionDAG &DAG) const {
9385  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9386          getTargetMachine().Options.EnableSegmentedStacks) &&
9387         "This should be used only on Windows targets or when segmented stacks "
9388         "are being used");
9389  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9390  DebugLoc dl = Op.getDebugLoc();
9391
9392  // Get the inputs.
9393  SDValue Chain = Op.getOperand(0);
9394  SDValue Size  = Op.getOperand(1);
9395  // FIXME: Ensure alignment here
9396
9397  bool Is64Bit = Subtarget->is64Bit();
9398  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9399
9400  if (getTargetMachine().Options.EnableSegmentedStacks) {
9401    MachineFunction &MF = DAG.getMachineFunction();
9402    MachineRegisterInfo &MRI = MF.getRegInfo();
9403
9404    if (Is64Bit) {
9405      // The 64 bit implementation of segmented stacks needs to clobber both r10
9406      // r11. This makes it impossible to use it along with nested parameters.
9407      const Function *F = MF.getFunction();
9408
9409      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9410           I != E; ++I)
9411        if (I->hasNestAttr())
9412          report_fatal_error("Cannot use segmented stacks with functions that "
9413                             "have nested arguments.");
9414    }
9415
9416    const TargetRegisterClass *AddrRegClass =
9417      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9418    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9419    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9420    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9421                                DAG.getRegister(Vreg, SPTy));
9422    SDValue Ops1[2] = { Value, Chain };
9423    return DAG.getMergeValues(Ops1, 2, dl);
9424  } else {
9425    SDValue Flag;
9426    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9427
9428    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9429    Flag = Chain.getValue(1);
9430    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9431
9432    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9433    Flag = Chain.getValue(1);
9434
9435    Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9436
9437    SDValue Ops1[2] = { Chain.getValue(0), Chain };
9438    return DAG.getMergeValues(Ops1, 2, dl);
9439  }
9440}
9441
9442SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9443  MachineFunction &MF = DAG.getMachineFunction();
9444  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9445
9446  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9447  DebugLoc DL = Op.getDebugLoc();
9448
9449  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9450    // vastart just stores the address of the VarArgsFrameIndex slot into the
9451    // memory location argument.
9452    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9453                                   getPointerTy());
9454    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9455                        MachinePointerInfo(SV), false, false, 0);
9456  }
9457
9458  // __va_list_tag:
9459  //   gp_offset         (0 - 6 * 8)
9460  //   fp_offset         (48 - 48 + 8 * 16)
9461  //   overflow_arg_area (point to parameters coming in memory).
9462  //   reg_save_area
9463  SmallVector<SDValue, 8> MemOps;
9464  SDValue FIN = Op.getOperand(1);
9465  // Store gp_offset
9466  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9467                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9468                                               MVT::i32),
9469                               FIN, MachinePointerInfo(SV), false, false, 0);
9470  MemOps.push_back(Store);
9471
9472  // Store fp_offset
9473  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9474                    FIN, DAG.getIntPtrConstant(4));
9475  Store = DAG.getStore(Op.getOperand(0), DL,
9476                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9477                                       MVT::i32),
9478                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
9479  MemOps.push_back(Store);
9480
9481  // Store ptr to overflow_arg_area
9482  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9483                    FIN, DAG.getIntPtrConstant(4));
9484  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9485                                    getPointerTy());
9486  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9487                       MachinePointerInfo(SV, 8),
9488                       false, false, 0);
9489  MemOps.push_back(Store);
9490
9491  // Store ptr to reg_save_area.
9492  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9493                    FIN, DAG.getIntPtrConstant(8));
9494  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9495                                    getPointerTy());
9496  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9497                       MachinePointerInfo(SV, 16), false, false, 0);
9498  MemOps.push_back(Store);
9499  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9500                     &MemOps[0], MemOps.size());
9501}
9502
9503SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9504  assert(Subtarget->is64Bit() &&
9505         "LowerVAARG only handles 64-bit va_arg!");
9506  assert((Subtarget->isTargetLinux() ||
9507          Subtarget->isTargetDarwin()) &&
9508          "Unhandled target in LowerVAARG");
9509  assert(Op.getNode()->getNumOperands() == 4);
9510  SDValue Chain = Op.getOperand(0);
9511  SDValue SrcPtr = Op.getOperand(1);
9512  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9513  unsigned Align = Op.getConstantOperandVal(3);
9514  DebugLoc dl = Op.getDebugLoc();
9515
9516  EVT ArgVT = Op.getNode()->getValueType(0);
9517  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9518  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9519  uint8_t ArgMode;
9520
9521  // Decide which area this value should be read from.
9522  // TODO: Implement the AMD64 ABI in its entirety. This simple
9523  // selection mechanism works only for the basic types.
9524  if (ArgVT == MVT::f80) {
9525    llvm_unreachable("va_arg for f80 not yet implemented");
9526  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9527    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9528  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9529    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9530  } else {
9531    llvm_unreachable("Unhandled argument type in LowerVAARG");
9532  }
9533
9534  if (ArgMode == 2) {
9535    // Sanity Check: Make sure using fp_offset makes sense.
9536    assert(!getTargetMachine().Options.UseSoftFloat &&
9537           !(DAG.getMachineFunction()
9538                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9539           Subtarget->hasSSE1());
9540  }
9541
9542  // Insert VAARG_64 node into the DAG
9543  // VAARG_64 returns two values: Variable Argument Address, Chain
9544  SmallVector<SDValue, 11> InstOps;
9545  InstOps.push_back(Chain);
9546  InstOps.push_back(SrcPtr);
9547  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9548  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9549  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9550  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9551  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9552                                          VTs, &InstOps[0], InstOps.size(),
9553                                          MVT::i64,
9554                                          MachinePointerInfo(SV),
9555                                          /*Align=*/0,
9556                                          /*Volatile=*/false,
9557                                          /*ReadMem=*/true,
9558                                          /*WriteMem=*/true);
9559  Chain = VAARG.getValue(1);
9560
9561  // Load the next argument and return it
9562  return DAG.getLoad(ArgVT, dl,
9563                     Chain,
9564                     VAARG,
9565                     MachinePointerInfo(),
9566                     false, false, false, 0);
9567}
9568
9569SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9570  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9571  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9572  SDValue Chain = Op.getOperand(0);
9573  SDValue DstPtr = Op.getOperand(1);
9574  SDValue SrcPtr = Op.getOperand(2);
9575  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9576  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9577  DebugLoc DL = Op.getDebugLoc();
9578
9579  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9580                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9581                       false,
9582                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9583}
9584
9585// getTargetVShiftNOde - Handle vector element shifts where the shift amount
9586// may or may not be a constant. Takes immediate version of shift as input.
9587static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9588                                   SDValue SrcOp, SDValue ShAmt,
9589                                   SelectionDAG &DAG) {
9590  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9591
9592  if (isa<ConstantSDNode>(ShAmt)) {
9593    // Constant may be a TargetConstant. Use a regular constant.
9594    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9595    switch (Opc) {
9596      default: llvm_unreachable("Unknown target vector shift node");
9597      case X86ISD::VSHLI:
9598      case X86ISD::VSRLI:
9599      case X86ISD::VSRAI:
9600        return DAG.getNode(Opc, dl, VT, SrcOp,
9601                           DAG.getConstant(ShiftAmt, MVT::i32));
9602    }
9603  }
9604
9605  // Change opcode to non-immediate version
9606  switch (Opc) {
9607    default: llvm_unreachable("Unknown target vector shift node");
9608    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9609    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9610    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9611  }
9612
9613  // Need to build a vector containing shift amount
9614  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9615  SDValue ShOps[4];
9616  ShOps[0] = ShAmt;
9617  ShOps[1] = DAG.getConstant(0, MVT::i32);
9618  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9619  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9620
9621  // The return type has to be a 128-bit type with the same element
9622  // type as the input type.
9623  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9624  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9625
9626  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9627  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9628}
9629
9630SDValue
9631X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9632  DebugLoc dl = Op.getDebugLoc();
9633  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9634  switch (IntNo) {
9635  default: return SDValue();    // Don't custom lower most intrinsics.
9636  // Comparison intrinsics.
9637  case Intrinsic::x86_sse_comieq_ss:
9638  case Intrinsic::x86_sse_comilt_ss:
9639  case Intrinsic::x86_sse_comile_ss:
9640  case Intrinsic::x86_sse_comigt_ss:
9641  case Intrinsic::x86_sse_comige_ss:
9642  case Intrinsic::x86_sse_comineq_ss:
9643  case Intrinsic::x86_sse_ucomieq_ss:
9644  case Intrinsic::x86_sse_ucomilt_ss:
9645  case Intrinsic::x86_sse_ucomile_ss:
9646  case Intrinsic::x86_sse_ucomigt_ss:
9647  case Intrinsic::x86_sse_ucomige_ss:
9648  case Intrinsic::x86_sse_ucomineq_ss:
9649  case Intrinsic::x86_sse2_comieq_sd:
9650  case Intrinsic::x86_sse2_comilt_sd:
9651  case Intrinsic::x86_sse2_comile_sd:
9652  case Intrinsic::x86_sse2_comigt_sd:
9653  case Intrinsic::x86_sse2_comige_sd:
9654  case Intrinsic::x86_sse2_comineq_sd:
9655  case Intrinsic::x86_sse2_ucomieq_sd:
9656  case Intrinsic::x86_sse2_ucomilt_sd:
9657  case Intrinsic::x86_sse2_ucomile_sd:
9658  case Intrinsic::x86_sse2_ucomigt_sd:
9659  case Intrinsic::x86_sse2_ucomige_sd:
9660  case Intrinsic::x86_sse2_ucomineq_sd: {
9661    unsigned Opc;
9662    ISD::CondCode CC;
9663    switch (IntNo) {
9664    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9665    case Intrinsic::x86_sse_comieq_ss:
9666    case Intrinsic::x86_sse2_comieq_sd:
9667      Opc = X86ISD::COMI;
9668      CC = ISD::SETEQ;
9669      break;
9670    case Intrinsic::x86_sse_comilt_ss:
9671    case Intrinsic::x86_sse2_comilt_sd:
9672      Opc = X86ISD::COMI;
9673      CC = ISD::SETLT;
9674      break;
9675    case Intrinsic::x86_sse_comile_ss:
9676    case Intrinsic::x86_sse2_comile_sd:
9677      Opc = X86ISD::COMI;
9678      CC = ISD::SETLE;
9679      break;
9680    case Intrinsic::x86_sse_comigt_ss:
9681    case Intrinsic::x86_sse2_comigt_sd:
9682      Opc = X86ISD::COMI;
9683      CC = ISD::SETGT;
9684      break;
9685    case Intrinsic::x86_sse_comige_ss:
9686    case Intrinsic::x86_sse2_comige_sd:
9687      Opc = X86ISD::COMI;
9688      CC = ISD::SETGE;
9689      break;
9690    case Intrinsic::x86_sse_comineq_ss:
9691    case Intrinsic::x86_sse2_comineq_sd:
9692      Opc = X86ISD::COMI;
9693      CC = ISD::SETNE;
9694      break;
9695    case Intrinsic::x86_sse_ucomieq_ss:
9696    case Intrinsic::x86_sse2_ucomieq_sd:
9697      Opc = X86ISD::UCOMI;
9698      CC = ISD::SETEQ;
9699      break;
9700    case Intrinsic::x86_sse_ucomilt_ss:
9701    case Intrinsic::x86_sse2_ucomilt_sd:
9702      Opc = X86ISD::UCOMI;
9703      CC = ISD::SETLT;
9704      break;
9705    case Intrinsic::x86_sse_ucomile_ss:
9706    case Intrinsic::x86_sse2_ucomile_sd:
9707      Opc = X86ISD::UCOMI;
9708      CC = ISD::SETLE;
9709      break;
9710    case Intrinsic::x86_sse_ucomigt_ss:
9711    case Intrinsic::x86_sse2_ucomigt_sd:
9712      Opc = X86ISD::UCOMI;
9713      CC = ISD::SETGT;
9714      break;
9715    case Intrinsic::x86_sse_ucomige_ss:
9716    case Intrinsic::x86_sse2_ucomige_sd:
9717      Opc = X86ISD::UCOMI;
9718      CC = ISD::SETGE;
9719      break;
9720    case Intrinsic::x86_sse_ucomineq_ss:
9721    case Intrinsic::x86_sse2_ucomineq_sd:
9722      Opc = X86ISD::UCOMI;
9723      CC = ISD::SETNE;
9724      break;
9725    }
9726
9727    SDValue LHS = Op.getOperand(1);
9728    SDValue RHS = Op.getOperand(2);
9729    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9730    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9731    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9732    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9733                                DAG.getConstant(X86CC, MVT::i8), Cond);
9734    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9735  }
9736
9737  // Arithmetic intrinsics.
9738  case Intrinsic::x86_sse2_pmulu_dq:
9739  case Intrinsic::x86_avx2_pmulu_dq:
9740    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9741                       Op.getOperand(1), Op.getOperand(2));
9742
9743  // SSE3/AVX horizontal add/sub intrinsics
9744  case Intrinsic::x86_sse3_hadd_ps:
9745  case Intrinsic::x86_sse3_hadd_pd:
9746  case Intrinsic::x86_avx_hadd_ps_256:
9747  case Intrinsic::x86_avx_hadd_pd_256:
9748  case Intrinsic::x86_sse3_hsub_ps:
9749  case Intrinsic::x86_sse3_hsub_pd:
9750  case Intrinsic::x86_avx_hsub_ps_256:
9751  case Intrinsic::x86_avx_hsub_pd_256:
9752  case Intrinsic::x86_ssse3_phadd_w_128:
9753  case Intrinsic::x86_ssse3_phadd_d_128:
9754  case Intrinsic::x86_avx2_phadd_w:
9755  case Intrinsic::x86_avx2_phadd_d:
9756  case Intrinsic::x86_ssse3_phsub_w_128:
9757  case Intrinsic::x86_ssse3_phsub_d_128:
9758  case Intrinsic::x86_avx2_phsub_w:
9759  case Intrinsic::x86_avx2_phsub_d: {
9760    unsigned Opcode;
9761    switch (IntNo) {
9762    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9763    case Intrinsic::x86_sse3_hadd_ps:
9764    case Intrinsic::x86_sse3_hadd_pd:
9765    case Intrinsic::x86_avx_hadd_ps_256:
9766    case Intrinsic::x86_avx_hadd_pd_256:
9767      Opcode = X86ISD::FHADD;
9768      break;
9769    case Intrinsic::x86_sse3_hsub_ps:
9770    case Intrinsic::x86_sse3_hsub_pd:
9771    case Intrinsic::x86_avx_hsub_ps_256:
9772    case Intrinsic::x86_avx_hsub_pd_256:
9773      Opcode = X86ISD::FHSUB;
9774      break;
9775    case Intrinsic::x86_ssse3_phadd_w_128:
9776    case Intrinsic::x86_ssse3_phadd_d_128:
9777    case Intrinsic::x86_avx2_phadd_w:
9778    case Intrinsic::x86_avx2_phadd_d:
9779      Opcode = X86ISD::HADD;
9780      break;
9781    case Intrinsic::x86_ssse3_phsub_w_128:
9782    case Intrinsic::x86_ssse3_phsub_d_128:
9783    case Intrinsic::x86_avx2_phsub_w:
9784    case Intrinsic::x86_avx2_phsub_d:
9785      Opcode = X86ISD::HSUB;
9786      break;
9787    }
9788    return DAG.getNode(Opcode, dl, Op.getValueType(),
9789                       Op.getOperand(1), Op.getOperand(2));
9790  }
9791
9792  // AVX2 variable shift intrinsics
9793  case Intrinsic::x86_avx2_psllv_d:
9794  case Intrinsic::x86_avx2_psllv_q:
9795  case Intrinsic::x86_avx2_psllv_d_256:
9796  case Intrinsic::x86_avx2_psllv_q_256:
9797  case Intrinsic::x86_avx2_psrlv_d:
9798  case Intrinsic::x86_avx2_psrlv_q:
9799  case Intrinsic::x86_avx2_psrlv_d_256:
9800  case Intrinsic::x86_avx2_psrlv_q_256:
9801  case Intrinsic::x86_avx2_psrav_d:
9802  case Intrinsic::x86_avx2_psrav_d_256: {
9803    unsigned Opcode;
9804    switch (IntNo) {
9805    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9806    case Intrinsic::x86_avx2_psllv_d:
9807    case Intrinsic::x86_avx2_psllv_q:
9808    case Intrinsic::x86_avx2_psllv_d_256:
9809    case Intrinsic::x86_avx2_psllv_q_256:
9810      Opcode = ISD::SHL;
9811      break;
9812    case Intrinsic::x86_avx2_psrlv_d:
9813    case Intrinsic::x86_avx2_psrlv_q:
9814    case Intrinsic::x86_avx2_psrlv_d_256:
9815    case Intrinsic::x86_avx2_psrlv_q_256:
9816      Opcode = ISD::SRL;
9817      break;
9818    case Intrinsic::x86_avx2_psrav_d:
9819    case Intrinsic::x86_avx2_psrav_d_256:
9820      Opcode = ISD::SRA;
9821      break;
9822    }
9823    return DAG.getNode(Opcode, dl, Op.getValueType(),
9824                       Op.getOperand(1), Op.getOperand(2));
9825  }
9826
9827  case Intrinsic::x86_ssse3_pshuf_b_128:
9828  case Intrinsic::x86_avx2_pshuf_b:
9829    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9830                       Op.getOperand(1), Op.getOperand(2));
9831
9832  case Intrinsic::x86_ssse3_psign_b_128:
9833  case Intrinsic::x86_ssse3_psign_w_128:
9834  case Intrinsic::x86_ssse3_psign_d_128:
9835  case Intrinsic::x86_avx2_psign_b:
9836  case Intrinsic::x86_avx2_psign_w:
9837  case Intrinsic::x86_avx2_psign_d:
9838    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9839                       Op.getOperand(1), Op.getOperand(2));
9840
9841  case Intrinsic::x86_sse41_insertps:
9842    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9843                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9844
9845  case Intrinsic::x86_avx_vperm2f128_ps_256:
9846  case Intrinsic::x86_avx_vperm2f128_pd_256:
9847  case Intrinsic::x86_avx_vperm2f128_si_256:
9848  case Intrinsic::x86_avx2_vperm2i128:
9849    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9850                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9851
9852  case Intrinsic::x86_avx2_permd:
9853  case Intrinsic::x86_avx2_permps:
9854    // Operands intentionally swapped. Mask is last operand to intrinsic,
9855    // but second operand for node/intruction.
9856    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9857                       Op.getOperand(2), Op.getOperand(1));
9858
9859  // ptest and testp intrinsics. The intrinsic these come from are designed to
9860  // return an integer value, not just an instruction so lower it to the ptest
9861  // or testp pattern and a setcc for the result.
9862  case Intrinsic::x86_sse41_ptestz:
9863  case Intrinsic::x86_sse41_ptestc:
9864  case Intrinsic::x86_sse41_ptestnzc:
9865  case Intrinsic::x86_avx_ptestz_256:
9866  case Intrinsic::x86_avx_ptestc_256:
9867  case Intrinsic::x86_avx_ptestnzc_256:
9868  case Intrinsic::x86_avx_vtestz_ps:
9869  case Intrinsic::x86_avx_vtestc_ps:
9870  case Intrinsic::x86_avx_vtestnzc_ps:
9871  case Intrinsic::x86_avx_vtestz_pd:
9872  case Intrinsic::x86_avx_vtestc_pd:
9873  case Intrinsic::x86_avx_vtestnzc_pd:
9874  case Intrinsic::x86_avx_vtestz_ps_256:
9875  case Intrinsic::x86_avx_vtestc_ps_256:
9876  case Intrinsic::x86_avx_vtestnzc_ps_256:
9877  case Intrinsic::x86_avx_vtestz_pd_256:
9878  case Intrinsic::x86_avx_vtestc_pd_256:
9879  case Intrinsic::x86_avx_vtestnzc_pd_256: {
9880    bool IsTestPacked = false;
9881    unsigned X86CC;
9882    switch (IntNo) {
9883    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9884    case Intrinsic::x86_avx_vtestz_ps:
9885    case Intrinsic::x86_avx_vtestz_pd:
9886    case Intrinsic::x86_avx_vtestz_ps_256:
9887    case Intrinsic::x86_avx_vtestz_pd_256:
9888      IsTestPacked = true; // Fallthrough
9889    case Intrinsic::x86_sse41_ptestz:
9890    case Intrinsic::x86_avx_ptestz_256:
9891      // ZF = 1
9892      X86CC = X86::COND_E;
9893      break;
9894    case Intrinsic::x86_avx_vtestc_ps:
9895    case Intrinsic::x86_avx_vtestc_pd:
9896    case Intrinsic::x86_avx_vtestc_ps_256:
9897    case Intrinsic::x86_avx_vtestc_pd_256:
9898      IsTestPacked = true; // Fallthrough
9899    case Intrinsic::x86_sse41_ptestc:
9900    case Intrinsic::x86_avx_ptestc_256:
9901      // CF = 1
9902      X86CC = X86::COND_B;
9903      break;
9904    case Intrinsic::x86_avx_vtestnzc_ps:
9905    case Intrinsic::x86_avx_vtestnzc_pd:
9906    case Intrinsic::x86_avx_vtestnzc_ps_256:
9907    case Intrinsic::x86_avx_vtestnzc_pd_256:
9908      IsTestPacked = true; // Fallthrough
9909    case Intrinsic::x86_sse41_ptestnzc:
9910    case Intrinsic::x86_avx_ptestnzc_256:
9911      // ZF and CF = 0
9912      X86CC = X86::COND_A;
9913      break;
9914    }
9915
9916    SDValue LHS = Op.getOperand(1);
9917    SDValue RHS = Op.getOperand(2);
9918    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9919    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9920    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9921    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9922    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9923  }
9924
9925  // SSE/AVX shift intrinsics
9926  case Intrinsic::x86_sse2_psll_w:
9927  case Intrinsic::x86_sse2_psll_d:
9928  case Intrinsic::x86_sse2_psll_q:
9929  case Intrinsic::x86_avx2_psll_w:
9930  case Intrinsic::x86_avx2_psll_d:
9931  case Intrinsic::x86_avx2_psll_q:
9932  case Intrinsic::x86_sse2_psrl_w:
9933  case Intrinsic::x86_sse2_psrl_d:
9934  case Intrinsic::x86_sse2_psrl_q:
9935  case Intrinsic::x86_avx2_psrl_w:
9936  case Intrinsic::x86_avx2_psrl_d:
9937  case Intrinsic::x86_avx2_psrl_q:
9938  case Intrinsic::x86_sse2_psra_w:
9939  case Intrinsic::x86_sse2_psra_d:
9940  case Intrinsic::x86_avx2_psra_w:
9941  case Intrinsic::x86_avx2_psra_d: {
9942    unsigned Opcode;
9943    switch (IntNo) {
9944    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9945    case Intrinsic::x86_sse2_psll_w:
9946    case Intrinsic::x86_sse2_psll_d:
9947    case Intrinsic::x86_sse2_psll_q:
9948    case Intrinsic::x86_avx2_psll_w:
9949    case Intrinsic::x86_avx2_psll_d:
9950    case Intrinsic::x86_avx2_psll_q:
9951      Opcode = X86ISD::VSHL;
9952      break;
9953    case Intrinsic::x86_sse2_psrl_w:
9954    case Intrinsic::x86_sse2_psrl_d:
9955    case Intrinsic::x86_sse2_psrl_q:
9956    case Intrinsic::x86_avx2_psrl_w:
9957    case Intrinsic::x86_avx2_psrl_d:
9958    case Intrinsic::x86_avx2_psrl_q:
9959      Opcode = X86ISD::VSRL;
9960      break;
9961    case Intrinsic::x86_sse2_psra_w:
9962    case Intrinsic::x86_sse2_psra_d:
9963    case Intrinsic::x86_avx2_psra_w:
9964    case Intrinsic::x86_avx2_psra_d:
9965      Opcode = X86ISD::VSRA;
9966      break;
9967    }
9968    return DAG.getNode(Opcode, dl, Op.getValueType(),
9969                       Op.getOperand(1), Op.getOperand(2));
9970  }
9971
9972  // SSE/AVX immediate shift intrinsics
9973  case Intrinsic::x86_sse2_pslli_w:
9974  case Intrinsic::x86_sse2_pslli_d:
9975  case Intrinsic::x86_sse2_pslli_q:
9976  case Intrinsic::x86_avx2_pslli_w:
9977  case Intrinsic::x86_avx2_pslli_d:
9978  case Intrinsic::x86_avx2_pslli_q:
9979  case Intrinsic::x86_sse2_psrli_w:
9980  case Intrinsic::x86_sse2_psrli_d:
9981  case Intrinsic::x86_sse2_psrli_q:
9982  case Intrinsic::x86_avx2_psrli_w:
9983  case Intrinsic::x86_avx2_psrli_d:
9984  case Intrinsic::x86_avx2_psrli_q:
9985  case Intrinsic::x86_sse2_psrai_w:
9986  case Intrinsic::x86_sse2_psrai_d:
9987  case Intrinsic::x86_avx2_psrai_w:
9988  case Intrinsic::x86_avx2_psrai_d: {
9989    unsigned Opcode;
9990    switch (IntNo) {
9991    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9992    case Intrinsic::x86_sse2_pslli_w:
9993    case Intrinsic::x86_sse2_pslli_d:
9994    case Intrinsic::x86_sse2_pslli_q:
9995    case Intrinsic::x86_avx2_pslli_w:
9996    case Intrinsic::x86_avx2_pslli_d:
9997    case Intrinsic::x86_avx2_pslli_q:
9998      Opcode = X86ISD::VSHLI;
9999      break;
10000    case Intrinsic::x86_sse2_psrli_w:
10001    case Intrinsic::x86_sse2_psrli_d:
10002    case Intrinsic::x86_sse2_psrli_q:
10003    case Intrinsic::x86_avx2_psrli_w:
10004    case Intrinsic::x86_avx2_psrli_d:
10005    case Intrinsic::x86_avx2_psrli_q:
10006      Opcode = X86ISD::VSRLI;
10007      break;
10008    case Intrinsic::x86_sse2_psrai_w:
10009    case Intrinsic::x86_sse2_psrai_d:
10010    case Intrinsic::x86_avx2_psrai_w:
10011    case Intrinsic::x86_avx2_psrai_d:
10012      Opcode = X86ISD::VSRAI;
10013      break;
10014    }
10015    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10016                               Op.getOperand(1), Op.getOperand(2), DAG);
10017  }
10018
10019  case Intrinsic::x86_sse42_pcmpistria128:
10020  case Intrinsic::x86_sse42_pcmpestria128:
10021  case Intrinsic::x86_sse42_pcmpistric128:
10022  case Intrinsic::x86_sse42_pcmpestric128:
10023  case Intrinsic::x86_sse42_pcmpistrio128:
10024  case Intrinsic::x86_sse42_pcmpestrio128:
10025  case Intrinsic::x86_sse42_pcmpistris128:
10026  case Intrinsic::x86_sse42_pcmpestris128:
10027  case Intrinsic::x86_sse42_pcmpistriz128:
10028  case Intrinsic::x86_sse42_pcmpestriz128: {
10029    unsigned Opcode;
10030    unsigned X86CC;
10031    switch (IntNo) {
10032    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10033    case Intrinsic::x86_sse42_pcmpistria128:
10034      Opcode = X86ISD::PCMPISTRI;
10035      X86CC = X86::COND_A;
10036      break;
10037    case Intrinsic::x86_sse42_pcmpestria128:
10038      Opcode = X86ISD::PCMPESTRI;
10039      X86CC = X86::COND_A;
10040      break;
10041    case Intrinsic::x86_sse42_pcmpistric128:
10042      Opcode = X86ISD::PCMPISTRI;
10043      X86CC = X86::COND_B;
10044      break;
10045    case Intrinsic::x86_sse42_pcmpestric128:
10046      Opcode = X86ISD::PCMPESTRI;
10047      X86CC = X86::COND_B;
10048      break;
10049    case Intrinsic::x86_sse42_pcmpistrio128:
10050      Opcode = X86ISD::PCMPISTRI;
10051      X86CC = X86::COND_O;
10052      break;
10053    case Intrinsic::x86_sse42_pcmpestrio128:
10054      Opcode = X86ISD::PCMPESTRI;
10055      X86CC = X86::COND_O;
10056      break;
10057    case Intrinsic::x86_sse42_pcmpistris128:
10058      Opcode = X86ISD::PCMPISTRI;
10059      X86CC = X86::COND_S;
10060      break;
10061    case Intrinsic::x86_sse42_pcmpestris128:
10062      Opcode = X86ISD::PCMPESTRI;
10063      X86CC = X86::COND_S;
10064      break;
10065    case Intrinsic::x86_sse42_pcmpistriz128:
10066      Opcode = X86ISD::PCMPISTRI;
10067      X86CC = X86::COND_E;
10068      break;
10069    case Intrinsic::x86_sse42_pcmpestriz128:
10070      Opcode = X86ISD::PCMPESTRI;
10071      X86CC = X86::COND_E;
10072      break;
10073    }
10074    SmallVector<SDValue, 5> NewOps;
10075    NewOps.append(Op->op_begin()+1, Op->op_end());
10076    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10077    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10078    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10079                                DAG.getConstant(X86CC, MVT::i8),
10080                                SDValue(PCMP.getNode(), 1));
10081    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10082  }
10083
10084  case Intrinsic::x86_sse42_pcmpistri128:
10085  case Intrinsic::x86_sse42_pcmpestri128: {
10086    unsigned Opcode;
10087    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10088      Opcode = X86ISD::PCMPISTRI;
10089    else
10090      Opcode = X86ISD::PCMPESTRI;
10091
10092    SmallVector<SDValue, 5> NewOps;
10093    NewOps.append(Op->op_begin()+1, Op->op_end());
10094    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10095    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10096  }
10097  case Intrinsic::x86_fma_vfmadd_ps:
10098  case Intrinsic::x86_fma_vfmadd_pd:
10099  case Intrinsic::x86_fma_vfmsub_ps:
10100  case Intrinsic::x86_fma_vfmsub_pd:
10101  case Intrinsic::x86_fma_vfnmadd_ps:
10102  case Intrinsic::x86_fma_vfnmadd_pd:
10103  case Intrinsic::x86_fma_vfnmsub_ps:
10104  case Intrinsic::x86_fma_vfnmsub_pd:
10105  case Intrinsic::x86_fma_vfmaddsub_ps:
10106  case Intrinsic::x86_fma_vfmaddsub_pd:
10107  case Intrinsic::x86_fma_vfmsubadd_ps:
10108  case Intrinsic::x86_fma_vfmsubadd_pd:
10109  case Intrinsic::x86_fma_vfmadd_ps_256:
10110  case Intrinsic::x86_fma_vfmadd_pd_256:
10111  case Intrinsic::x86_fma_vfmsub_ps_256:
10112  case Intrinsic::x86_fma_vfmsub_pd_256:
10113  case Intrinsic::x86_fma_vfnmadd_ps_256:
10114  case Intrinsic::x86_fma_vfnmadd_pd_256:
10115  case Intrinsic::x86_fma_vfnmsub_ps_256:
10116  case Intrinsic::x86_fma_vfnmsub_pd_256:
10117  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10118  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10119  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10120  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10121    unsigned Opc;
10122    switch (IntNo) {
10123    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10124    case Intrinsic::x86_fma_vfmadd_ps:
10125    case Intrinsic::x86_fma_vfmadd_pd:
10126    case Intrinsic::x86_fma_vfmadd_ps_256:
10127    case Intrinsic::x86_fma_vfmadd_pd_256:
10128      Opc = X86ISD::FMADD;
10129      break;
10130    case Intrinsic::x86_fma_vfmsub_ps:
10131    case Intrinsic::x86_fma_vfmsub_pd:
10132    case Intrinsic::x86_fma_vfmsub_ps_256:
10133    case Intrinsic::x86_fma_vfmsub_pd_256:
10134      Opc = X86ISD::FMSUB;
10135      break;
10136    case Intrinsic::x86_fma_vfnmadd_ps:
10137    case Intrinsic::x86_fma_vfnmadd_pd:
10138    case Intrinsic::x86_fma_vfnmadd_ps_256:
10139    case Intrinsic::x86_fma_vfnmadd_pd_256:
10140      Opc = X86ISD::FNMADD;
10141      break;
10142    case Intrinsic::x86_fma_vfnmsub_ps:
10143    case Intrinsic::x86_fma_vfnmsub_pd:
10144    case Intrinsic::x86_fma_vfnmsub_ps_256:
10145    case Intrinsic::x86_fma_vfnmsub_pd_256:
10146      Opc = X86ISD::FNMSUB;
10147      break;
10148    case Intrinsic::x86_fma_vfmaddsub_ps:
10149    case Intrinsic::x86_fma_vfmaddsub_pd:
10150    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10151    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10152      Opc = X86ISD::FMADDSUB;
10153      break;
10154    case Intrinsic::x86_fma_vfmsubadd_ps:
10155    case Intrinsic::x86_fma_vfmsubadd_pd:
10156    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10157    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10158      Opc = X86ISD::FMSUBADD;
10159      break;
10160    }
10161
10162    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10163                       Op.getOperand(2), Op.getOperand(3));
10164  }
10165  }
10166}
10167
10168SDValue
10169X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10170  DebugLoc dl = Op.getDebugLoc();
10171  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10172  switch (IntNo) {
10173  default: return SDValue();    // Don't custom lower most intrinsics.
10174
10175  // RDRAND intrinsics.
10176  case Intrinsic::x86_rdrand_16:
10177  case Intrinsic::x86_rdrand_32:
10178  case Intrinsic::x86_rdrand_64: {
10179    // Emit the node with the right value type.
10180    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10181    SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10182
10183    // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10184    // return the value from Rand, which is always 0, casted to i32.
10185    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10186                      DAG.getConstant(1, Op->getValueType(1)),
10187                      DAG.getConstant(X86::COND_B, MVT::i32),
10188                      SDValue(Result.getNode(), 1) };
10189    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10190                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10191                                  Ops, 4);
10192
10193    // Return { result, isValid, chain }.
10194    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10195                       SDValue(Result.getNode(), 2));
10196  }
10197  }
10198}
10199
10200SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10201                                           SelectionDAG &DAG) const {
10202  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10203  MFI->setReturnAddressIsTaken(true);
10204
10205  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10206  DebugLoc dl = Op.getDebugLoc();
10207
10208  if (Depth > 0) {
10209    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10210    SDValue Offset =
10211      DAG.getConstant(TD->getPointerSize(),
10212                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10213    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10214                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
10215                                   FrameAddr, Offset),
10216                       MachinePointerInfo(), false, false, false, 0);
10217  }
10218
10219  // Just load the return address.
10220  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10221  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10222                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10223}
10224
10225SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10226  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10227  MFI->setFrameAddressIsTaken(true);
10228
10229  EVT VT = Op.getValueType();
10230  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10231  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10232  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10233  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10234  while (Depth--)
10235    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10236                            MachinePointerInfo(),
10237                            false, false, false, 0);
10238  return FrameAddr;
10239}
10240
10241SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10242                                                     SelectionDAG &DAG) const {
10243  return DAG.getIntPtrConstant(2*TD->getPointerSize());
10244}
10245
10246SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10247  SDValue Chain     = Op.getOperand(0);
10248  SDValue Offset    = Op.getOperand(1);
10249  SDValue Handler   = Op.getOperand(2);
10250  DebugLoc dl       = Op.getDebugLoc();
10251
10252  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10253                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10254                                     getPointerTy());
10255  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10256
10257  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10258                                  DAG.getIntPtrConstant(TD->getPointerSize()));
10259  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10260  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10261                       false, false, 0);
10262  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10263
10264  return DAG.getNode(X86ISD::EH_RETURN, dl,
10265                     MVT::Other,
10266                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10267}
10268
10269SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10270                                                  SelectionDAG &DAG) const {
10271  return Op.getOperand(0);
10272}
10273
10274SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10275                                                SelectionDAG &DAG) const {
10276  SDValue Root = Op.getOperand(0);
10277  SDValue Trmp = Op.getOperand(1); // trampoline
10278  SDValue FPtr = Op.getOperand(2); // nested function
10279  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10280  DebugLoc dl  = Op.getDebugLoc();
10281
10282  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10283
10284  if (Subtarget->is64Bit()) {
10285    SDValue OutChains[6];
10286
10287    // Large code-model.
10288    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10289    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10290
10291    const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10292    const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10293
10294    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10295
10296    // Load the pointer to the nested function into R11.
10297    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10298    SDValue Addr = Trmp;
10299    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10300                                Addr, MachinePointerInfo(TrmpAddr),
10301                                false, false, 0);
10302
10303    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10304                       DAG.getConstant(2, MVT::i64));
10305    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10306                                MachinePointerInfo(TrmpAddr, 2),
10307                                false, false, 2);
10308
10309    // Load the 'nest' parameter value into R10.
10310    // R10 is specified in X86CallingConv.td
10311    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10312    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10313                       DAG.getConstant(10, MVT::i64));
10314    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10315                                Addr, MachinePointerInfo(TrmpAddr, 10),
10316                                false, false, 0);
10317
10318    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10319                       DAG.getConstant(12, MVT::i64));
10320    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10321                                MachinePointerInfo(TrmpAddr, 12),
10322                                false, false, 2);
10323
10324    // Jump to the nested function.
10325    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10326    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10327                       DAG.getConstant(20, MVT::i64));
10328    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10329                                Addr, MachinePointerInfo(TrmpAddr, 20),
10330                                false, false, 0);
10331
10332    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10333    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10334                       DAG.getConstant(22, MVT::i64));
10335    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10336                                MachinePointerInfo(TrmpAddr, 22),
10337                                false, false, 0);
10338
10339    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10340  } else {
10341    const Function *Func =
10342      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10343    CallingConv::ID CC = Func->getCallingConv();
10344    unsigned NestReg;
10345
10346    switch (CC) {
10347    default:
10348      llvm_unreachable("Unsupported calling convention");
10349    case CallingConv::C:
10350    case CallingConv::X86_StdCall: {
10351      // Pass 'nest' parameter in ECX.
10352      // Must be kept in sync with X86CallingConv.td
10353      NestReg = X86::ECX;
10354
10355      // Check that ECX wasn't needed by an 'inreg' parameter.
10356      FunctionType *FTy = Func->getFunctionType();
10357      const AttrListPtr &Attrs = Func->getAttributes();
10358
10359      if (!Attrs.isEmpty() && !Func->isVarArg()) {
10360        unsigned InRegCount = 0;
10361        unsigned Idx = 1;
10362
10363        for (FunctionType::param_iterator I = FTy->param_begin(),
10364             E = FTy->param_end(); I != E; ++I, ++Idx)
10365          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10366            // FIXME: should only count parameters that are lowered to integers.
10367            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10368
10369        if (InRegCount > 2) {
10370          report_fatal_error("Nest register in use - reduce number of inreg"
10371                             " parameters!");
10372        }
10373      }
10374      break;
10375    }
10376    case CallingConv::X86_FastCall:
10377    case CallingConv::X86_ThisCall:
10378    case CallingConv::Fast:
10379      // Pass 'nest' parameter in EAX.
10380      // Must be kept in sync with X86CallingConv.td
10381      NestReg = X86::EAX;
10382      break;
10383    }
10384
10385    SDValue OutChains[4];
10386    SDValue Addr, Disp;
10387
10388    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10389                       DAG.getConstant(10, MVT::i32));
10390    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10391
10392    // This is storing the opcode for MOV32ri.
10393    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10394    const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10395    OutChains[0] = DAG.getStore(Root, dl,
10396                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10397                                Trmp, MachinePointerInfo(TrmpAddr),
10398                                false, false, 0);
10399
10400    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10401                       DAG.getConstant(1, MVT::i32));
10402    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10403                                MachinePointerInfo(TrmpAddr, 1),
10404                                false, false, 1);
10405
10406    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10407    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10408                       DAG.getConstant(5, MVT::i32));
10409    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10410                                MachinePointerInfo(TrmpAddr, 5),
10411                                false, false, 1);
10412
10413    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10414                       DAG.getConstant(6, MVT::i32));
10415    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10416                                MachinePointerInfo(TrmpAddr, 6),
10417                                false, false, 1);
10418
10419    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10420  }
10421}
10422
10423SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10424                                            SelectionDAG &DAG) const {
10425  /*
10426   The rounding mode is in bits 11:10 of FPSR, and has the following
10427   settings:
10428     00 Round to nearest
10429     01 Round to -inf
10430     10 Round to +inf
10431     11 Round to 0
10432
10433  FLT_ROUNDS, on the other hand, expects the following:
10434    -1 Undefined
10435     0 Round to 0
10436     1 Round to nearest
10437     2 Round to +inf
10438     3 Round to -inf
10439
10440  To perform the conversion, we do:
10441    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10442  */
10443
10444  MachineFunction &MF = DAG.getMachineFunction();
10445  const TargetMachine &TM = MF.getTarget();
10446  const TargetFrameLowering &TFI = *TM.getFrameLowering();
10447  unsigned StackAlignment = TFI.getStackAlignment();
10448  EVT VT = Op.getValueType();
10449  DebugLoc DL = Op.getDebugLoc();
10450
10451  // Save FP Control Word to stack slot
10452  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10453  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10454
10455
10456  MachineMemOperand *MMO =
10457   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10458                           MachineMemOperand::MOStore, 2, 2);
10459
10460  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10461  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10462                                          DAG.getVTList(MVT::Other),
10463                                          Ops, 2, MVT::i16, MMO);
10464
10465  // Load FP Control Word from stack slot
10466  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10467                            MachinePointerInfo(), false, false, false, 0);
10468
10469  // Transform as necessary
10470  SDValue CWD1 =
10471    DAG.getNode(ISD::SRL, DL, MVT::i16,
10472                DAG.getNode(ISD::AND, DL, MVT::i16,
10473                            CWD, DAG.getConstant(0x800, MVT::i16)),
10474                DAG.getConstant(11, MVT::i8));
10475  SDValue CWD2 =
10476    DAG.getNode(ISD::SRL, DL, MVT::i16,
10477                DAG.getNode(ISD::AND, DL, MVT::i16,
10478                            CWD, DAG.getConstant(0x400, MVT::i16)),
10479                DAG.getConstant(9, MVT::i8));
10480
10481  SDValue RetVal =
10482    DAG.getNode(ISD::AND, DL, MVT::i16,
10483                DAG.getNode(ISD::ADD, DL, MVT::i16,
10484                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10485                            DAG.getConstant(1, MVT::i16)),
10486                DAG.getConstant(3, MVT::i16));
10487
10488
10489  return DAG.getNode((VT.getSizeInBits() < 16 ?
10490                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10491}
10492
10493SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10494  EVT VT = Op.getValueType();
10495  EVT OpVT = VT;
10496  unsigned NumBits = VT.getSizeInBits();
10497  DebugLoc dl = Op.getDebugLoc();
10498
10499  Op = Op.getOperand(0);
10500  if (VT == MVT::i8) {
10501    // Zero extend to i32 since there is not an i8 bsr.
10502    OpVT = MVT::i32;
10503    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10504  }
10505
10506  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10507  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10508  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10509
10510  // If src is zero (i.e. bsr sets ZF), returns NumBits.
10511  SDValue Ops[] = {
10512    Op,
10513    DAG.getConstant(NumBits+NumBits-1, OpVT),
10514    DAG.getConstant(X86::COND_E, MVT::i8),
10515    Op.getValue(1)
10516  };
10517  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10518
10519  // Finally xor with NumBits-1.
10520  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10521
10522  if (VT == MVT::i8)
10523    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10524  return Op;
10525}
10526
10527SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10528                                                SelectionDAG &DAG) const {
10529  EVT VT = Op.getValueType();
10530  EVT OpVT = VT;
10531  unsigned NumBits = VT.getSizeInBits();
10532  DebugLoc dl = Op.getDebugLoc();
10533
10534  Op = Op.getOperand(0);
10535  if (VT == MVT::i8) {
10536    // Zero extend to i32 since there is not an i8 bsr.
10537    OpVT = MVT::i32;
10538    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10539  }
10540
10541  // Issue a bsr (scan bits in reverse).
10542  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10543  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10544
10545  // And xor with NumBits-1.
10546  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10547
10548  if (VT == MVT::i8)
10549    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10550  return Op;
10551}
10552
10553SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10554  EVT VT = Op.getValueType();
10555  unsigned NumBits = VT.getSizeInBits();
10556  DebugLoc dl = Op.getDebugLoc();
10557  Op = Op.getOperand(0);
10558
10559  // Issue a bsf (scan bits forward) which also sets EFLAGS.
10560  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10561  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10562
10563  // If src is zero (i.e. bsf sets ZF), returns NumBits.
10564  SDValue Ops[] = {
10565    Op,
10566    DAG.getConstant(NumBits, VT),
10567    DAG.getConstant(X86::COND_E, MVT::i8),
10568    Op.getValue(1)
10569  };
10570  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10571}
10572
10573// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10574// ones, and then concatenate the result back.
10575static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10576  EVT VT = Op.getValueType();
10577
10578  assert(VT.is256BitVector() && VT.isInteger() &&
10579         "Unsupported value type for operation");
10580
10581  unsigned NumElems = VT.getVectorNumElements();
10582  DebugLoc dl = Op.getDebugLoc();
10583
10584  // Extract the LHS vectors
10585  SDValue LHS = Op.getOperand(0);
10586  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10587  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10588
10589  // Extract the RHS vectors
10590  SDValue RHS = Op.getOperand(1);
10591  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10592  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10593
10594  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10595  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10596
10597  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10598                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10599                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10600}
10601
10602SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10603  assert(Op.getValueType().is256BitVector() &&
10604         Op.getValueType().isInteger() &&
10605         "Only handle AVX 256-bit vector integer operation");
10606  return Lower256IntArith(Op, DAG);
10607}
10608
10609SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10610  assert(Op.getValueType().is256BitVector() &&
10611         Op.getValueType().isInteger() &&
10612         "Only handle AVX 256-bit vector integer operation");
10613  return Lower256IntArith(Op, DAG);
10614}
10615
10616SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10617  EVT VT = Op.getValueType();
10618
10619  // Decompose 256-bit ops into smaller 128-bit ops.
10620  if (VT.is256BitVector() && !Subtarget->hasAVX2())
10621    return Lower256IntArith(Op, DAG);
10622
10623  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10624         "Only know how to lower V2I64/V4I64 multiply");
10625
10626  DebugLoc dl = Op.getDebugLoc();
10627
10628  //  Ahi = psrlqi(a, 32);
10629  //  Bhi = psrlqi(b, 32);
10630  //
10631  //  AloBlo = pmuludq(a, b);
10632  //  AloBhi = pmuludq(a, Bhi);
10633  //  AhiBlo = pmuludq(Ahi, b);
10634
10635  //  AloBhi = psllqi(AloBhi, 32);
10636  //  AhiBlo = psllqi(AhiBlo, 32);
10637  //  return AloBlo + AloBhi + AhiBlo;
10638
10639  SDValue A = Op.getOperand(0);
10640  SDValue B = Op.getOperand(1);
10641
10642  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10643
10644  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10645  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10646
10647  // Bit cast to 32-bit vectors for MULUDQ
10648  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10649  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10650  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10651  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10652  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10653
10654  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10655  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10656  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10657
10658  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10659  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10660
10661  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10662  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10663}
10664
10665SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10666
10667  EVT VT = Op.getValueType();
10668  DebugLoc dl = Op.getDebugLoc();
10669  SDValue R = Op.getOperand(0);
10670  SDValue Amt = Op.getOperand(1);
10671  LLVMContext *Context = DAG.getContext();
10672
10673  if (!Subtarget->hasSSE2())
10674    return SDValue();
10675
10676  // Optimize shl/srl/sra with constant shift amount.
10677  if (isSplatVector(Amt.getNode())) {
10678    SDValue SclrAmt = Amt->getOperand(0);
10679    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10680      uint64_t ShiftAmt = C->getZExtValue();
10681
10682      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10683          (Subtarget->hasAVX2() &&
10684           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10685        if (Op.getOpcode() == ISD::SHL)
10686          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10687                             DAG.getConstant(ShiftAmt, MVT::i32));
10688        if (Op.getOpcode() == ISD::SRL)
10689          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10690                             DAG.getConstant(ShiftAmt, MVT::i32));
10691        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10692          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10693                             DAG.getConstant(ShiftAmt, MVT::i32));
10694      }
10695
10696      if (VT == MVT::v16i8) {
10697        if (Op.getOpcode() == ISD::SHL) {
10698          // Make a large shift.
10699          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10700                                    DAG.getConstant(ShiftAmt, MVT::i32));
10701          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10702          // Zero out the rightmost bits.
10703          SmallVector<SDValue, 16> V(16,
10704                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
10705                                                     MVT::i8));
10706          return DAG.getNode(ISD::AND, dl, VT, SHL,
10707                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10708        }
10709        if (Op.getOpcode() == ISD::SRL) {
10710          // Make a large shift.
10711          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10712                                    DAG.getConstant(ShiftAmt, MVT::i32));
10713          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10714          // Zero out the leftmost bits.
10715          SmallVector<SDValue, 16> V(16,
10716                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10717                                                     MVT::i8));
10718          return DAG.getNode(ISD::AND, dl, VT, SRL,
10719                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10720        }
10721        if (Op.getOpcode() == ISD::SRA) {
10722          if (ShiftAmt == 7) {
10723            // R s>> 7  ===  R s< 0
10724            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10725            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10726          }
10727
10728          // R s>> a === ((R u>> a) ^ m) - m
10729          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10730          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10731                                                         MVT::i8));
10732          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10733          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10734          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10735          return Res;
10736        }
10737        llvm_unreachable("Unknown shift opcode.");
10738      }
10739
10740      if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10741        if (Op.getOpcode() == ISD::SHL) {
10742          // Make a large shift.
10743          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10744                                    DAG.getConstant(ShiftAmt, MVT::i32));
10745          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10746          // Zero out the rightmost bits.
10747          SmallVector<SDValue, 32> V(32,
10748                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
10749                                                     MVT::i8));
10750          return DAG.getNode(ISD::AND, dl, VT, SHL,
10751                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10752        }
10753        if (Op.getOpcode() == ISD::SRL) {
10754          // Make a large shift.
10755          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10756                                    DAG.getConstant(ShiftAmt, MVT::i32));
10757          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10758          // Zero out the leftmost bits.
10759          SmallVector<SDValue, 32> V(32,
10760                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10761                                                     MVT::i8));
10762          return DAG.getNode(ISD::AND, dl, VT, SRL,
10763                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10764        }
10765        if (Op.getOpcode() == ISD::SRA) {
10766          if (ShiftAmt == 7) {
10767            // R s>> 7  ===  R s< 0
10768            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10769            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10770          }
10771
10772          // R s>> a === ((R u>> a) ^ m) - m
10773          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10774          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10775                                                         MVT::i8));
10776          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10777          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10778          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10779          return Res;
10780        }
10781        llvm_unreachable("Unknown shift opcode.");
10782      }
10783    }
10784  }
10785
10786  // Lower SHL with variable shift amount.
10787  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10788    Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10789                     DAG.getConstant(23, MVT::i32));
10790
10791    const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10792    Constant *C = ConstantDataVector::get(*Context, CV);
10793    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10794    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10795                                 MachinePointerInfo::getConstantPool(),
10796                                 false, false, false, 16);
10797
10798    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10799    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10800    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10801    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10802  }
10803  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10804    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10805
10806    // a = a << 5;
10807    Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10808                     DAG.getConstant(5, MVT::i32));
10809    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10810
10811    // Turn 'a' into a mask suitable for VSELECT
10812    SDValue VSelM = DAG.getConstant(0x80, VT);
10813    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10814    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10815
10816    SDValue CM1 = DAG.getConstant(0x0f, VT);
10817    SDValue CM2 = DAG.getConstant(0x3f, VT);
10818
10819    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10820    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10821    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10822                            DAG.getConstant(4, MVT::i32), DAG);
10823    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10824    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10825
10826    // a += a
10827    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10828    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10829    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10830
10831    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10832    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10833    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10834                            DAG.getConstant(2, MVT::i32), DAG);
10835    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10836    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10837
10838    // a += a
10839    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10840    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10841    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10842
10843    // return VSELECT(r, r+r, a);
10844    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10845                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10846    return R;
10847  }
10848
10849  // Decompose 256-bit shifts into smaller 128-bit shifts.
10850  if (VT.is256BitVector()) {
10851    unsigned NumElems = VT.getVectorNumElements();
10852    MVT EltVT = VT.getVectorElementType().getSimpleVT();
10853    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10854
10855    // Extract the two vectors
10856    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10857    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10858
10859    // Recreate the shift amount vectors
10860    SDValue Amt1, Amt2;
10861    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10862      // Constant shift amount
10863      SmallVector<SDValue, 4> Amt1Csts;
10864      SmallVector<SDValue, 4> Amt2Csts;
10865      for (unsigned i = 0; i != NumElems/2; ++i)
10866        Amt1Csts.push_back(Amt->getOperand(i));
10867      for (unsigned i = NumElems/2; i != NumElems; ++i)
10868        Amt2Csts.push_back(Amt->getOperand(i));
10869
10870      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10871                                 &Amt1Csts[0], NumElems/2);
10872      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10873                                 &Amt2Csts[0], NumElems/2);
10874    } else {
10875      // Variable shift amount
10876      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10877      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10878    }
10879
10880    // Issue new vector shifts for the smaller types
10881    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10882    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10883
10884    // Concatenate the result back
10885    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10886  }
10887
10888  return SDValue();
10889}
10890
10891SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10892  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10893  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10894  // looks for this combo and may remove the "setcc" instruction if the "setcc"
10895  // has only one use.
10896  SDNode *N = Op.getNode();
10897  SDValue LHS = N->getOperand(0);
10898  SDValue RHS = N->getOperand(1);
10899  unsigned BaseOp = 0;
10900  unsigned Cond = 0;
10901  DebugLoc DL = Op.getDebugLoc();
10902  switch (Op.getOpcode()) {
10903  default: llvm_unreachable("Unknown ovf instruction!");
10904  case ISD::SADDO:
10905    // A subtract of one will be selected as a INC. Note that INC doesn't
10906    // set CF, so we can't do this for UADDO.
10907    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10908      if (C->isOne()) {
10909        BaseOp = X86ISD::INC;
10910        Cond = X86::COND_O;
10911        break;
10912      }
10913    BaseOp = X86ISD::ADD;
10914    Cond = X86::COND_O;
10915    break;
10916  case ISD::UADDO:
10917    BaseOp = X86ISD::ADD;
10918    Cond = X86::COND_B;
10919    break;
10920  case ISD::SSUBO:
10921    // A subtract of one will be selected as a DEC. Note that DEC doesn't
10922    // set CF, so we can't do this for USUBO.
10923    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10924      if (C->isOne()) {
10925        BaseOp = X86ISD::DEC;
10926        Cond = X86::COND_O;
10927        break;
10928      }
10929    BaseOp = X86ISD::SUB;
10930    Cond = X86::COND_O;
10931    break;
10932  case ISD::USUBO:
10933    BaseOp = X86ISD::SUB;
10934    Cond = X86::COND_B;
10935    break;
10936  case ISD::SMULO:
10937    BaseOp = X86ISD::SMUL;
10938    Cond = X86::COND_O;
10939    break;
10940  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10941    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10942                                 MVT::i32);
10943    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10944
10945    SDValue SetCC =
10946      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10947                  DAG.getConstant(X86::COND_O, MVT::i32),
10948                  SDValue(Sum.getNode(), 2));
10949
10950    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10951  }
10952  }
10953
10954  // Also sets EFLAGS.
10955  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10956  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10957
10958  SDValue SetCC =
10959    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10960                DAG.getConstant(Cond, MVT::i32),
10961                SDValue(Sum.getNode(), 1));
10962
10963  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10964}
10965
10966SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10967                                                  SelectionDAG &DAG) const {
10968  DebugLoc dl = Op.getDebugLoc();
10969  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10970  EVT VT = Op.getValueType();
10971
10972  if (!Subtarget->hasSSE2() || !VT.isVector())
10973    return SDValue();
10974
10975  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10976                      ExtraVT.getScalarType().getSizeInBits();
10977  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10978
10979  switch (VT.getSimpleVT().SimpleTy) {
10980    default: return SDValue();
10981    case MVT::v8i32:
10982    case MVT::v16i16:
10983      if (!Subtarget->hasAVX())
10984        return SDValue();
10985      if (!Subtarget->hasAVX2()) {
10986        // needs to be split
10987        unsigned NumElems = VT.getVectorNumElements();
10988
10989        // Extract the LHS vectors
10990        SDValue LHS = Op.getOperand(0);
10991        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10992        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10993
10994        MVT EltVT = VT.getVectorElementType().getSimpleVT();
10995        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10996
10997        EVT ExtraEltVT = ExtraVT.getVectorElementType();
10998        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10999        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11000                                   ExtraNumElems/2);
11001        SDValue Extra = DAG.getValueType(ExtraVT);
11002
11003        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11004        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11005
11006        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
11007      }
11008      // fall through
11009    case MVT::v4i32:
11010    case MVT::v8i16: {
11011      SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11012                                         Op.getOperand(0), ShAmt, DAG);
11013      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11014    }
11015  }
11016}
11017
11018
11019SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
11020  DebugLoc dl = Op.getDebugLoc();
11021
11022  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11023  // There isn't any reason to disable it if the target processor supports it.
11024  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11025    SDValue Chain = Op.getOperand(0);
11026    SDValue Zero = DAG.getConstant(0, MVT::i32);
11027    SDValue Ops[] = {
11028      DAG.getRegister(X86::ESP, MVT::i32), // Base
11029      DAG.getTargetConstant(1, MVT::i8),   // Scale
11030      DAG.getRegister(0, MVT::i32),        // Index
11031      DAG.getTargetConstant(0, MVT::i32),  // Disp
11032      DAG.getRegister(0, MVT::i32),        // Segment.
11033      Zero,
11034      Chain
11035    };
11036    SDNode *Res =
11037      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11038                          array_lengthof(Ops));
11039    return SDValue(Res, 0);
11040  }
11041
11042  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11043  if (!isDev)
11044    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11045
11046  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11047  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11048  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11049  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11050
11051  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11052  if (!Op1 && !Op2 && !Op3 && Op4)
11053    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11054
11055  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11056  if (Op1 && !Op2 && !Op3 && !Op4)
11057    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11058
11059  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11060  //           (MFENCE)>;
11061  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11062}
11063
11064SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11065                                             SelectionDAG &DAG) const {
11066  DebugLoc dl = Op.getDebugLoc();
11067  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11068    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11069  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11070    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11071
11072  // The only fence that needs an instruction is a sequentially-consistent
11073  // cross-thread fence.
11074  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11075    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11076    // no-sse2). There isn't any reason to disable it if the target processor
11077    // supports it.
11078    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11079      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11080
11081    SDValue Chain = Op.getOperand(0);
11082    SDValue Zero = DAG.getConstant(0, MVT::i32);
11083    SDValue Ops[] = {
11084      DAG.getRegister(X86::ESP, MVT::i32), // Base
11085      DAG.getTargetConstant(1, MVT::i8),   // Scale
11086      DAG.getRegister(0, MVT::i32),        // Index
11087      DAG.getTargetConstant(0, MVT::i32),  // Disp
11088      DAG.getRegister(0, MVT::i32),        // Segment.
11089      Zero,
11090      Chain
11091    };
11092    SDNode *Res =
11093      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11094                         array_lengthof(Ops));
11095    return SDValue(Res, 0);
11096  }
11097
11098  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11099  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11100}
11101
11102
11103SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11104  EVT T = Op.getValueType();
11105  DebugLoc DL = Op.getDebugLoc();
11106  unsigned Reg = 0;
11107  unsigned size = 0;
11108  switch(T.getSimpleVT().SimpleTy) {
11109  default: llvm_unreachable("Invalid value type!");
11110  case MVT::i8:  Reg = X86::AL;  size = 1; break;
11111  case MVT::i16: Reg = X86::AX;  size = 2; break;
11112  case MVT::i32: Reg = X86::EAX; size = 4; break;
11113  case MVT::i64:
11114    assert(Subtarget->is64Bit() && "Node not type legal!");
11115    Reg = X86::RAX; size = 8;
11116    break;
11117  }
11118  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11119                                    Op.getOperand(2), SDValue());
11120  SDValue Ops[] = { cpIn.getValue(0),
11121                    Op.getOperand(1),
11122                    Op.getOperand(3),
11123                    DAG.getTargetConstant(size, MVT::i8),
11124                    cpIn.getValue(1) };
11125  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11126  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11127  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11128                                           Ops, 5, T, MMO);
11129  SDValue cpOut =
11130    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11131  return cpOut;
11132}
11133
11134SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11135                                                 SelectionDAG &DAG) const {
11136  assert(Subtarget->is64Bit() && "Result not type legalized?");
11137  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11138  SDValue TheChain = Op.getOperand(0);
11139  DebugLoc dl = Op.getDebugLoc();
11140  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11141  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11142  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11143                                   rax.getValue(2));
11144  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11145                            DAG.getConstant(32, MVT::i8));
11146  SDValue Ops[] = {
11147    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11148    rdx.getValue(1)
11149  };
11150  return DAG.getMergeValues(Ops, 2, dl);
11151}
11152
11153SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11154                                            SelectionDAG &DAG) const {
11155  EVT SrcVT = Op.getOperand(0).getValueType();
11156  EVT DstVT = Op.getValueType();
11157  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11158         Subtarget->hasMMX() && "Unexpected custom BITCAST");
11159  assert((DstVT == MVT::i64 ||
11160          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11161         "Unexpected custom BITCAST");
11162  // i64 <=> MMX conversions are Legal.
11163  if (SrcVT==MVT::i64 && DstVT.isVector())
11164    return Op;
11165  if (DstVT==MVT::i64 && SrcVT.isVector())
11166    return Op;
11167  // MMX <=> MMX conversions are Legal.
11168  if (SrcVT.isVector() && DstVT.isVector())
11169    return Op;
11170  // All other conversions need to be expanded.
11171  return SDValue();
11172}
11173
11174SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11175  SDNode *Node = Op.getNode();
11176  DebugLoc dl = Node->getDebugLoc();
11177  EVT T = Node->getValueType(0);
11178  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11179                              DAG.getConstant(0, T), Node->getOperand(2));
11180  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11181                       cast<AtomicSDNode>(Node)->getMemoryVT(),
11182                       Node->getOperand(0),
11183                       Node->getOperand(1), negOp,
11184                       cast<AtomicSDNode>(Node)->getSrcValue(),
11185                       cast<AtomicSDNode>(Node)->getAlignment(),
11186                       cast<AtomicSDNode>(Node)->getOrdering(),
11187                       cast<AtomicSDNode>(Node)->getSynchScope());
11188}
11189
11190static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11191  SDNode *Node = Op.getNode();
11192  DebugLoc dl = Node->getDebugLoc();
11193  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11194
11195  // Convert seq_cst store -> xchg
11196  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11197  // FIXME: On 32-bit, store -> fist or movq would be more efficient
11198  //        (The only way to get a 16-byte store is cmpxchg16b)
11199  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11200  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11201      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11202    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11203                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
11204                                 Node->getOperand(0),
11205                                 Node->getOperand(1), Node->getOperand(2),
11206                                 cast<AtomicSDNode>(Node)->getMemOperand(),
11207                                 cast<AtomicSDNode>(Node)->getOrdering(),
11208                                 cast<AtomicSDNode>(Node)->getSynchScope());
11209    return Swap.getValue(1);
11210  }
11211  // Other atomic stores have a simple pattern.
11212  return Op;
11213}
11214
11215static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11216  EVT VT = Op.getNode()->getValueType(0);
11217
11218  // Let legalize expand this if it isn't a legal type yet.
11219  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11220    return SDValue();
11221
11222  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11223
11224  unsigned Opc;
11225  bool ExtraOp = false;
11226  switch (Op.getOpcode()) {
11227  default: llvm_unreachable("Invalid code");
11228  case ISD::ADDC: Opc = X86ISD::ADD; break;
11229  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11230  case ISD::SUBC: Opc = X86ISD::SUB; break;
11231  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11232  }
11233
11234  if (!ExtraOp)
11235    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11236                       Op.getOperand(1));
11237  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11238                     Op.getOperand(1), Op.getOperand(2));
11239}
11240
11241/// LowerOperation - Provide custom lowering hooks for some operations.
11242///
11243SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11244  switch (Op.getOpcode()) {
11245  default: llvm_unreachable("Should not custom lower this!");
11246  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11247  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11248  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11249  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11250  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11251  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11252  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11253  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11254  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11255  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11256  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11257  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11258  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11259  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11260  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11261  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11262  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11263  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11264  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11265  case ISD::SHL_PARTS:
11266  case ISD::SRA_PARTS:
11267  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11268  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11269  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11270  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11271  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11272  case ISD::FABS:               return LowerFABS(Op, DAG);
11273  case ISD::FNEG:               return LowerFNEG(Op, DAG);
11274  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11275  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11276  case ISD::SETCC:              return LowerSETCC(Op, DAG);
11277  case ISD::SELECT:             return LowerSELECT(Op, DAG);
11278  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11279  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11280  case ISD::VASTART:            return LowerVASTART(Op, DAG);
11281  case ISD::VAARG:              return LowerVAARG(Op, DAG);
11282  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11283  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11284  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11285  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11286  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11287  case ISD::FRAME_TO_ARGS_OFFSET:
11288                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11289  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11290  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11291  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11292  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11293  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11294  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11295  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11296  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11297  case ISD::MUL:                return LowerMUL(Op, DAG);
11298  case ISD::SRA:
11299  case ISD::SRL:
11300  case ISD::SHL:                return LowerShift(Op, DAG);
11301  case ISD::SADDO:
11302  case ISD::UADDO:
11303  case ISD::SSUBO:
11304  case ISD::USUBO:
11305  case ISD::SMULO:
11306  case ISD::UMULO:              return LowerXALUO(Op, DAG);
11307  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11308  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11309  case ISD::ADDC:
11310  case ISD::ADDE:
11311  case ISD::SUBC:
11312  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11313  case ISD::ADD:                return LowerADD(Op, DAG);
11314  case ISD::SUB:                return LowerSUB(Op, DAG);
11315  }
11316}
11317
11318static void ReplaceATOMIC_LOAD(SDNode *Node,
11319                                  SmallVectorImpl<SDValue> &Results,
11320                                  SelectionDAG &DAG) {
11321  DebugLoc dl = Node->getDebugLoc();
11322  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11323
11324  // Convert wide load -> cmpxchg8b/cmpxchg16b
11325  // FIXME: On 32-bit, load -> fild or movq would be more efficient
11326  //        (The only way to get a 16-byte load is cmpxchg16b)
11327  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11328  SDValue Zero = DAG.getConstant(0, VT);
11329  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11330                               Node->getOperand(0),
11331                               Node->getOperand(1), Zero, Zero,
11332                               cast<AtomicSDNode>(Node)->getMemOperand(),
11333                               cast<AtomicSDNode>(Node)->getOrdering(),
11334                               cast<AtomicSDNode>(Node)->getSynchScope());
11335  Results.push_back(Swap.getValue(0));
11336  Results.push_back(Swap.getValue(1));
11337}
11338
11339static void
11340ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11341                        SelectionDAG &DAG, unsigned NewOp) {
11342  DebugLoc dl = Node->getDebugLoc();
11343  assert (Node->getValueType(0) == MVT::i64 &&
11344          "Only know how to expand i64 atomics");
11345
11346  SDValue Chain = Node->getOperand(0);
11347  SDValue In1 = Node->getOperand(1);
11348  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11349                             Node->getOperand(2), DAG.getIntPtrConstant(0));
11350  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11351                             Node->getOperand(2), DAG.getIntPtrConstant(1));
11352  SDValue Ops[] = { Chain, In1, In2L, In2H };
11353  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11354  SDValue Result =
11355    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11356                            cast<MemSDNode>(Node)->getMemOperand());
11357  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11358  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11359  Results.push_back(Result.getValue(2));
11360}
11361
11362/// ReplaceNodeResults - Replace a node with an illegal result type
11363/// with a new node built out of custom code.
11364void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11365                                           SmallVectorImpl<SDValue>&Results,
11366                                           SelectionDAG &DAG) const {
11367  DebugLoc dl = N->getDebugLoc();
11368  switch (N->getOpcode()) {
11369  default:
11370    llvm_unreachable("Do not know how to custom type legalize this operation!");
11371  case ISD::SIGN_EXTEND_INREG:
11372  case ISD::ADDC:
11373  case ISD::ADDE:
11374  case ISD::SUBC:
11375  case ISD::SUBE:
11376    // We don't want to expand or promote these.
11377    return;
11378  case ISD::FP_TO_SINT:
11379  case ISD::FP_TO_UINT: {
11380    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11381
11382    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11383      return;
11384
11385    std::pair<SDValue,SDValue> Vals =
11386        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11387    SDValue FIST = Vals.first, StackSlot = Vals.second;
11388    if (FIST.getNode() != 0) {
11389      EVT VT = N->getValueType(0);
11390      // Return a load from the stack slot.
11391      if (StackSlot.getNode() != 0)
11392        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11393                                      MachinePointerInfo(),
11394                                      false, false, false, 0));
11395      else
11396        Results.push_back(FIST);
11397    }
11398    return;
11399  }
11400  case ISD::READCYCLECOUNTER: {
11401    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11402    SDValue TheChain = N->getOperand(0);
11403    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11404    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11405                                     rd.getValue(1));
11406    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11407                                     eax.getValue(2));
11408    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11409    SDValue Ops[] = { eax, edx };
11410    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11411    Results.push_back(edx.getValue(1));
11412    return;
11413  }
11414  case ISD::ATOMIC_CMP_SWAP: {
11415    EVT T = N->getValueType(0);
11416    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11417    bool Regs64bit = T == MVT::i128;
11418    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11419    SDValue cpInL, cpInH;
11420    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11421                        DAG.getConstant(0, HalfT));
11422    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11423                        DAG.getConstant(1, HalfT));
11424    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11425                             Regs64bit ? X86::RAX : X86::EAX,
11426                             cpInL, SDValue());
11427    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11428                             Regs64bit ? X86::RDX : X86::EDX,
11429                             cpInH, cpInL.getValue(1));
11430    SDValue swapInL, swapInH;
11431    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11432                          DAG.getConstant(0, HalfT));
11433    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11434                          DAG.getConstant(1, HalfT));
11435    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11436                               Regs64bit ? X86::RBX : X86::EBX,
11437                               swapInL, cpInH.getValue(1));
11438    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11439                               Regs64bit ? X86::RCX : X86::ECX,
11440                               swapInH, swapInL.getValue(1));
11441    SDValue Ops[] = { swapInH.getValue(0),
11442                      N->getOperand(1),
11443                      swapInH.getValue(1) };
11444    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11445    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11446    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11447                                  X86ISD::LCMPXCHG8_DAG;
11448    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11449                                             Ops, 3, T, MMO);
11450    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11451                                        Regs64bit ? X86::RAX : X86::EAX,
11452                                        HalfT, Result.getValue(1));
11453    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11454                                        Regs64bit ? X86::RDX : X86::EDX,
11455                                        HalfT, cpOutL.getValue(2));
11456    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11457    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11458    Results.push_back(cpOutH.getValue(1));
11459    return;
11460  }
11461  case ISD::ATOMIC_LOAD_ADD:
11462  case ISD::ATOMIC_LOAD_AND:
11463  case ISD::ATOMIC_LOAD_NAND:
11464  case ISD::ATOMIC_LOAD_OR:
11465  case ISD::ATOMIC_LOAD_SUB:
11466  case ISD::ATOMIC_LOAD_XOR:
11467  case ISD::ATOMIC_SWAP: {
11468    unsigned Opc;
11469    switch (N->getOpcode()) {
11470    default: llvm_unreachable("Unexpected opcode");
11471    case ISD::ATOMIC_LOAD_ADD:
11472      Opc = X86ISD::ATOMADD64_DAG;
11473      break;
11474    case ISD::ATOMIC_LOAD_AND:
11475      Opc = X86ISD::ATOMAND64_DAG;
11476      break;
11477    case ISD::ATOMIC_LOAD_NAND:
11478      Opc = X86ISD::ATOMNAND64_DAG;
11479      break;
11480    case ISD::ATOMIC_LOAD_OR:
11481      Opc = X86ISD::ATOMOR64_DAG;
11482      break;
11483    case ISD::ATOMIC_LOAD_SUB:
11484      Opc = X86ISD::ATOMSUB64_DAG;
11485      break;
11486    case ISD::ATOMIC_LOAD_XOR:
11487      Opc = X86ISD::ATOMXOR64_DAG;
11488      break;
11489    case ISD::ATOMIC_SWAP:
11490      Opc = X86ISD::ATOMSWAP64_DAG;
11491      break;
11492    }
11493    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11494    return;
11495  }
11496  case ISD::ATOMIC_LOAD:
11497    ReplaceATOMIC_LOAD(N, Results, DAG);
11498  }
11499}
11500
11501const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11502  switch (Opcode) {
11503  default: return NULL;
11504  case X86ISD::BSF:                return "X86ISD::BSF";
11505  case X86ISD::BSR:                return "X86ISD::BSR";
11506  case X86ISD::SHLD:               return "X86ISD::SHLD";
11507  case X86ISD::SHRD:               return "X86ISD::SHRD";
11508  case X86ISD::FAND:               return "X86ISD::FAND";
11509  case X86ISD::FOR:                return "X86ISD::FOR";
11510  case X86ISD::FXOR:               return "X86ISD::FXOR";
11511  case X86ISD::FSRL:               return "X86ISD::FSRL";
11512  case X86ISD::FILD:               return "X86ISD::FILD";
11513  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11514  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11515  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11516  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11517  case X86ISD::FLD:                return "X86ISD::FLD";
11518  case X86ISD::FST:                return "X86ISD::FST";
11519  case X86ISD::CALL:               return "X86ISD::CALL";
11520  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11521  case X86ISD::BT:                 return "X86ISD::BT";
11522  case X86ISD::CMP:                return "X86ISD::CMP";
11523  case X86ISD::COMI:               return "X86ISD::COMI";
11524  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11525  case X86ISD::SETCC:              return "X86ISD::SETCC";
11526  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11527  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11528  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11529  case X86ISD::CMOV:               return "X86ISD::CMOV";
11530  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11531  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11532  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11533  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11534  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11535  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11536  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11537  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11538  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11539  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11540  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11541  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11542  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11543  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11544  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11545  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11546  case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11547  case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11548  case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11549  case X86ISD::HADD:               return "X86ISD::HADD";
11550  case X86ISD::HSUB:               return "X86ISD::HSUB";
11551  case X86ISD::FHADD:              return "X86ISD::FHADD";
11552  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11553  case X86ISD::FMAX:               return "X86ISD::FMAX";
11554  case X86ISD::FMIN:               return "X86ISD::FMIN";
11555  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11556  case X86ISD::FMINC:              return "X86ISD::FMINC";
11557  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11558  case X86ISD::FRCP:               return "X86ISD::FRCP";
11559  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11560  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11561  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11562  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11563  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11564  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11565  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11566  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11567  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11568  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11569  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11570  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11571  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11572  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11573  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11574  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11575  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11576  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11577  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11578  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11579  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11580  case X86ISD::VSHL:               return "X86ISD::VSHL";
11581  case X86ISD::VSRL:               return "X86ISD::VSRL";
11582  case X86ISD::VSRA:               return "X86ISD::VSRA";
11583  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11584  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11585  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11586  case X86ISD::CMPP:               return "X86ISD::CMPP";
11587  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11588  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11589  case X86ISD::ADD:                return "X86ISD::ADD";
11590  case X86ISD::SUB:                return "X86ISD::SUB";
11591  case X86ISD::ADC:                return "X86ISD::ADC";
11592  case X86ISD::SBB:                return "X86ISD::SBB";
11593  case X86ISD::SMUL:               return "X86ISD::SMUL";
11594  case X86ISD::UMUL:               return "X86ISD::UMUL";
11595  case X86ISD::INC:                return "X86ISD::INC";
11596  case X86ISD::DEC:                return "X86ISD::DEC";
11597  case X86ISD::OR:                 return "X86ISD::OR";
11598  case X86ISD::XOR:                return "X86ISD::XOR";
11599  case X86ISD::AND:                return "X86ISD::AND";
11600  case X86ISD::ANDN:               return "X86ISD::ANDN";
11601  case X86ISD::BLSI:               return "X86ISD::BLSI";
11602  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11603  case X86ISD::BLSR:               return "X86ISD::BLSR";
11604  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11605  case X86ISD::PTEST:              return "X86ISD::PTEST";
11606  case X86ISD::TESTP:              return "X86ISD::TESTP";
11607  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11608  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11609  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11610  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11611  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11612  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11613  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11614  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11615  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11616  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11617  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11618  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11619  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11620  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11621  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11622  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11623  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11624  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11625  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11626  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11627  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11628  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11629  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11630  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11631  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11632  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11633  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11634  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11635  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11636  case X86ISD::SAHF:               return "X86ISD::SAHF";
11637  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11638  case X86ISD::FMADD:              return "X86ISD::FMADD";
11639  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11640  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11641  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11642  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11643  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11644  }
11645}
11646
11647// isLegalAddressingMode - Return true if the addressing mode represented
11648// by AM is legal for this target, for a load/store of the specified type.
11649bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11650                                              Type *Ty) const {
11651  // X86 supports extremely general addressing modes.
11652  CodeModel::Model M = getTargetMachine().getCodeModel();
11653  Reloc::Model R = getTargetMachine().getRelocationModel();
11654
11655  // X86 allows a sign-extended 32-bit immediate field as a displacement.
11656  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11657    return false;
11658
11659  if (AM.BaseGV) {
11660    unsigned GVFlags =
11661      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11662
11663    // If a reference to this global requires an extra load, we can't fold it.
11664    if (isGlobalStubReference(GVFlags))
11665      return false;
11666
11667    // If BaseGV requires a register for the PIC base, we cannot also have a
11668    // BaseReg specified.
11669    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11670      return false;
11671
11672    // If lower 4G is not available, then we must use rip-relative addressing.
11673    if ((M != CodeModel::Small || R != Reloc::Static) &&
11674        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11675      return false;
11676  }
11677
11678  switch (AM.Scale) {
11679  case 0:
11680  case 1:
11681  case 2:
11682  case 4:
11683  case 8:
11684    // These scales always work.
11685    break;
11686  case 3:
11687  case 5:
11688  case 9:
11689    // These scales are formed with basereg+scalereg.  Only accept if there is
11690    // no basereg yet.
11691    if (AM.HasBaseReg)
11692      return false;
11693    break;
11694  default:  // Other stuff never works.
11695    return false;
11696  }
11697
11698  return true;
11699}
11700
11701
11702bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11703  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11704    return false;
11705  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11706  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11707  if (NumBits1 <= NumBits2)
11708    return false;
11709  return true;
11710}
11711
11712bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11713  return Imm == (int32_t)Imm;
11714}
11715
11716bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11717  // Can also use sub to handle negated immediates.
11718  return Imm == (int32_t)Imm;
11719}
11720
11721bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11722  if (!VT1.isInteger() || !VT2.isInteger())
11723    return false;
11724  unsigned NumBits1 = VT1.getSizeInBits();
11725  unsigned NumBits2 = VT2.getSizeInBits();
11726  if (NumBits1 <= NumBits2)
11727    return false;
11728  return true;
11729}
11730
11731bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11732  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11733  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11734}
11735
11736bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11737  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11738  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11739}
11740
11741bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11742  // i16 instructions are longer (0x66 prefix) and potentially slower.
11743  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11744}
11745
11746/// isShuffleMaskLegal - Targets can use this to indicate that they only
11747/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11748/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11749/// are assumed to be legal.
11750bool
11751X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11752                                      EVT VT) const {
11753  // Very little shuffling can be done for 64-bit vectors right now.
11754  if (VT.getSizeInBits() == 64)
11755    return false;
11756
11757  // FIXME: pshufb, blends, shifts.
11758  return (VT.getVectorNumElements() == 2 ||
11759          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11760          isMOVLMask(M, VT) ||
11761          isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11762          isPSHUFDMask(M, VT) ||
11763          isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11764          isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11765          isPALIGNRMask(M, VT, Subtarget) ||
11766          isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11767          isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11768          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11769          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11770}
11771
11772bool
11773X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11774                                          EVT VT) const {
11775  unsigned NumElts = VT.getVectorNumElements();
11776  // FIXME: This collection of masks seems suspect.
11777  if (NumElts == 2)
11778    return true;
11779  if (NumElts == 4 && VT.is128BitVector()) {
11780    return (isMOVLMask(Mask, VT)  ||
11781            isCommutedMOVLMask(Mask, VT, true) ||
11782            isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11783            isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11784  }
11785  return false;
11786}
11787
11788//===----------------------------------------------------------------------===//
11789//                           X86 Scheduler Hooks
11790//===----------------------------------------------------------------------===//
11791
11792// private utility function
11793MachineBasicBlock *
11794X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11795                                                       MachineBasicBlock *MBB,
11796                                                       unsigned regOpc,
11797                                                       unsigned immOpc,
11798                                                       unsigned LoadOpc,
11799                                                       unsigned CXchgOpc,
11800                                                       unsigned notOpc,
11801                                                       unsigned EAXreg,
11802                                                 const TargetRegisterClass *RC,
11803                                                       bool Invert) const {
11804  // For the atomic bitwise operator, we generate
11805  //   thisMBB:
11806  //   newMBB:
11807  //     ld  t1 = [bitinstr.addr]
11808  //     op  t2 = t1, [bitinstr.val]
11809  //     not t3 = t2  (if Invert)
11810  //     mov EAX = t1
11811  //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11812  //     bz  newMBB
11813  //     fallthrough -->nextMBB
11814  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11815  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11816  MachineFunction::iterator MBBIter = MBB;
11817  ++MBBIter;
11818
11819  /// First build the CFG
11820  MachineFunction *F = MBB->getParent();
11821  MachineBasicBlock *thisMBB = MBB;
11822  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11823  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11824  F->insert(MBBIter, newMBB);
11825  F->insert(MBBIter, nextMBB);
11826
11827  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11828  nextMBB->splice(nextMBB->begin(), thisMBB,
11829                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11830                  thisMBB->end());
11831  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11832
11833  // Update thisMBB to fall through to newMBB
11834  thisMBB->addSuccessor(newMBB);
11835
11836  // newMBB jumps to itself and fall through to nextMBB
11837  newMBB->addSuccessor(nextMBB);
11838  newMBB->addSuccessor(newMBB);
11839
11840  // Insert instructions into newMBB based on incoming instruction
11841  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11842         "unexpected number of operands");
11843  DebugLoc dl = bInstr->getDebugLoc();
11844  MachineOperand& destOper = bInstr->getOperand(0);
11845  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11846  int numArgs = bInstr->getNumOperands() - 1;
11847  for (int i=0; i < numArgs; ++i)
11848    argOpers[i] = &bInstr->getOperand(i+1);
11849
11850  // x86 address has 4 operands: base, index, scale, and displacement
11851  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11852  int valArgIndx = lastAddrIndx + 1;
11853
11854  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11855  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11856  for (int i=0; i <= lastAddrIndx; ++i)
11857    (*MIB).addOperand(*argOpers[i]);
11858
11859  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11860  assert((argOpers[valArgIndx]->isReg() ||
11861          argOpers[valArgIndx]->isImm()) &&
11862         "invalid operand");
11863  if (argOpers[valArgIndx]->isReg())
11864    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11865  else
11866    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11867  MIB.addReg(t1);
11868  (*MIB).addOperand(*argOpers[valArgIndx]);
11869
11870  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11871  if (Invert) {
11872    MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11873  }
11874  else
11875    t3 = t2;
11876
11877  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11878  MIB.addReg(t1);
11879
11880  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11881  for (int i=0; i <= lastAddrIndx; ++i)
11882    (*MIB).addOperand(*argOpers[i]);
11883  MIB.addReg(t3);
11884  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11885  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11886                    bInstr->memoperands_end());
11887
11888  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11889  MIB.addReg(EAXreg);
11890
11891  // insert branch
11892  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11893
11894  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11895  return nextMBB;
11896}
11897
11898// private utility function:  64 bit atomics on 32 bit host.
11899MachineBasicBlock *
11900X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11901                                                       MachineBasicBlock *MBB,
11902                                                       unsigned regOpcL,
11903                                                       unsigned regOpcH,
11904                                                       unsigned immOpcL,
11905                                                       unsigned immOpcH,
11906                                                       bool Invert) const {
11907  // For the atomic bitwise operator, we generate
11908  //   thisMBB (instructions are in pairs, except cmpxchg8b)
11909  //     ld t1,t2 = [bitinstr.addr]
11910  //   newMBB:
11911  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11912  //     op  t5, t6 <- out1, out2, [bitinstr.val]
11913  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11914  //     neg t7, t8 < t5, t6  (if Invert)
11915  //     mov ECX, EBX <- t5, t6
11916  //     mov EAX, EDX <- t1, t2
11917  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11918  //     mov t3, t4 <- EAX, EDX
11919  //     bz  newMBB
11920  //     result in out1, out2
11921  //     fallthrough -->nextMBB
11922
11923  const TargetRegisterClass *RC = &X86::GR32RegClass;
11924  const unsigned LoadOpc = X86::MOV32rm;
11925  const unsigned NotOpc = X86::NOT32r;
11926  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11927  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11928  MachineFunction::iterator MBBIter = MBB;
11929  ++MBBIter;
11930
11931  /// First build the CFG
11932  MachineFunction *F = MBB->getParent();
11933  MachineBasicBlock *thisMBB = MBB;
11934  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11935  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11936  F->insert(MBBIter, newMBB);
11937  F->insert(MBBIter, nextMBB);
11938
11939  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11940  nextMBB->splice(nextMBB->begin(), thisMBB,
11941                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11942                  thisMBB->end());
11943  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11944
11945  // Update thisMBB to fall through to newMBB
11946  thisMBB->addSuccessor(newMBB);
11947
11948  // newMBB jumps to itself and fall through to nextMBB
11949  newMBB->addSuccessor(nextMBB);
11950  newMBB->addSuccessor(newMBB);
11951
11952  DebugLoc dl = bInstr->getDebugLoc();
11953  // Insert instructions into newMBB based on incoming instruction
11954  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11955  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11956         "unexpected number of operands");
11957  MachineOperand& dest1Oper = bInstr->getOperand(0);
11958  MachineOperand& dest2Oper = bInstr->getOperand(1);
11959  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11960  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11961    argOpers[i] = &bInstr->getOperand(i+2);
11962
11963    // We use some of the operands multiple times, so conservatively just
11964    // clear any kill flags that might be present.
11965    if (argOpers[i]->isReg() && argOpers[i]->isUse())
11966      argOpers[i]->setIsKill(false);
11967  }
11968
11969  // x86 address has 5 operands: base, index, scale, displacement, and segment.
11970  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11971
11972  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11973  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11974  for (int i=0; i <= lastAddrIndx; ++i)
11975    (*MIB).addOperand(*argOpers[i]);
11976  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11977  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11978  // add 4 to displacement.
11979  for (int i=0; i <= lastAddrIndx-2; ++i)
11980    (*MIB).addOperand(*argOpers[i]);
11981  MachineOperand newOp3 = *(argOpers[3]);
11982  if (newOp3.isImm())
11983    newOp3.setImm(newOp3.getImm()+4);
11984  else
11985    newOp3.setOffset(newOp3.getOffset()+4);
11986  (*MIB).addOperand(newOp3);
11987  (*MIB).addOperand(*argOpers[lastAddrIndx]);
11988
11989  // t3/4 are defined later, at the bottom of the loop
11990  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11991  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11992  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11993    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11994  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11995    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11996
11997  // The subsequent operations should be using the destination registers of
11998  // the PHI instructions.
11999  t1 = dest1Oper.getReg();
12000  t2 = dest2Oper.getReg();
12001
12002  int valArgIndx = lastAddrIndx + 1;
12003  assert((argOpers[valArgIndx]->isReg() ||
12004          argOpers[valArgIndx]->isImm()) &&
12005         "invalid operand");
12006  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12007  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12008  if (argOpers[valArgIndx]->isReg())
12009    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12010  else
12011    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12012  if (regOpcL != X86::MOV32rr)
12013    MIB.addReg(t1);
12014  (*MIB).addOperand(*argOpers[valArgIndx]);
12015  assert(argOpers[valArgIndx + 1]->isReg() ==
12016         argOpers[valArgIndx]->isReg());
12017  assert(argOpers[valArgIndx + 1]->isImm() ==
12018         argOpers[valArgIndx]->isImm());
12019  if (argOpers[valArgIndx + 1]->isReg())
12020    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12021  else
12022    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12023  if (regOpcH != X86::MOV32rr)
12024    MIB.addReg(t2);
12025  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12026
12027  unsigned t7, t8;
12028  if (Invert) {
12029    t7 = F->getRegInfo().createVirtualRegister(RC);
12030    t8 = F->getRegInfo().createVirtualRegister(RC);
12031    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12032    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12033  } else {
12034    t7 = t5;
12035    t8 = t6;
12036  }
12037
12038  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12039  MIB.addReg(t1);
12040  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12041  MIB.addReg(t2);
12042
12043  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12044  MIB.addReg(t7);
12045  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12046  MIB.addReg(t8);
12047
12048  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12049  for (int i=0; i <= lastAddrIndx; ++i)
12050    (*MIB).addOperand(*argOpers[i]);
12051
12052  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12053  (*MIB).setMemRefs(bInstr->memoperands_begin(),
12054                    bInstr->memoperands_end());
12055
12056  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12057  MIB.addReg(X86::EAX);
12058  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12059  MIB.addReg(X86::EDX);
12060
12061  // insert branch
12062  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12063
12064  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12065  return nextMBB;
12066}
12067
12068// private utility function
12069MachineBasicBlock *
12070X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12071                                                      MachineBasicBlock *MBB,
12072                                                      unsigned cmovOpc) const {
12073  // For the atomic min/max operator, we generate
12074  //   thisMBB:
12075  //   newMBB:
12076  //     ld t1 = [min/max.addr]
12077  //     mov t2 = [min/max.val]
12078  //     cmp  t1, t2
12079  //     cmov[cond] t2 = t1
12080  //     mov EAX = t1
12081  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12082  //     bz   newMBB
12083  //     fallthrough -->nextMBB
12084  //
12085  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12086  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12087  MachineFunction::iterator MBBIter = MBB;
12088  ++MBBIter;
12089
12090  /// First build the CFG
12091  MachineFunction *F = MBB->getParent();
12092  MachineBasicBlock *thisMBB = MBB;
12093  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12094  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12095  F->insert(MBBIter, newMBB);
12096  F->insert(MBBIter, nextMBB);
12097
12098  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12099  nextMBB->splice(nextMBB->begin(), thisMBB,
12100                  llvm::next(MachineBasicBlock::iterator(mInstr)),
12101                  thisMBB->end());
12102  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12103
12104  // Update thisMBB to fall through to newMBB
12105  thisMBB->addSuccessor(newMBB);
12106
12107  // newMBB jumps to newMBB and fall through to nextMBB
12108  newMBB->addSuccessor(nextMBB);
12109  newMBB->addSuccessor(newMBB);
12110
12111  DebugLoc dl = mInstr->getDebugLoc();
12112  // Insert instructions into newMBB based on incoming instruction
12113  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12114         "unexpected number of operands");
12115  MachineOperand& destOper = mInstr->getOperand(0);
12116  MachineOperand* argOpers[2 + X86::AddrNumOperands];
12117  int numArgs = mInstr->getNumOperands() - 1;
12118  for (int i=0; i < numArgs; ++i)
12119    argOpers[i] = &mInstr->getOperand(i+1);
12120
12121  // x86 address has 4 operands: base, index, scale, and displacement
12122  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12123  int valArgIndx = lastAddrIndx + 1;
12124
12125  unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12126  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12127  for (int i=0; i <= lastAddrIndx; ++i)
12128    (*MIB).addOperand(*argOpers[i]);
12129
12130  // We only support register and immediate values
12131  assert((argOpers[valArgIndx]->isReg() ||
12132          argOpers[valArgIndx]->isImm()) &&
12133         "invalid operand");
12134
12135  unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12136  if (argOpers[valArgIndx]->isReg())
12137    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12138  else
12139    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12140  (*MIB).addOperand(*argOpers[valArgIndx]);
12141
12142  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12143  MIB.addReg(t1);
12144
12145  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12146  MIB.addReg(t1);
12147  MIB.addReg(t2);
12148
12149  // Generate movc
12150  unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12151  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12152  MIB.addReg(t2);
12153  MIB.addReg(t1);
12154
12155  // Cmp and exchange if none has modified the memory location
12156  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12157  for (int i=0; i <= lastAddrIndx; ++i)
12158    (*MIB).addOperand(*argOpers[i]);
12159  MIB.addReg(t3);
12160  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12161  (*MIB).setMemRefs(mInstr->memoperands_begin(),
12162                    mInstr->memoperands_end());
12163
12164  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12165  MIB.addReg(X86::EAX);
12166
12167  // insert branch
12168  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12169
12170  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12171  return nextMBB;
12172}
12173
12174// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12175// or XMM0_V32I8 in AVX all of this code can be replaced with that
12176// in the .td file.
12177MachineBasicBlock *
12178X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12179                            unsigned numArgs, bool memArg) const {
12180  assert(Subtarget->hasSSE42() &&
12181         "Target must have SSE4.2 or AVX features enabled");
12182
12183  DebugLoc dl = MI->getDebugLoc();
12184  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12185  unsigned Opc;
12186  if (!Subtarget->hasAVX()) {
12187    if (memArg)
12188      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12189    else
12190      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12191  } else {
12192    if (memArg)
12193      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12194    else
12195      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12196  }
12197
12198  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12199  for (unsigned i = 0; i < numArgs; ++i) {
12200    MachineOperand &Op = MI->getOperand(i+1);
12201    if (!(Op.isReg() && Op.isImplicit()))
12202      MIB.addOperand(Op);
12203  }
12204  BuildMI(*BB, MI, dl,
12205    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12206    .addReg(X86::XMM0);
12207
12208  MI->eraseFromParent();
12209  return BB;
12210}
12211
12212MachineBasicBlock *
12213X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12214  DebugLoc dl = MI->getDebugLoc();
12215  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12216
12217  // Address into RAX/EAX, other two args into ECX, EDX.
12218  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12219  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12220  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12221  for (int i = 0; i < X86::AddrNumOperands; ++i)
12222    MIB.addOperand(MI->getOperand(i));
12223
12224  unsigned ValOps = X86::AddrNumOperands;
12225  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12226    .addReg(MI->getOperand(ValOps).getReg());
12227  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12228    .addReg(MI->getOperand(ValOps+1).getReg());
12229
12230  // The instruction doesn't actually take any operands though.
12231  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12232
12233  MI->eraseFromParent(); // The pseudo is gone now.
12234  return BB;
12235}
12236
12237MachineBasicBlock *
12238X86TargetLowering::EmitVAARG64WithCustomInserter(
12239                   MachineInstr *MI,
12240                   MachineBasicBlock *MBB) const {
12241  // Emit va_arg instruction on X86-64.
12242
12243  // Operands to this pseudo-instruction:
12244  // 0  ) Output        : destination address (reg)
12245  // 1-5) Input         : va_list address (addr, i64mem)
12246  // 6  ) ArgSize       : Size (in bytes) of vararg type
12247  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12248  // 8  ) Align         : Alignment of type
12249  // 9  ) EFLAGS (implicit-def)
12250
12251  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12252  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12253
12254  unsigned DestReg = MI->getOperand(0).getReg();
12255  MachineOperand &Base = MI->getOperand(1);
12256  MachineOperand &Scale = MI->getOperand(2);
12257  MachineOperand &Index = MI->getOperand(3);
12258  MachineOperand &Disp = MI->getOperand(4);
12259  MachineOperand &Segment = MI->getOperand(5);
12260  unsigned ArgSize = MI->getOperand(6).getImm();
12261  unsigned ArgMode = MI->getOperand(7).getImm();
12262  unsigned Align = MI->getOperand(8).getImm();
12263
12264  // Memory Reference
12265  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12266  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12267  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12268
12269  // Machine Information
12270  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12271  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12272  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12273  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12274  DebugLoc DL = MI->getDebugLoc();
12275
12276  // struct va_list {
12277  //   i32   gp_offset
12278  //   i32   fp_offset
12279  //   i64   overflow_area (address)
12280  //   i64   reg_save_area (address)
12281  // }
12282  // sizeof(va_list) = 24
12283  // alignment(va_list) = 8
12284
12285  unsigned TotalNumIntRegs = 6;
12286  unsigned TotalNumXMMRegs = 8;
12287  bool UseGPOffset = (ArgMode == 1);
12288  bool UseFPOffset = (ArgMode == 2);
12289  unsigned MaxOffset = TotalNumIntRegs * 8 +
12290                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12291
12292  /* Align ArgSize to a multiple of 8 */
12293  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12294  bool NeedsAlign = (Align > 8);
12295
12296  MachineBasicBlock *thisMBB = MBB;
12297  MachineBasicBlock *overflowMBB;
12298  MachineBasicBlock *offsetMBB;
12299  MachineBasicBlock *endMBB;
12300
12301  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12302  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12303  unsigned OffsetReg = 0;
12304
12305  if (!UseGPOffset && !UseFPOffset) {
12306    // If we only pull from the overflow region, we don't create a branch.
12307    // We don't need to alter control flow.
12308    OffsetDestReg = 0; // unused
12309    OverflowDestReg = DestReg;
12310
12311    offsetMBB = NULL;
12312    overflowMBB = thisMBB;
12313    endMBB = thisMBB;
12314  } else {
12315    // First emit code to check if gp_offset (or fp_offset) is below the bound.
12316    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12317    // If not, pull from overflow_area. (branch to overflowMBB)
12318    //
12319    //       thisMBB
12320    //         |     .
12321    //         |        .
12322    //     offsetMBB   overflowMBB
12323    //         |        .
12324    //         |     .
12325    //        endMBB
12326
12327    // Registers for the PHI in endMBB
12328    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12329    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12330
12331    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12332    MachineFunction *MF = MBB->getParent();
12333    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12334    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12335    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12336
12337    MachineFunction::iterator MBBIter = MBB;
12338    ++MBBIter;
12339
12340    // Insert the new basic blocks
12341    MF->insert(MBBIter, offsetMBB);
12342    MF->insert(MBBIter, overflowMBB);
12343    MF->insert(MBBIter, endMBB);
12344
12345    // Transfer the remainder of MBB and its successor edges to endMBB.
12346    endMBB->splice(endMBB->begin(), thisMBB,
12347                    llvm::next(MachineBasicBlock::iterator(MI)),
12348                    thisMBB->end());
12349    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12350
12351    // Make offsetMBB and overflowMBB successors of thisMBB
12352    thisMBB->addSuccessor(offsetMBB);
12353    thisMBB->addSuccessor(overflowMBB);
12354
12355    // endMBB is a successor of both offsetMBB and overflowMBB
12356    offsetMBB->addSuccessor(endMBB);
12357    overflowMBB->addSuccessor(endMBB);
12358
12359    // Load the offset value into a register
12360    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12361    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12362      .addOperand(Base)
12363      .addOperand(Scale)
12364      .addOperand(Index)
12365      .addDisp(Disp, UseFPOffset ? 4 : 0)
12366      .addOperand(Segment)
12367      .setMemRefs(MMOBegin, MMOEnd);
12368
12369    // Check if there is enough room left to pull this argument.
12370    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12371      .addReg(OffsetReg)
12372      .addImm(MaxOffset + 8 - ArgSizeA8);
12373
12374    // Branch to "overflowMBB" if offset >= max
12375    // Fall through to "offsetMBB" otherwise
12376    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12377      .addMBB(overflowMBB);
12378  }
12379
12380  // In offsetMBB, emit code to use the reg_save_area.
12381  if (offsetMBB) {
12382    assert(OffsetReg != 0);
12383
12384    // Read the reg_save_area address.
12385    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12386    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12387      .addOperand(Base)
12388      .addOperand(Scale)
12389      .addOperand(Index)
12390      .addDisp(Disp, 16)
12391      .addOperand(Segment)
12392      .setMemRefs(MMOBegin, MMOEnd);
12393
12394    // Zero-extend the offset
12395    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12396      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12397        .addImm(0)
12398        .addReg(OffsetReg)
12399        .addImm(X86::sub_32bit);
12400
12401    // Add the offset to the reg_save_area to get the final address.
12402    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12403      .addReg(OffsetReg64)
12404      .addReg(RegSaveReg);
12405
12406    // Compute the offset for the next argument
12407    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12408    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12409      .addReg(OffsetReg)
12410      .addImm(UseFPOffset ? 16 : 8);
12411
12412    // Store it back into the va_list.
12413    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12414      .addOperand(Base)
12415      .addOperand(Scale)
12416      .addOperand(Index)
12417      .addDisp(Disp, UseFPOffset ? 4 : 0)
12418      .addOperand(Segment)
12419      .addReg(NextOffsetReg)
12420      .setMemRefs(MMOBegin, MMOEnd);
12421
12422    // Jump to endMBB
12423    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12424      .addMBB(endMBB);
12425  }
12426
12427  //
12428  // Emit code to use overflow area
12429  //
12430
12431  // Load the overflow_area address into a register.
12432  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12433  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12434    .addOperand(Base)
12435    .addOperand(Scale)
12436    .addOperand(Index)
12437    .addDisp(Disp, 8)
12438    .addOperand(Segment)
12439    .setMemRefs(MMOBegin, MMOEnd);
12440
12441  // If we need to align it, do so. Otherwise, just copy the address
12442  // to OverflowDestReg.
12443  if (NeedsAlign) {
12444    // Align the overflow address
12445    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12446    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12447
12448    // aligned_addr = (addr + (align-1)) & ~(align-1)
12449    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12450      .addReg(OverflowAddrReg)
12451      .addImm(Align-1);
12452
12453    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12454      .addReg(TmpReg)
12455      .addImm(~(uint64_t)(Align-1));
12456  } else {
12457    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12458      .addReg(OverflowAddrReg);
12459  }
12460
12461  // Compute the next overflow address after this argument.
12462  // (the overflow address should be kept 8-byte aligned)
12463  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12464  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12465    .addReg(OverflowDestReg)
12466    .addImm(ArgSizeA8);
12467
12468  // Store the new overflow address.
12469  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12470    .addOperand(Base)
12471    .addOperand(Scale)
12472    .addOperand(Index)
12473    .addDisp(Disp, 8)
12474    .addOperand(Segment)
12475    .addReg(NextAddrReg)
12476    .setMemRefs(MMOBegin, MMOEnd);
12477
12478  // If we branched, emit the PHI to the front of endMBB.
12479  if (offsetMBB) {
12480    BuildMI(*endMBB, endMBB->begin(), DL,
12481            TII->get(X86::PHI), DestReg)
12482      .addReg(OffsetDestReg).addMBB(offsetMBB)
12483      .addReg(OverflowDestReg).addMBB(overflowMBB);
12484  }
12485
12486  // Erase the pseudo instruction
12487  MI->eraseFromParent();
12488
12489  return endMBB;
12490}
12491
12492MachineBasicBlock *
12493X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12494                                                 MachineInstr *MI,
12495                                                 MachineBasicBlock *MBB) const {
12496  // Emit code to save XMM registers to the stack. The ABI says that the
12497  // number of registers to save is given in %al, so it's theoretically
12498  // possible to do an indirect jump trick to avoid saving all of them,
12499  // however this code takes a simpler approach and just executes all
12500  // of the stores if %al is non-zero. It's less code, and it's probably
12501  // easier on the hardware branch predictor, and stores aren't all that
12502  // expensive anyway.
12503
12504  // Create the new basic blocks. One block contains all the XMM stores,
12505  // and one block is the final destination regardless of whether any
12506  // stores were performed.
12507  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12508  MachineFunction *F = MBB->getParent();
12509  MachineFunction::iterator MBBIter = MBB;
12510  ++MBBIter;
12511  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12512  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12513  F->insert(MBBIter, XMMSaveMBB);
12514  F->insert(MBBIter, EndMBB);
12515
12516  // Transfer the remainder of MBB and its successor edges to EndMBB.
12517  EndMBB->splice(EndMBB->begin(), MBB,
12518                 llvm::next(MachineBasicBlock::iterator(MI)),
12519                 MBB->end());
12520  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12521
12522  // The original block will now fall through to the XMM save block.
12523  MBB->addSuccessor(XMMSaveMBB);
12524  // The XMMSaveMBB will fall through to the end block.
12525  XMMSaveMBB->addSuccessor(EndMBB);
12526
12527  // Now add the instructions.
12528  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12529  DebugLoc DL = MI->getDebugLoc();
12530
12531  unsigned CountReg = MI->getOperand(0).getReg();
12532  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12533  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12534
12535  if (!Subtarget->isTargetWin64()) {
12536    // If %al is 0, branch around the XMM save block.
12537    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12538    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12539    MBB->addSuccessor(EndMBB);
12540  }
12541
12542  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12543  // In the XMM save block, save all the XMM argument registers.
12544  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12545    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12546    MachineMemOperand *MMO =
12547      F->getMachineMemOperand(
12548          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12549        MachineMemOperand::MOStore,
12550        /*Size=*/16, /*Align=*/16);
12551    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12552      .addFrameIndex(RegSaveFrameIndex)
12553      .addImm(/*Scale=*/1)
12554      .addReg(/*IndexReg=*/0)
12555      .addImm(/*Disp=*/Offset)
12556      .addReg(/*Segment=*/0)
12557      .addReg(MI->getOperand(i).getReg())
12558      .addMemOperand(MMO);
12559  }
12560
12561  MI->eraseFromParent();   // The pseudo instruction is gone now.
12562
12563  return EndMBB;
12564}
12565
12566// The EFLAGS operand of SelectItr might be missing a kill marker
12567// because there were multiple uses of EFLAGS, and ISel didn't know
12568// which to mark. Figure out whether SelectItr should have had a
12569// kill marker, and set it if it should. Returns the correct kill
12570// marker value.
12571static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12572                                     MachineBasicBlock* BB,
12573                                     const TargetRegisterInfo* TRI) {
12574  // Scan forward through BB for a use/def of EFLAGS.
12575  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12576  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12577    const MachineInstr& mi = *miI;
12578    if (mi.readsRegister(X86::EFLAGS))
12579      return false;
12580    if (mi.definesRegister(X86::EFLAGS))
12581      break; // Should have kill-flag - update below.
12582  }
12583
12584  // If we hit the end of the block, check whether EFLAGS is live into a
12585  // successor.
12586  if (miI == BB->end()) {
12587    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12588                                          sEnd = BB->succ_end();
12589         sItr != sEnd; ++sItr) {
12590      MachineBasicBlock* succ = *sItr;
12591      if (succ->isLiveIn(X86::EFLAGS))
12592        return false;
12593    }
12594  }
12595
12596  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12597  // out. SelectMI should have a kill flag on EFLAGS.
12598  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12599  return true;
12600}
12601
12602MachineBasicBlock *
12603X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12604                                     MachineBasicBlock *BB) const {
12605  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12606  DebugLoc DL = MI->getDebugLoc();
12607
12608  // To "insert" a SELECT_CC instruction, we actually have to insert the
12609  // diamond control-flow pattern.  The incoming instruction knows the
12610  // destination vreg to set, the condition code register to branch on, the
12611  // true/false values to select between, and a branch opcode to use.
12612  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12613  MachineFunction::iterator It = BB;
12614  ++It;
12615
12616  //  thisMBB:
12617  //  ...
12618  //   TrueVal = ...
12619  //   cmpTY ccX, r1, r2
12620  //   bCC copy1MBB
12621  //   fallthrough --> copy0MBB
12622  MachineBasicBlock *thisMBB = BB;
12623  MachineFunction *F = BB->getParent();
12624  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12625  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12626  F->insert(It, copy0MBB);
12627  F->insert(It, sinkMBB);
12628
12629  // If the EFLAGS register isn't dead in the terminator, then claim that it's
12630  // live into the sink and copy blocks.
12631  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12632  if (!MI->killsRegister(X86::EFLAGS) &&
12633      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12634    copy0MBB->addLiveIn(X86::EFLAGS);
12635    sinkMBB->addLiveIn(X86::EFLAGS);
12636  }
12637
12638  // Transfer the remainder of BB and its successor edges to sinkMBB.
12639  sinkMBB->splice(sinkMBB->begin(), BB,
12640                  llvm::next(MachineBasicBlock::iterator(MI)),
12641                  BB->end());
12642  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12643
12644  // Add the true and fallthrough blocks as its successors.
12645  BB->addSuccessor(copy0MBB);
12646  BB->addSuccessor(sinkMBB);
12647
12648  // Create the conditional branch instruction.
12649  unsigned Opc =
12650    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12651  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12652
12653  //  copy0MBB:
12654  //   %FalseValue = ...
12655  //   # fallthrough to sinkMBB
12656  copy0MBB->addSuccessor(sinkMBB);
12657
12658  //  sinkMBB:
12659  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12660  //  ...
12661  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12662          TII->get(X86::PHI), MI->getOperand(0).getReg())
12663    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12664    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12665
12666  MI->eraseFromParent();   // The pseudo instruction is gone now.
12667  return sinkMBB;
12668}
12669
12670MachineBasicBlock *
12671X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12672                                        bool Is64Bit) const {
12673  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12674  DebugLoc DL = MI->getDebugLoc();
12675  MachineFunction *MF = BB->getParent();
12676  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12677
12678  assert(getTargetMachine().Options.EnableSegmentedStacks);
12679
12680  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12681  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12682
12683  // BB:
12684  //  ... [Till the alloca]
12685  // If stacklet is not large enough, jump to mallocMBB
12686  //
12687  // bumpMBB:
12688  //  Allocate by subtracting from RSP
12689  //  Jump to continueMBB
12690  //
12691  // mallocMBB:
12692  //  Allocate by call to runtime
12693  //
12694  // continueMBB:
12695  //  ...
12696  //  [rest of original BB]
12697  //
12698
12699  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12700  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12701  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12702
12703  MachineRegisterInfo &MRI = MF->getRegInfo();
12704  const TargetRegisterClass *AddrRegClass =
12705    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12706
12707  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12708    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12709    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12710    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12711    sizeVReg = MI->getOperand(1).getReg(),
12712    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12713
12714  MachineFunction::iterator MBBIter = BB;
12715  ++MBBIter;
12716
12717  MF->insert(MBBIter, bumpMBB);
12718  MF->insert(MBBIter, mallocMBB);
12719  MF->insert(MBBIter, continueMBB);
12720
12721  continueMBB->splice(continueMBB->begin(), BB, llvm::next
12722                      (MachineBasicBlock::iterator(MI)), BB->end());
12723  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12724
12725  // Add code to the main basic block to check if the stack limit has been hit,
12726  // and if so, jump to mallocMBB otherwise to bumpMBB.
12727  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12728  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12729    .addReg(tmpSPVReg).addReg(sizeVReg);
12730  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12731    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12732    .addReg(SPLimitVReg);
12733  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12734
12735  // bumpMBB simply decreases the stack pointer, since we know the current
12736  // stacklet has enough space.
12737  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12738    .addReg(SPLimitVReg);
12739  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12740    .addReg(SPLimitVReg);
12741  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12742
12743  // Calls into a routine in libgcc to allocate more space from the heap.
12744  const uint32_t *RegMask =
12745    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12746  if (Is64Bit) {
12747    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12748      .addReg(sizeVReg);
12749    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12750      .addExternalSymbol("__morestack_allocate_stack_space")
12751      .addRegMask(RegMask)
12752      .addReg(X86::RDI, RegState::Implicit)
12753      .addReg(X86::RAX, RegState::ImplicitDefine);
12754  } else {
12755    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12756      .addImm(12);
12757    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12758    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12759      .addExternalSymbol("__morestack_allocate_stack_space")
12760      .addRegMask(RegMask)
12761      .addReg(X86::EAX, RegState::ImplicitDefine);
12762  }
12763
12764  if (!Is64Bit)
12765    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12766      .addImm(16);
12767
12768  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12769    .addReg(Is64Bit ? X86::RAX : X86::EAX);
12770  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12771
12772  // Set up the CFG correctly.
12773  BB->addSuccessor(bumpMBB);
12774  BB->addSuccessor(mallocMBB);
12775  mallocMBB->addSuccessor(continueMBB);
12776  bumpMBB->addSuccessor(continueMBB);
12777
12778  // Take care of the PHI nodes.
12779  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12780          MI->getOperand(0).getReg())
12781    .addReg(mallocPtrVReg).addMBB(mallocMBB)
12782    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12783
12784  // Delete the original pseudo instruction.
12785  MI->eraseFromParent();
12786
12787  // And we're done.
12788  return continueMBB;
12789}
12790
12791MachineBasicBlock *
12792X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12793                                          MachineBasicBlock *BB) const {
12794  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12795  DebugLoc DL = MI->getDebugLoc();
12796
12797  assert(!Subtarget->isTargetEnvMacho());
12798
12799  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12800  // non-trivial part is impdef of ESP.
12801
12802  if (Subtarget->isTargetWin64()) {
12803    if (Subtarget->isTargetCygMing()) {
12804      // ___chkstk(Mingw64):
12805      // Clobbers R10, R11, RAX and EFLAGS.
12806      // Updates RSP.
12807      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12808        .addExternalSymbol("___chkstk")
12809        .addReg(X86::RAX, RegState::Implicit)
12810        .addReg(X86::RSP, RegState::Implicit)
12811        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12812        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12813        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12814    } else {
12815      // __chkstk(MSVCRT): does not update stack pointer.
12816      // Clobbers R10, R11 and EFLAGS.
12817      // FIXME: RAX(allocated size) might be reused and not killed.
12818      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12819        .addExternalSymbol("__chkstk")
12820        .addReg(X86::RAX, RegState::Implicit)
12821        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12822      // RAX has the offset to subtracted from RSP.
12823      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12824        .addReg(X86::RSP)
12825        .addReg(X86::RAX);
12826    }
12827  } else {
12828    const char *StackProbeSymbol =
12829      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12830
12831    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12832      .addExternalSymbol(StackProbeSymbol)
12833      .addReg(X86::EAX, RegState::Implicit)
12834      .addReg(X86::ESP, RegState::Implicit)
12835      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12836      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12837      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12838  }
12839
12840  MI->eraseFromParent();   // The pseudo instruction is gone now.
12841  return BB;
12842}
12843
12844MachineBasicBlock *
12845X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12846                                      MachineBasicBlock *BB) const {
12847  // This is pretty easy.  We're taking the value that we received from
12848  // our load from the relocation, sticking it in either RDI (x86-64)
12849  // or EAX and doing an indirect call.  The return value will then
12850  // be in the normal return register.
12851  const X86InstrInfo *TII
12852    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12853  DebugLoc DL = MI->getDebugLoc();
12854  MachineFunction *F = BB->getParent();
12855
12856  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12857  assert(MI->getOperand(3).isGlobal() && "This should be a global");
12858
12859  // Get a register mask for the lowered call.
12860  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12861  // proper register mask.
12862  const uint32_t *RegMask =
12863    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12864  if (Subtarget->is64Bit()) {
12865    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12866                                      TII->get(X86::MOV64rm), X86::RDI)
12867    .addReg(X86::RIP)
12868    .addImm(0).addReg(0)
12869    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12870                      MI->getOperand(3).getTargetFlags())
12871    .addReg(0);
12872    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12873    addDirectMem(MIB, X86::RDI);
12874    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12875  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12876    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12877                                      TII->get(X86::MOV32rm), X86::EAX)
12878    .addReg(0)
12879    .addImm(0).addReg(0)
12880    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12881                      MI->getOperand(3).getTargetFlags())
12882    .addReg(0);
12883    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12884    addDirectMem(MIB, X86::EAX);
12885    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12886  } else {
12887    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12888                                      TII->get(X86::MOV32rm), X86::EAX)
12889    .addReg(TII->getGlobalBaseReg(F))
12890    .addImm(0).addReg(0)
12891    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12892                      MI->getOperand(3).getTargetFlags())
12893    .addReg(0);
12894    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12895    addDirectMem(MIB, X86::EAX);
12896    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12897  }
12898
12899  MI->eraseFromParent(); // The pseudo instruction is gone now.
12900  return BB;
12901}
12902
12903MachineBasicBlock *
12904X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12905                                               MachineBasicBlock *BB) const {
12906  switch (MI->getOpcode()) {
12907  default: llvm_unreachable("Unexpected instr type to insert");
12908  case X86::TAILJMPd64:
12909  case X86::TAILJMPr64:
12910  case X86::TAILJMPm64:
12911    llvm_unreachable("TAILJMP64 would not be touched here.");
12912  case X86::TCRETURNdi64:
12913  case X86::TCRETURNri64:
12914  case X86::TCRETURNmi64:
12915    return BB;
12916  case X86::WIN_ALLOCA:
12917    return EmitLoweredWinAlloca(MI, BB);
12918  case X86::SEG_ALLOCA_32:
12919    return EmitLoweredSegAlloca(MI, BB, false);
12920  case X86::SEG_ALLOCA_64:
12921    return EmitLoweredSegAlloca(MI, BB, true);
12922  case X86::TLSCall_32:
12923  case X86::TLSCall_64:
12924    return EmitLoweredTLSCall(MI, BB);
12925  case X86::CMOV_GR8:
12926  case X86::CMOV_FR32:
12927  case X86::CMOV_FR64:
12928  case X86::CMOV_V4F32:
12929  case X86::CMOV_V2F64:
12930  case X86::CMOV_V2I64:
12931  case X86::CMOV_V8F32:
12932  case X86::CMOV_V4F64:
12933  case X86::CMOV_V4I64:
12934  case X86::CMOV_GR16:
12935  case X86::CMOV_GR32:
12936  case X86::CMOV_RFP32:
12937  case X86::CMOV_RFP64:
12938  case X86::CMOV_RFP80:
12939    return EmitLoweredSelect(MI, BB);
12940
12941  case X86::FP32_TO_INT16_IN_MEM:
12942  case X86::FP32_TO_INT32_IN_MEM:
12943  case X86::FP32_TO_INT64_IN_MEM:
12944  case X86::FP64_TO_INT16_IN_MEM:
12945  case X86::FP64_TO_INT32_IN_MEM:
12946  case X86::FP64_TO_INT64_IN_MEM:
12947  case X86::FP80_TO_INT16_IN_MEM:
12948  case X86::FP80_TO_INT32_IN_MEM:
12949  case X86::FP80_TO_INT64_IN_MEM: {
12950    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12951    DebugLoc DL = MI->getDebugLoc();
12952
12953    // Change the floating point control register to use "round towards zero"
12954    // mode when truncating to an integer value.
12955    MachineFunction *F = BB->getParent();
12956    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12957    addFrameReference(BuildMI(*BB, MI, DL,
12958                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
12959
12960    // Load the old value of the high byte of the control word...
12961    unsigned OldCW =
12962      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12963    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12964                      CWFrameIdx);
12965
12966    // Set the high part to be round to zero...
12967    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12968      .addImm(0xC7F);
12969
12970    // Reload the modified control word now...
12971    addFrameReference(BuildMI(*BB, MI, DL,
12972                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12973
12974    // Restore the memory image of control word to original value
12975    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12976      .addReg(OldCW);
12977
12978    // Get the X86 opcode to use.
12979    unsigned Opc;
12980    switch (MI->getOpcode()) {
12981    default: llvm_unreachable("illegal opcode!");
12982    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12983    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12984    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12985    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12986    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12987    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12988    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12989    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12990    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12991    }
12992
12993    X86AddressMode AM;
12994    MachineOperand &Op = MI->getOperand(0);
12995    if (Op.isReg()) {
12996      AM.BaseType = X86AddressMode::RegBase;
12997      AM.Base.Reg = Op.getReg();
12998    } else {
12999      AM.BaseType = X86AddressMode::FrameIndexBase;
13000      AM.Base.FrameIndex = Op.getIndex();
13001    }
13002    Op = MI->getOperand(1);
13003    if (Op.isImm())
13004      AM.Scale = Op.getImm();
13005    Op = MI->getOperand(2);
13006    if (Op.isImm())
13007      AM.IndexReg = Op.getImm();
13008    Op = MI->getOperand(3);
13009    if (Op.isGlobal()) {
13010      AM.GV = Op.getGlobal();
13011    } else {
13012      AM.Disp = Op.getImm();
13013    }
13014    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13015                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13016
13017    // Reload the original control word now.
13018    addFrameReference(BuildMI(*BB, MI, DL,
13019                              TII->get(X86::FLDCW16m)), CWFrameIdx);
13020
13021    MI->eraseFromParent();   // The pseudo instruction is gone now.
13022    return BB;
13023  }
13024    // String/text processing lowering.
13025  case X86::PCMPISTRM128REG:
13026  case X86::VPCMPISTRM128REG:
13027  case X86::PCMPISTRM128MEM:
13028  case X86::VPCMPISTRM128MEM:
13029  case X86::PCMPESTRM128REG:
13030  case X86::VPCMPESTRM128REG:
13031  case X86::PCMPESTRM128MEM:
13032  case X86::VPCMPESTRM128MEM: {
13033    unsigned NumArgs;
13034    bool MemArg;
13035    switch (MI->getOpcode()) {
13036    default: llvm_unreachable("illegal opcode!");
13037    case X86::PCMPISTRM128REG:
13038    case X86::VPCMPISTRM128REG:
13039      NumArgs = 3; MemArg = false; break;
13040    case X86::PCMPISTRM128MEM:
13041    case X86::VPCMPISTRM128MEM:
13042      NumArgs = 3; MemArg = true; break;
13043    case X86::PCMPESTRM128REG:
13044    case X86::VPCMPESTRM128REG:
13045      NumArgs = 5; MemArg = false; break;
13046    case X86::PCMPESTRM128MEM:
13047    case X86::VPCMPESTRM128MEM:
13048      NumArgs = 5; MemArg = true; break;
13049    }
13050    return EmitPCMP(MI, BB, NumArgs, MemArg);
13051  }
13052
13053    // Thread synchronization.
13054  case X86::MONITOR:
13055    return EmitMonitor(MI, BB);
13056
13057    // Atomic Lowering.
13058  case X86::ATOMMIN32:
13059  case X86::ATOMMAX32:
13060  case X86::ATOMUMIN32:
13061  case X86::ATOMUMAX32:
13062  case X86::ATOMMIN16:
13063  case X86::ATOMMAX16:
13064  case X86::ATOMUMIN16:
13065  case X86::ATOMUMAX16:
13066  case X86::ATOMMIN64:
13067  case X86::ATOMMAX64:
13068  case X86::ATOMUMIN64:
13069  case X86::ATOMUMAX64: {
13070    unsigned Opc;
13071    switch (MI->getOpcode()) {
13072    default: llvm_unreachable("illegal opcode!");
13073    case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13074    case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13075    case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13076    case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13077    case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13078    case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13079    case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13080    case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13081    case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13082    case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13083    case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13084    case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13085    // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13086    }
13087    return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13088  }
13089
13090  case X86::ATOMAND32:
13091  case X86::ATOMOR32:
13092  case X86::ATOMXOR32:
13093  case X86::ATOMNAND32: {
13094    bool Invert = false;
13095    unsigned RegOpc, ImmOpc;
13096    switch (MI->getOpcode()) {
13097    default: llvm_unreachable("illegal opcode!");
13098    case X86::ATOMAND32:
13099      RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13100    case X86::ATOMOR32:
13101      RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13102    case X86::ATOMXOR32:
13103      RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13104    case X86::ATOMNAND32:
13105      RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13106    }
13107    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13108                                               X86::MOV32rm, X86::LCMPXCHG32,
13109                                               X86::NOT32r, X86::EAX,
13110                                               &X86::GR32RegClass, Invert);
13111  }
13112
13113  case X86::ATOMAND16:
13114  case X86::ATOMOR16:
13115  case X86::ATOMXOR16:
13116  case X86::ATOMNAND16: {
13117    bool Invert = false;
13118    unsigned RegOpc, ImmOpc;
13119    switch (MI->getOpcode()) {
13120    default: llvm_unreachable("illegal opcode!");
13121    case X86::ATOMAND16:
13122      RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13123    case X86::ATOMOR16:
13124      RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13125    case X86::ATOMXOR16:
13126      RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13127    case X86::ATOMNAND16:
13128      RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13129    }
13130    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13131                                               X86::MOV16rm, X86::LCMPXCHG16,
13132                                               X86::NOT16r, X86::AX,
13133                                               &X86::GR16RegClass, Invert);
13134  }
13135
13136  case X86::ATOMAND8:
13137  case X86::ATOMOR8:
13138  case X86::ATOMXOR8:
13139  case X86::ATOMNAND8: {
13140    bool Invert = false;
13141    unsigned RegOpc, ImmOpc;
13142    switch (MI->getOpcode()) {
13143    default: llvm_unreachable("illegal opcode!");
13144    case X86::ATOMAND8:
13145      RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13146    case X86::ATOMOR8:
13147      RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13148    case X86::ATOMXOR8:
13149      RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13150    case X86::ATOMNAND8:
13151      RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13152    }
13153    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13154                                               X86::MOV8rm, X86::LCMPXCHG8,
13155                                               X86::NOT8r, X86::AL,
13156                                               &X86::GR8RegClass, Invert);
13157  }
13158
13159  // This group is for 64-bit host.
13160  case X86::ATOMAND64:
13161  case X86::ATOMOR64:
13162  case X86::ATOMXOR64:
13163  case X86::ATOMNAND64: {
13164    bool Invert = false;
13165    unsigned RegOpc, ImmOpc;
13166    switch (MI->getOpcode()) {
13167    default: llvm_unreachable("illegal opcode!");
13168    case X86::ATOMAND64:
13169      RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13170    case X86::ATOMOR64:
13171      RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13172    case X86::ATOMXOR64:
13173      RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13174    case X86::ATOMNAND64:
13175      RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13176    }
13177    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13178                                               X86::MOV64rm, X86::LCMPXCHG64,
13179                                               X86::NOT64r, X86::RAX,
13180                                               &X86::GR64RegClass, Invert);
13181  }
13182
13183  // This group does 64-bit operations on a 32-bit host.
13184  case X86::ATOMAND6432:
13185  case X86::ATOMOR6432:
13186  case X86::ATOMXOR6432:
13187  case X86::ATOMNAND6432:
13188  case X86::ATOMADD6432:
13189  case X86::ATOMSUB6432:
13190  case X86::ATOMSWAP6432: {
13191    bool Invert = false;
13192    unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13193    switch (MI->getOpcode()) {
13194    default: llvm_unreachable("illegal opcode!");
13195    case X86::ATOMAND6432:
13196      RegOpcL = RegOpcH = X86::AND32rr;
13197      ImmOpcL = ImmOpcH = X86::AND32ri;
13198      break;
13199    case X86::ATOMOR6432:
13200      RegOpcL = RegOpcH = X86::OR32rr;
13201      ImmOpcL = ImmOpcH = X86::OR32ri;
13202      break;
13203    case X86::ATOMXOR6432:
13204      RegOpcL = RegOpcH = X86::XOR32rr;
13205      ImmOpcL = ImmOpcH = X86::XOR32ri;
13206      break;
13207    case X86::ATOMNAND6432:
13208      RegOpcL = RegOpcH = X86::AND32rr;
13209      ImmOpcL = ImmOpcH = X86::AND32ri;
13210      Invert = true;
13211      break;
13212    case X86::ATOMADD6432:
13213      RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13214      ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13215      break;
13216    case X86::ATOMSUB6432:
13217      RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13218      ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13219      break;
13220    case X86::ATOMSWAP6432:
13221      RegOpcL = RegOpcH = X86::MOV32rr;
13222      ImmOpcL = ImmOpcH = X86::MOV32ri;
13223      break;
13224    }
13225    return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13226                                               ImmOpcL, ImmOpcH, Invert);
13227  }
13228
13229  case X86::VASTART_SAVE_XMM_REGS:
13230    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13231
13232  case X86::VAARG_64:
13233    return EmitVAARG64WithCustomInserter(MI, BB);
13234  }
13235}
13236
13237//===----------------------------------------------------------------------===//
13238//                           X86 Optimization Hooks
13239//===----------------------------------------------------------------------===//
13240
13241void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13242                                                       APInt &KnownZero,
13243                                                       APInt &KnownOne,
13244                                                       const SelectionDAG &DAG,
13245                                                       unsigned Depth) const {
13246  unsigned BitWidth = KnownZero.getBitWidth();
13247  unsigned Opc = Op.getOpcode();
13248  assert((Opc >= ISD::BUILTIN_OP_END ||
13249          Opc == ISD::INTRINSIC_WO_CHAIN ||
13250          Opc == ISD::INTRINSIC_W_CHAIN ||
13251          Opc == ISD::INTRINSIC_VOID) &&
13252         "Should use MaskedValueIsZero if you don't know whether Op"
13253         " is a target node!");
13254
13255  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13256  switch (Opc) {
13257  default: break;
13258  case X86ISD::ADD:
13259  case X86ISD::SUB:
13260  case X86ISD::ADC:
13261  case X86ISD::SBB:
13262  case X86ISD::SMUL:
13263  case X86ISD::UMUL:
13264  case X86ISD::INC:
13265  case X86ISD::DEC:
13266  case X86ISD::OR:
13267  case X86ISD::XOR:
13268  case X86ISD::AND:
13269    // These nodes' second result is a boolean.
13270    if (Op.getResNo() == 0)
13271      break;
13272    // Fallthrough
13273  case X86ISD::SETCC:
13274    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13275    break;
13276  case ISD::INTRINSIC_WO_CHAIN: {
13277    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13278    unsigned NumLoBits = 0;
13279    switch (IntId) {
13280    default: break;
13281    case Intrinsic::x86_sse_movmsk_ps:
13282    case Intrinsic::x86_avx_movmsk_ps_256:
13283    case Intrinsic::x86_sse2_movmsk_pd:
13284    case Intrinsic::x86_avx_movmsk_pd_256:
13285    case Intrinsic::x86_mmx_pmovmskb:
13286    case Intrinsic::x86_sse2_pmovmskb_128:
13287    case Intrinsic::x86_avx2_pmovmskb: {
13288      // High bits of movmskp{s|d}, pmovmskb are known zero.
13289      switch (IntId) {
13290        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13291        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13292        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13293        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13294        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13295        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13296        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13297        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13298      }
13299      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13300      break;
13301    }
13302    }
13303    break;
13304  }
13305  }
13306}
13307
13308unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13309                                                         unsigned Depth) const {
13310  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13311  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13312    return Op.getValueType().getScalarType().getSizeInBits();
13313
13314  // Fallback case.
13315  return 1;
13316}
13317
13318/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13319/// node is a GlobalAddress + offset.
13320bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13321                                       const GlobalValue* &GA,
13322                                       int64_t &Offset) const {
13323  if (N->getOpcode() == X86ISD::Wrapper) {
13324    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13325      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13326      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13327      return true;
13328    }
13329  }
13330  return TargetLowering::isGAPlusOffset(N, GA, Offset);
13331}
13332
13333/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13334/// same as extracting the high 128-bit part of 256-bit vector and then
13335/// inserting the result into the low part of a new 256-bit vector
13336static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13337  EVT VT = SVOp->getValueType(0);
13338  unsigned NumElems = VT.getVectorNumElements();
13339
13340  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13341  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13342    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13343        SVOp->getMaskElt(j) >= 0)
13344      return false;
13345
13346  return true;
13347}
13348
13349/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13350/// same as extracting the low 128-bit part of 256-bit vector and then
13351/// inserting the result into the high part of a new 256-bit vector
13352static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13353  EVT VT = SVOp->getValueType(0);
13354  unsigned NumElems = VT.getVectorNumElements();
13355
13356  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13357  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13358    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13359        SVOp->getMaskElt(j) >= 0)
13360      return false;
13361
13362  return true;
13363}
13364
13365/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13366static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13367                                        TargetLowering::DAGCombinerInfo &DCI,
13368                                        const X86Subtarget* Subtarget) {
13369  DebugLoc dl = N->getDebugLoc();
13370  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13371  SDValue V1 = SVOp->getOperand(0);
13372  SDValue V2 = SVOp->getOperand(1);
13373  EVT VT = SVOp->getValueType(0);
13374  unsigned NumElems = VT.getVectorNumElements();
13375
13376  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13377      V2.getOpcode() == ISD::CONCAT_VECTORS) {
13378    //
13379    //                   0,0,0,...
13380    //                      |
13381    //    V      UNDEF    BUILD_VECTOR    UNDEF
13382    //     \      /           \           /
13383    //  CONCAT_VECTOR         CONCAT_VECTOR
13384    //         \                  /
13385    //          \                /
13386    //          RESULT: V + zero extended
13387    //
13388    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13389        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13390        V1.getOperand(1).getOpcode() != ISD::UNDEF)
13391      return SDValue();
13392
13393    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13394      return SDValue();
13395
13396    // To match the shuffle mask, the first half of the mask should
13397    // be exactly the first vector, and all the rest a splat with the
13398    // first element of the second one.
13399    for (unsigned i = 0; i != NumElems/2; ++i)
13400      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13401          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13402        return SDValue();
13403
13404    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13405    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13406      if (Ld->hasNUsesOfValue(1, 0)) {
13407        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13408        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13409        SDValue ResNode =
13410          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13411                                  Ld->getMemoryVT(),
13412                                  Ld->getPointerInfo(),
13413                                  Ld->getAlignment(),
13414                                  false/*isVolatile*/, true/*ReadMem*/,
13415                                  false/*WriteMem*/);
13416        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13417      }
13418    }
13419
13420    // Emit a zeroed vector and insert the desired subvector on its
13421    // first half.
13422    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13423    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13424    return DCI.CombineTo(N, InsV);
13425  }
13426
13427  //===--------------------------------------------------------------------===//
13428  // Combine some shuffles into subvector extracts and inserts:
13429  //
13430
13431  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13432  if (isShuffleHigh128VectorInsertLow(SVOp)) {
13433    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13434    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13435    return DCI.CombineTo(N, InsV);
13436  }
13437
13438  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13439  if (isShuffleLow128VectorInsertHigh(SVOp)) {
13440    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13441    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13442    return DCI.CombineTo(N, InsV);
13443  }
13444
13445  return SDValue();
13446}
13447
13448/// PerformShuffleCombine - Performs several different shuffle combines.
13449static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13450                                     TargetLowering::DAGCombinerInfo &DCI,
13451                                     const X86Subtarget *Subtarget) {
13452  DebugLoc dl = N->getDebugLoc();
13453  EVT VT = N->getValueType(0);
13454
13455  // Don't create instructions with illegal types after legalize types has run.
13456  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13457  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13458    return SDValue();
13459
13460  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13461  if (Subtarget->hasAVX() && VT.is256BitVector() &&
13462      N->getOpcode() == ISD::VECTOR_SHUFFLE)
13463    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13464
13465  // Only handle 128 wide vector from here on.
13466  if (!VT.is128BitVector())
13467    return SDValue();
13468
13469  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13470  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13471  // consecutive, non-overlapping, and in the right order.
13472  SmallVector<SDValue, 16> Elts;
13473  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13474    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13475
13476  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13477}
13478
13479
13480/// DCI, PerformTruncateCombine - Converts truncate operation to
13481/// a sequence of vector shuffle operations.
13482/// It is possible when we truncate 256-bit vector to 128-bit vector
13483
13484SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13485                                                  DAGCombinerInfo &DCI) const {
13486  if (!DCI.isBeforeLegalizeOps())
13487    return SDValue();
13488
13489  if (!Subtarget->hasAVX())
13490    return SDValue();
13491
13492  EVT VT = N->getValueType(0);
13493  SDValue Op = N->getOperand(0);
13494  EVT OpVT = Op.getValueType();
13495  DebugLoc dl = N->getDebugLoc();
13496
13497  if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13498
13499    if (Subtarget->hasAVX2()) {
13500      // AVX2: v4i64 -> v4i32
13501
13502      // VPERMD
13503      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13504
13505      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13506      Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13507                                ShufMask);
13508
13509      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13510                         DAG.getIntPtrConstant(0));
13511    }
13512
13513    // AVX: v4i64 -> v4i32
13514    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13515                               DAG.getIntPtrConstant(0));
13516
13517    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13518                               DAG.getIntPtrConstant(2));
13519
13520    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13521    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13522
13523    // PSHUFD
13524    static const int ShufMask1[] = {0, 2, 0, 0};
13525
13526    SDValue Undef = DAG.getUNDEF(VT);
13527    OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13528    OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13529
13530    // MOVLHPS
13531    static const int ShufMask2[] = {0, 1, 4, 5};
13532
13533    return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13534  }
13535
13536  if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13537
13538    if (Subtarget->hasAVX2()) {
13539      // AVX2: v8i32 -> v8i16
13540
13541      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13542
13543      // PSHUFB
13544      SmallVector<SDValue,32> pshufbMask;
13545      for (unsigned i = 0; i < 2; ++i) {
13546        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13547        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13548        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13549        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13550        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13551        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13552        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13553        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13554        for (unsigned j = 0; j < 8; ++j)
13555          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13556      }
13557      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13558                               &pshufbMask[0], 32);
13559      Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13560
13561      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13562
13563      static const int ShufMask[] = {0,  2,  -1,  -1};
13564      Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13565                                &ShufMask[0]);
13566
13567      Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13568                       DAG.getIntPtrConstant(0));
13569
13570      return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13571    }
13572
13573    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13574                               DAG.getIntPtrConstant(0));
13575
13576    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13577                               DAG.getIntPtrConstant(4));
13578
13579    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13580    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13581
13582    // PSHUFB
13583    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13584                                   -1, -1, -1, -1, -1, -1, -1, -1};
13585
13586    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13587    OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13588    OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13589
13590    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13591    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13592
13593    // MOVLHPS
13594    static const int ShufMask2[] = {0, 1, 4, 5};
13595
13596    SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13597    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13598  }
13599
13600  return SDValue();
13601}
13602
13603/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13604/// specific shuffle of a load can be folded into a single element load.
13605/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13606/// shuffles have been customed lowered so we need to handle those here.
13607static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13608                                         TargetLowering::DAGCombinerInfo &DCI) {
13609  if (DCI.isBeforeLegalizeOps())
13610    return SDValue();
13611
13612  SDValue InVec = N->getOperand(0);
13613  SDValue EltNo = N->getOperand(1);
13614
13615  if (!isa<ConstantSDNode>(EltNo))
13616    return SDValue();
13617
13618  EVT VT = InVec.getValueType();
13619
13620  bool HasShuffleIntoBitcast = false;
13621  if (InVec.getOpcode() == ISD::BITCAST) {
13622    // Don't duplicate a load with other uses.
13623    if (!InVec.hasOneUse())
13624      return SDValue();
13625    EVT BCVT = InVec.getOperand(0).getValueType();
13626    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13627      return SDValue();
13628    InVec = InVec.getOperand(0);
13629    HasShuffleIntoBitcast = true;
13630  }
13631
13632  if (!isTargetShuffle(InVec.getOpcode()))
13633    return SDValue();
13634
13635  // Don't duplicate a load with other uses.
13636  if (!InVec.hasOneUse())
13637    return SDValue();
13638
13639  SmallVector<int, 16> ShuffleMask;
13640  bool UnaryShuffle;
13641  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13642                            UnaryShuffle))
13643    return SDValue();
13644
13645  // Select the input vector, guarding against out of range extract vector.
13646  unsigned NumElems = VT.getVectorNumElements();
13647  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13648  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13649  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13650                                         : InVec.getOperand(1);
13651
13652  // If inputs to shuffle are the same for both ops, then allow 2 uses
13653  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13654
13655  if (LdNode.getOpcode() == ISD::BITCAST) {
13656    // Don't duplicate a load with other uses.
13657    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13658      return SDValue();
13659
13660    AllowedUses = 1; // only allow 1 load use if we have a bitcast
13661    LdNode = LdNode.getOperand(0);
13662  }
13663
13664  if (!ISD::isNormalLoad(LdNode.getNode()))
13665    return SDValue();
13666
13667  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13668
13669  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13670    return SDValue();
13671
13672  if (HasShuffleIntoBitcast) {
13673    // If there's a bitcast before the shuffle, check if the load type and
13674    // alignment is valid.
13675    unsigned Align = LN0->getAlignment();
13676    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13677    unsigned NewAlign = TLI.getTargetData()->
13678      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13679
13680    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13681      return SDValue();
13682  }
13683
13684  // All checks match so transform back to vector_shuffle so that DAG combiner
13685  // can finish the job
13686  DebugLoc dl = N->getDebugLoc();
13687
13688  // Create shuffle node taking into account the case that its a unary shuffle
13689  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13690  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13691                                 InVec.getOperand(0), Shuffle,
13692                                 &ShuffleMask[0]);
13693  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13694  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13695                     EltNo);
13696}
13697
13698/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13699/// generation and convert it from being a bunch of shuffles and extracts
13700/// to a simple store and scalar loads to extract the elements.
13701static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13702                                         TargetLowering::DAGCombinerInfo &DCI) {
13703  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13704  if (NewOp.getNode())
13705    return NewOp;
13706
13707  SDValue InputVector = N->getOperand(0);
13708
13709  // Only operate on vectors of 4 elements, where the alternative shuffling
13710  // gets to be more expensive.
13711  if (InputVector.getValueType() != MVT::v4i32)
13712    return SDValue();
13713
13714  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13715  // single use which is a sign-extend or zero-extend, and all elements are
13716  // used.
13717  SmallVector<SDNode *, 4> Uses;
13718  unsigned ExtractedElements = 0;
13719  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13720       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13721    if (UI.getUse().getResNo() != InputVector.getResNo())
13722      return SDValue();
13723
13724    SDNode *Extract = *UI;
13725    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13726      return SDValue();
13727
13728    if (Extract->getValueType(0) != MVT::i32)
13729      return SDValue();
13730    if (!Extract->hasOneUse())
13731      return SDValue();
13732    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13733        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13734      return SDValue();
13735    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13736      return SDValue();
13737
13738    // Record which element was extracted.
13739    ExtractedElements |=
13740      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13741
13742    Uses.push_back(Extract);
13743  }
13744
13745  // If not all the elements were used, this may not be worthwhile.
13746  if (ExtractedElements != 15)
13747    return SDValue();
13748
13749  // Ok, we've now decided to do the transformation.
13750  DebugLoc dl = InputVector.getDebugLoc();
13751
13752  // Store the value to a temporary stack slot.
13753  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13754  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13755                            MachinePointerInfo(), false, false, 0);
13756
13757  // Replace each use (extract) with a load of the appropriate element.
13758  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13759       UE = Uses.end(); UI != UE; ++UI) {
13760    SDNode *Extract = *UI;
13761
13762    // cOMpute the element's address.
13763    SDValue Idx = Extract->getOperand(1);
13764    unsigned EltSize =
13765        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13766    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13767    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13768    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13769
13770    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13771                                     StackPtr, OffsetVal);
13772
13773    // Load the scalar.
13774    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13775                                     ScalarAddr, MachinePointerInfo(),
13776                                     false, false, false, 0);
13777
13778    // Replace the exact with the load.
13779    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13780  }
13781
13782  // The replacement was made in place; don't return anything.
13783  return SDValue();
13784}
13785
13786/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13787/// nodes.
13788static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13789                                    TargetLowering::DAGCombinerInfo &DCI,
13790                                    const X86Subtarget *Subtarget) {
13791  DebugLoc DL = N->getDebugLoc();
13792  SDValue Cond = N->getOperand(0);
13793  // Get the LHS/RHS of the select.
13794  SDValue LHS = N->getOperand(1);
13795  SDValue RHS = N->getOperand(2);
13796  EVT VT = LHS.getValueType();
13797
13798  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13799  // instructions match the semantics of the common C idiom x<y?x:y but not
13800  // x<=y?x:y, because of how they handle negative zero (which can be
13801  // ignored in unsafe-math mode).
13802  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13803      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13804      (Subtarget->hasSSE2() ||
13805       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13806    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13807
13808    unsigned Opcode = 0;
13809    // Check for x CC y ? x : y.
13810    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13811        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13812      switch (CC) {
13813      default: break;
13814      case ISD::SETULT:
13815        // Converting this to a min would handle NaNs incorrectly, and swapping
13816        // the operands would cause it to handle comparisons between positive
13817        // and negative zero incorrectly.
13818        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13819          if (!DAG.getTarget().Options.UnsafeFPMath &&
13820              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13821            break;
13822          std::swap(LHS, RHS);
13823        }
13824        Opcode = X86ISD::FMIN;
13825        break;
13826      case ISD::SETOLE:
13827        // Converting this to a min would handle comparisons between positive
13828        // and negative zero incorrectly.
13829        if (!DAG.getTarget().Options.UnsafeFPMath &&
13830            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13831          break;
13832        Opcode = X86ISD::FMIN;
13833        break;
13834      case ISD::SETULE:
13835        // Converting this to a min would handle both negative zeros and NaNs
13836        // incorrectly, but we can swap the operands to fix both.
13837        std::swap(LHS, RHS);
13838      case ISD::SETOLT:
13839      case ISD::SETLT:
13840      case ISD::SETLE:
13841        Opcode = X86ISD::FMIN;
13842        break;
13843
13844      case ISD::SETOGE:
13845        // Converting this to a max would handle comparisons between positive
13846        // and negative zero incorrectly.
13847        if (!DAG.getTarget().Options.UnsafeFPMath &&
13848            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13849          break;
13850        Opcode = X86ISD::FMAX;
13851        break;
13852      case ISD::SETUGT:
13853        // Converting this to a max would handle NaNs incorrectly, and swapping
13854        // the operands would cause it to handle comparisons between positive
13855        // and negative zero incorrectly.
13856        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13857          if (!DAG.getTarget().Options.UnsafeFPMath &&
13858              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13859            break;
13860          std::swap(LHS, RHS);
13861        }
13862        Opcode = X86ISD::FMAX;
13863        break;
13864      case ISD::SETUGE:
13865        // Converting this to a max would handle both negative zeros and NaNs
13866        // incorrectly, but we can swap the operands to fix both.
13867        std::swap(LHS, RHS);
13868      case ISD::SETOGT:
13869      case ISD::SETGT:
13870      case ISD::SETGE:
13871        Opcode = X86ISD::FMAX;
13872        break;
13873      }
13874    // Check for x CC y ? y : x -- a min/max with reversed arms.
13875    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13876               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13877      switch (CC) {
13878      default: break;
13879      case ISD::SETOGE:
13880        // Converting this to a min would handle comparisons between positive
13881        // and negative zero incorrectly, and swapping the operands would
13882        // cause it to handle NaNs incorrectly.
13883        if (!DAG.getTarget().Options.UnsafeFPMath &&
13884            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13885          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13886            break;
13887          std::swap(LHS, RHS);
13888        }
13889        Opcode = X86ISD::FMIN;
13890        break;
13891      case ISD::SETUGT:
13892        // Converting this to a min would handle NaNs incorrectly.
13893        if (!DAG.getTarget().Options.UnsafeFPMath &&
13894            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13895          break;
13896        Opcode = X86ISD::FMIN;
13897        break;
13898      case ISD::SETUGE:
13899        // Converting this to a min would handle both negative zeros and NaNs
13900        // incorrectly, but we can swap the operands to fix both.
13901        std::swap(LHS, RHS);
13902      case ISD::SETOGT:
13903      case ISD::SETGT:
13904      case ISD::SETGE:
13905        Opcode = X86ISD::FMIN;
13906        break;
13907
13908      case ISD::SETULT:
13909        // Converting this to a max would handle NaNs incorrectly.
13910        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13911          break;
13912        Opcode = X86ISD::FMAX;
13913        break;
13914      case ISD::SETOLE:
13915        // Converting this to a max would handle comparisons between positive
13916        // and negative zero incorrectly, and swapping the operands would
13917        // cause it to handle NaNs incorrectly.
13918        if (!DAG.getTarget().Options.UnsafeFPMath &&
13919            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13920          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13921            break;
13922          std::swap(LHS, RHS);
13923        }
13924        Opcode = X86ISD::FMAX;
13925        break;
13926      case ISD::SETULE:
13927        // Converting this to a max would handle both negative zeros and NaNs
13928        // incorrectly, but we can swap the operands to fix both.
13929        std::swap(LHS, RHS);
13930      case ISD::SETOLT:
13931      case ISD::SETLT:
13932      case ISD::SETLE:
13933        Opcode = X86ISD::FMAX;
13934        break;
13935      }
13936    }
13937
13938    if (Opcode)
13939      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13940  }
13941
13942  // If this is a select between two integer constants, try to do some
13943  // optimizations.
13944  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13945    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13946      // Don't do this for crazy integer types.
13947      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13948        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13949        // so that TrueC (the true value) is larger than FalseC.
13950        bool NeedsCondInvert = false;
13951
13952        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13953            // Efficiently invertible.
13954            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13955             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13956              isa<ConstantSDNode>(Cond.getOperand(1))))) {
13957          NeedsCondInvert = true;
13958          std::swap(TrueC, FalseC);
13959        }
13960
13961        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13962        if (FalseC->getAPIntValue() == 0 &&
13963            TrueC->getAPIntValue().isPowerOf2()) {
13964          if (NeedsCondInvert) // Invert the condition if needed.
13965            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13966                               DAG.getConstant(1, Cond.getValueType()));
13967
13968          // Zero extend the condition if needed.
13969          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13970
13971          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13972          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13973                             DAG.getConstant(ShAmt, MVT::i8));
13974        }
13975
13976        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13977        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13978          if (NeedsCondInvert) // Invert the condition if needed.
13979            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13980                               DAG.getConstant(1, Cond.getValueType()));
13981
13982          // Zero extend the condition if needed.
13983          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13984                             FalseC->getValueType(0), Cond);
13985          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13986                             SDValue(FalseC, 0));
13987        }
13988
13989        // Optimize cases that will turn into an LEA instruction.  This requires
13990        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13991        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13992          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13993          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13994
13995          bool isFastMultiplier = false;
13996          if (Diff < 10) {
13997            switch ((unsigned char)Diff) {
13998              default: break;
13999              case 1:  // result = add base, cond
14000              case 2:  // result = lea base(    , cond*2)
14001              case 3:  // result = lea base(cond, cond*2)
14002              case 4:  // result = lea base(    , cond*4)
14003              case 5:  // result = lea base(cond, cond*4)
14004              case 8:  // result = lea base(    , cond*8)
14005              case 9:  // result = lea base(cond, cond*8)
14006                isFastMultiplier = true;
14007                break;
14008            }
14009          }
14010
14011          if (isFastMultiplier) {
14012            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14013            if (NeedsCondInvert) // Invert the condition if needed.
14014              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14015                                 DAG.getConstant(1, Cond.getValueType()));
14016
14017            // Zero extend the condition if needed.
14018            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14019                               Cond);
14020            // Scale the condition by the difference.
14021            if (Diff != 1)
14022              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14023                                 DAG.getConstant(Diff, Cond.getValueType()));
14024
14025            // Add the base if non-zero.
14026            if (FalseC->getAPIntValue() != 0)
14027              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14028                                 SDValue(FalseC, 0));
14029            return Cond;
14030          }
14031        }
14032      }
14033  }
14034
14035  // Canonicalize max and min:
14036  // (x > y) ? x : y -> (x >= y) ? x : y
14037  // (x < y) ? x : y -> (x <= y) ? x : y
14038  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14039  // the need for an extra compare
14040  // against zero. e.g.
14041  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14042  // subl   %esi, %edi
14043  // testl  %edi, %edi
14044  // movl   $0, %eax
14045  // cmovgl %edi, %eax
14046  // =>
14047  // xorl   %eax, %eax
14048  // subl   %esi, $edi
14049  // cmovsl %eax, %edi
14050  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14051      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14052      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14053    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14054    switch (CC) {
14055    default: break;
14056    case ISD::SETLT:
14057    case ISD::SETGT: {
14058      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14059      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14060                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
14061      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14062    }
14063    }
14064  }
14065
14066  // If we know that this node is legal then we know that it is going to be
14067  // matched by one of the SSE/AVX BLEND instructions. These instructions only
14068  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14069  // to simplify previous instructions.
14070  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14071  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14072      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14073    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14074
14075    // Don't optimize vector selects that map to mask-registers.
14076    if (BitWidth == 1)
14077      return SDValue();
14078
14079    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14080    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14081
14082    APInt KnownZero, KnownOne;
14083    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14084                                          DCI.isBeforeLegalizeOps());
14085    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14086        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14087      DCI.CommitTargetLoweringOpt(TLO);
14088  }
14089
14090  return SDValue();
14091}
14092
14093// Check whether a boolean test is testing a boolean value generated by
14094// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14095// code.
14096//
14097// Simplify the following patterns:
14098// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14099// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14100// to (Op EFLAGS Cond)
14101//
14102// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14103// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14104// to (Op EFLAGS !Cond)
14105//
14106// where Op could be BRCOND or CMOV.
14107//
14108static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14109  // Quit if not CMP and SUB with its value result used.
14110  if (Cmp.getOpcode() != X86ISD::CMP &&
14111      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14112      return SDValue();
14113
14114  // Quit if not used as a boolean value.
14115  if (CC != X86::COND_E && CC != X86::COND_NE)
14116    return SDValue();
14117
14118  // Check CMP operands. One of them should be 0 or 1 and the other should be
14119  // an SetCC or extended from it.
14120  SDValue Op1 = Cmp.getOperand(0);
14121  SDValue Op2 = Cmp.getOperand(1);
14122
14123  SDValue SetCC;
14124  const ConstantSDNode* C = 0;
14125  bool needOppositeCond = (CC == X86::COND_E);
14126
14127  if ((C = dyn_cast<ConstantSDNode>(Op1)))
14128    SetCC = Op2;
14129  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14130    SetCC = Op1;
14131  else // Quit if all operands are not constants.
14132    return SDValue();
14133
14134  if (C->getZExtValue() == 1)
14135    needOppositeCond = !needOppositeCond;
14136  else if (C->getZExtValue() != 0)
14137    // Quit if the constant is neither 0 or 1.
14138    return SDValue();
14139
14140  // Skip 'zext' node.
14141  if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14142    SetCC = SetCC.getOperand(0);
14143
14144  // Quit if not SETCC.
14145  // FIXME: So far we only handle the boolean value generated from SETCC. If
14146  // there is other ways to generate boolean values, we need handle them here
14147  // as well.
14148  if (SetCC.getOpcode() != X86ISD::SETCC)
14149    return SDValue();
14150
14151  // Set the condition code or opposite one if necessary.
14152  CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14153  if (needOppositeCond)
14154    CC = X86::GetOppositeBranchCondition(CC);
14155
14156  return SetCC.getOperand(1);
14157}
14158
14159/// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14160/// updated. If only flag result is used and the result is evaluated from a
14161/// series of element extraction, try to combine it into a PTEST.
14162static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14163                                     SelectionDAG &DAG,
14164                                     const X86Subtarget *Subtarget) {
14165  SDNode *N = Or.getNode();
14166  DebugLoc DL = N->getDebugLoc();
14167
14168  // Only SSE4.1 and beyond supports PTEST or like.
14169  if (!Subtarget->hasSSE41())
14170    return SDValue();
14171
14172  if (N->getOpcode() != X86ISD::OR)
14173    return SDValue();
14174
14175  // Quit if the value result of OR is used.
14176  if (N->hasAnyUseOfValue(0))
14177    return SDValue();
14178
14179  // Quit if not used as a boolean value.
14180  if (CC != X86::COND_E && CC != X86::COND_NE)
14181    return SDValue();
14182
14183  SmallVector<SDValue, 8> Opnds;
14184  SDValue VecIn;
14185  EVT VT = MVT::Other;
14186  unsigned Mask = 0;
14187
14188  // Recognize a special case where a vector is casted into wide integer to
14189  // test all 0s.
14190  Opnds.push_back(N->getOperand(0));
14191  Opnds.push_back(N->getOperand(1));
14192
14193  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14194    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14195    // BFS traverse all OR'd operands.
14196    if (I->getOpcode() == ISD::OR) {
14197      Opnds.push_back(I->getOperand(0));
14198      Opnds.push_back(I->getOperand(1));
14199      // Re-evaluate the number of nodes to be traversed.
14200      e += 2; // 2 more nodes (LHS and RHS) are pushed.
14201      continue;
14202    }
14203
14204    // Quit if a non-EXTRACT_VECTOR_ELT
14205    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14206      return SDValue();
14207
14208    // Quit if without a constant index.
14209    SDValue Idx = I->getOperand(1);
14210    if (!isa<ConstantSDNode>(Idx))
14211      return SDValue();
14212
14213    // Check if all elements are extracted from the same vector.
14214    SDValue ExtractedFromVec = I->getOperand(0);
14215    if (VecIn.getNode() == 0) {
14216      VT = ExtractedFromVec.getValueType();
14217      // FIXME: only 128-bit vector is supported so far.
14218      if (!VT.is128BitVector())
14219        return SDValue();
14220      VecIn = ExtractedFromVec;
14221    } else if (VecIn != ExtractedFromVec)
14222      return SDValue();
14223
14224    // Record the constant index.
14225    Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14226  }
14227
14228  assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14229
14230  // Quit if not all elements are used.
14231  if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14232    return SDValue();
14233
14234  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14235}
14236
14237/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14238static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14239                                  TargetLowering::DAGCombinerInfo &DCI,
14240                                  const X86Subtarget *Subtarget) {
14241  DebugLoc DL = N->getDebugLoc();
14242
14243  // If the flag operand isn't dead, don't touch this CMOV.
14244  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14245    return SDValue();
14246
14247  SDValue FalseOp = N->getOperand(0);
14248  SDValue TrueOp = N->getOperand(1);
14249  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14250  SDValue Cond = N->getOperand(3);
14251
14252  if (CC == X86::COND_E || CC == X86::COND_NE) {
14253    switch (Cond.getOpcode()) {
14254    default: break;
14255    case X86ISD::BSR:
14256    case X86ISD::BSF:
14257      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14258      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14259        return (CC == X86::COND_E) ? FalseOp : TrueOp;
14260    }
14261  }
14262
14263  SDValue Flags;
14264
14265  Flags = checkBoolTestSetCCCombine(Cond, CC);
14266  if (Flags.getNode() &&
14267      // Extra check as FCMOV only supports a subset of X86 cond.
14268      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14269    SDValue Ops[] = { FalseOp, TrueOp,
14270                      DAG.getConstant(CC, MVT::i8), Flags };
14271    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14272                       Ops, array_lengthof(Ops));
14273  }
14274
14275  Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14276  if (Flags.getNode()) {
14277    SDValue Ops[] = { FalseOp, TrueOp,
14278                      DAG.getConstant(CC, MVT::i8), Flags };
14279    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14280                       Ops, array_lengthof(Ops));
14281  }
14282
14283  // If this is a select between two integer constants, try to do some
14284  // optimizations.  Note that the operands are ordered the opposite of SELECT
14285  // operands.
14286  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14287    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14288      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14289      // larger than FalseC (the false value).
14290      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14291        CC = X86::GetOppositeBranchCondition(CC);
14292        std::swap(TrueC, FalseC);
14293      }
14294
14295      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14296      // This is efficient for any integer data type (including i8/i16) and
14297      // shift amount.
14298      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14299        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14300                           DAG.getConstant(CC, MVT::i8), Cond);
14301
14302        // Zero extend the condition if needed.
14303        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14304
14305        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14306        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14307                           DAG.getConstant(ShAmt, MVT::i8));
14308        if (N->getNumValues() == 2)  // Dead flag value?
14309          return DCI.CombineTo(N, Cond, SDValue());
14310        return Cond;
14311      }
14312
14313      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14314      // for any integer data type, including i8/i16.
14315      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14316        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14317                           DAG.getConstant(CC, MVT::i8), Cond);
14318
14319        // Zero extend the condition if needed.
14320        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14321                           FalseC->getValueType(0), Cond);
14322        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14323                           SDValue(FalseC, 0));
14324
14325        if (N->getNumValues() == 2)  // Dead flag value?
14326          return DCI.CombineTo(N, Cond, SDValue());
14327        return Cond;
14328      }
14329
14330      // Optimize cases that will turn into an LEA instruction.  This requires
14331      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14332      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14333        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14334        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14335
14336        bool isFastMultiplier = false;
14337        if (Diff < 10) {
14338          switch ((unsigned char)Diff) {
14339          default: break;
14340          case 1:  // result = add base, cond
14341          case 2:  // result = lea base(    , cond*2)
14342          case 3:  // result = lea base(cond, cond*2)
14343          case 4:  // result = lea base(    , cond*4)
14344          case 5:  // result = lea base(cond, cond*4)
14345          case 8:  // result = lea base(    , cond*8)
14346          case 9:  // result = lea base(cond, cond*8)
14347            isFastMultiplier = true;
14348            break;
14349          }
14350        }
14351
14352        if (isFastMultiplier) {
14353          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14354          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14355                             DAG.getConstant(CC, MVT::i8), Cond);
14356          // Zero extend the condition if needed.
14357          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14358                             Cond);
14359          // Scale the condition by the difference.
14360          if (Diff != 1)
14361            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14362                               DAG.getConstant(Diff, Cond.getValueType()));
14363
14364          // Add the base if non-zero.
14365          if (FalseC->getAPIntValue() != 0)
14366            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14367                               SDValue(FalseC, 0));
14368          if (N->getNumValues() == 2)  // Dead flag value?
14369            return DCI.CombineTo(N, Cond, SDValue());
14370          return Cond;
14371        }
14372      }
14373    }
14374  }
14375  return SDValue();
14376}
14377
14378
14379/// PerformMulCombine - Optimize a single multiply with constant into two
14380/// in order to implement it with two cheaper instructions, e.g.
14381/// LEA + SHL, LEA + LEA.
14382static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14383                                 TargetLowering::DAGCombinerInfo &DCI) {
14384  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14385    return SDValue();
14386
14387  EVT VT = N->getValueType(0);
14388  if (VT != MVT::i64)
14389    return SDValue();
14390
14391  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14392  if (!C)
14393    return SDValue();
14394  uint64_t MulAmt = C->getZExtValue();
14395  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14396    return SDValue();
14397
14398  uint64_t MulAmt1 = 0;
14399  uint64_t MulAmt2 = 0;
14400  if ((MulAmt % 9) == 0) {
14401    MulAmt1 = 9;
14402    MulAmt2 = MulAmt / 9;
14403  } else if ((MulAmt % 5) == 0) {
14404    MulAmt1 = 5;
14405    MulAmt2 = MulAmt / 5;
14406  } else if ((MulAmt % 3) == 0) {
14407    MulAmt1 = 3;
14408    MulAmt2 = MulAmt / 3;
14409  }
14410  if (MulAmt2 &&
14411      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14412    DebugLoc DL = N->getDebugLoc();
14413
14414    if (isPowerOf2_64(MulAmt2) &&
14415        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14416      // If second multiplifer is pow2, issue it first. We want the multiply by
14417      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14418      // is an add.
14419      std::swap(MulAmt1, MulAmt2);
14420
14421    SDValue NewMul;
14422    if (isPowerOf2_64(MulAmt1))
14423      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14424                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14425    else
14426      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14427                           DAG.getConstant(MulAmt1, VT));
14428
14429    if (isPowerOf2_64(MulAmt2))
14430      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14431                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14432    else
14433      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14434                           DAG.getConstant(MulAmt2, VT));
14435
14436    // Do not add new nodes to DAG combiner worklist.
14437    DCI.CombineTo(N, NewMul, false);
14438  }
14439  return SDValue();
14440}
14441
14442static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14443  SDValue N0 = N->getOperand(0);
14444  SDValue N1 = N->getOperand(1);
14445  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14446  EVT VT = N0.getValueType();
14447
14448  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14449  // since the result of setcc_c is all zero's or all ones.
14450  if (VT.isInteger() && !VT.isVector() &&
14451      N1C && N0.getOpcode() == ISD::AND &&
14452      N0.getOperand(1).getOpcode() == ISD::Constant) {
14453    SDValue N00 = N0.getOperand(0);
14454    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14455        ((N00.getOpcode() == ISD::ANY_EXTEND ||
14456          N00.getOpcode() == ISD::ZERO_EXTEND) &&
14457         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14458      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14459      APInt ShAmt = N1C->getAPIntValue();
14460      Mask = Mask.shl(ShAmt);
14461      if (Mask != 0)
14462        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14463                           N00, DAG.getConstant(Mask, VT));
14464    }
14465  }
14466
14467
14468  // Hardware support for vector shifts is sparse which makes us scalarize the
14469  // vector operations in many cases. Also, on sandybridge ADD is faster than
14470  // shl.
14471  // (shl V, 1) -> add V,V
14472  if (isSplatVector(N1.getNode())) {
14473    assert(N0.getValueType().isVector() && "Invalid vector shift type");
14474    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14475    // We shift all of the values by one. In many cases we do not have
14476    // hardware support for this operation. This is better expressed as an ADD
14477    // of two values.
14478    if (N1C && (1 == N1C->getZExtValue())) {
14479      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14480    }
14481  }
14482
14483  return SDValue();
14484}
14485
14486/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14487///                       when possible.
14488static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14489                                   TargetLowering::DAGCombinerInfo &DCI,
14490                                   const X86Subtarget *Subtarget) {
14491  EVT VT = N->getValueType(0);
14492  if (N->getOpcode() == ISD::SHL) {
14493    SDValue V = PerformSHLCombine(N, DAG);
14494    if (V.getNode()) return V;
14495  }
14496
14497  // On X86 with SSE2 support, we can transform this to a vector shift if
14498  // all elements are shifted by the same amount.  We can't do this in legalize
14499  // because the a constant vector is typically transformed to a constant pool
14500  // so we have no knowledge of the shift amount.
14501  if (!Subtarget->hasSSE2())
14502    return SDValue();
14503
14504  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14505      (!Subtarget->hasAVX2() ||
14506       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14507    return SDValue();
14508
14509  SDValue ShAmtOp = N->getOperand(1);
14510  EVT EltVT = VT.getVectorElementType();
14511  DebugLoc DL = N->getDebugLoc();
14512  SDValue BaseShAmt = SDValue();
14513  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14514    unsigned NumElts = VT.getVectorNumElements();
14515    unsigned i = 0;
14516    for (; i != NumElts; ++i) {
14517      SDValue Arg = ShAmtOp.getOperand(i);
14518      if (Arg.getOpcode() == ISD::UNDEF) continue;
14519      BaseShAmt = Arg;
14520      break;
14521    }
14522    // Handle the case where the build_vector is all undef
14523    // FIXME: Should DAG allow this?
14524    if (i == NumElts)
14525      return SDValue();
14526
14527    for (; i != NumElts; ++i) {
14528      SDValue Arg = ShAmtOp.getOperand(i);
14529      if (Arg.getOpcode() == ISD::UNDEF) continue;
14530      if (Arg != BaseShAmt) {
14531        return SDValue();
14532      }
14533    }
14534  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14535             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14536    SDValue InVec = ShAmtOp.getOperand(0);
14537    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14538      unsigned NumElts = InVec.getValueType().getVectorNumElements();
14539      unsigned i = 0;
14540      for (; i != NumElts; ++i) {
14541        SDValue Arg = InVec.getOperand(i);
14542        if (Arg.getOpcode() == ISD::UNDEF) continue;
14543        BaseShAmt = Arg;
14544        break;
14545      }
14546    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14547       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14548         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14549         if (C->getZExtValue() == SplatIdx)
14550           BaseShAmt = InVec.getOperand(1);
14551       }
14552    }
14553    if (BaseShAmt.getNode() == 0) {
14554      // Don't create instructions with illegal types after legalize
14555      // types has run.
14556      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14557          !DCI.isBeforeLegalize())
14558        return SDValue();
14559
14560      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14561                              DAG.getIntPtrConstant(0));
14562    }
14563  } else
14564    return SDValue();
14565
14566  // The shift amount is an i32.
14567  if (EltVT.bitsGT(MVT::i32))
14568    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14569  else if (EltVT.bitsLT(MVT::i32))
14570    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14571
14572  // The shift amount is identical so we can do a vector shift.
14573  SDValue  ValOp = N->getOperand(0);
14574  switch (N->getOpcode()) {
14575  default:
14576    llvm_unreachable("Unknown shift opcode!");
14577  case ISD::SHL:
14578    switch (VT.getSimpleVT().SimpleTy) {
14579    default: return SDValue();
14580    case MVT::v2i64:
14581    case MVT::v4i32:
14582    case MVT::v8i16:
14583    case MVT::v4i64:
14584    case MVT::v8i32:
14585    case MVT::v16i16:
14586      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14587    }
14588  case ISD::SRA:
14589    switch (VT.getSimpleVT().SimpleTy) {
14590    default: return SDValue();
14591    case MVT::v4i32:
14592    case MVT::v8i16:
14593    case MVT::v8i32:
14594    case MVT::v16i16:
14595      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14596    }
14597  case ISD::SRL:
14598    switch (VT.getSimpleVT().SimpleTy) {
14599    default: return SDValue();
14600    case MVT::v2i64:
14601    case MVT::v4i32:
14602    case MVT::v8i16:
14603    case MVT::v4i64:
14604    case MVT::v8i32:
14605    case MVT::v16i16:
14606      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14607    }
14608  }
14609}
14610
14611
14612// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14613// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14614// and friends.  Likewise for OR -> CMPNEQSS.
14615static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14616                            TargetLowering::DAGCombinerInfo &DCI,
14617                            const X86Subtarget *Subtarget) {
14618  unsigned opcode;
14619
14620  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14621  // we're requiring SSE2 for both.
14622  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14623    SDValue N0 = N->getOperand(0);
14624    SDValue N1 = N->getOperand(1);
14625    SDValue CMP0 = N0->getOperand(1);
14626    SDValue CMP1 = N1->getOperand(1);
14627    DebugLoc DL = N->getDebugLoc();
14628
14629    // The SETCCs should both refer to the same CMP.
14630    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14631      return SDValue();
14632
14633    SDValue CMP00 = CMP0->getOperand(0);
14634    SDValue CMP01 = CMP0->getOperand(1);
14635    EVT     VT    = CMP00.getValueType();
14636
14637    if (VT == MVT::f32 || VT == MVT::f64) {
14638      bool ExpectingFlags = false;
14639      // Check for any users that want flags:
14640      for (SDNode::use_iterator UI = N->use_begin(),
14641             UE = N->use_end();
14642           !ExpectingFlags && UI != UE; ++UI)
14643        switch (UI->getOpcode()) {
14644        default:
14645        case ISD::BR_CC:
14646        case ISD::BRCOND:
14647        case ISD::SELECT:
14648          ExpectingFlags = true;
14649          break;
14650        case ISD::CopyToReg:
14651        case ISD::SIGN_EXTEND:
14652        case ISD::ZERO_EXTEND:
14653        case ISD::ANY_EXTEND:
14654          break;
14655        }
14656
14657      if (!ExpectingFlags) {
14658        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14659        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14660
14661        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14662          X86::CondCode tmp = cc0;
14663          cc0 = cc1;
14664          cc1 = tmp;
14665        }
14666
14667        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14668            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14669          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14670          X86ISD::NodeType NTOperator = is64BitFP ?
14671            X86ISD::FSETCCsd : X86ISD::FSETCCss;
14672          // FIXME: need symbolic constants for these magic numbers.
14673          // See X86ATTInstPrinter.cpp:printSSECC().
14674          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14675          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14676                                              DAG.getConstant(x86cc, MVT::i8));
14677          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14678                                              OnesOrZeroesF);
14679          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14680                                      DAG.getConstant(1, MVT::i32));
14681          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14682          return OneBitOfTruth;
14683        }
14684      }
14685    }
14686  }
14687  return SDValue();
14688}
14689
14690/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14691/// so it can be folded inside ANDNP.
14692static bool CanFoldXORWithAllOnes(const SDNode *N) {
14693  EVT VT = N->getValueType(0);
14694
14695  // Match direct AllOnes for 128 and 256-bit vectors
14696  if (ISD::isBuildVectorAllOnes(N))
14697    return true;
14698
14699  // Look through a bit convert.
14700  if (N->getOpcode() == ISD::BITCAST)
14701    N = N->getOperand(0).getNode();
14702
14703  // Sometimes the operand may come from a insert_subvector building a 256-bit
14704  // allones vector
14705  if (VT.is256BitVector() &&
14706      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14707    SDValue V1 = N->getOperand(0);
14708    SDValue V2 = N->getOperand(1);
14709
14710    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14711        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14712        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14713        ISD::isBuildVectorAllOnes(V2.getNode()))
14714      return true;
14715  }
14716
14717  return false;
14718}
14719
14720static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14721                                 TargetLowering::DAGCombinerInfo &DCI,
14722                                 const X86Subtarget *Subtarget) {
14723  if (DCI.isBeforeLegalizeOps())
14724    return SDValue();
14725
14726  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14727  if (R.getNode())
14728    return R;
14729
14730  EVT VT = N->getValueType(0);
14731
14732  // Create ANDN, BLSI, and BLSR instructions
14733  // BLSI is X & (-X)
14734  // BLSR is X & (X-1)
14735  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14736    SDValue N0 = N->getOperand(0);
14737    SDValue N1 = N->getOperand(1);
14738    DebugLoc DL = N->getDebugLoc();
14739
14740    // Check LHS for not
14741    if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14742      return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14743    // Check RHS for not
14744    if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14745      return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14746
14747    // Check LHS for neg
14748    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14749        isZero(N0.getOperand(0)))
14750      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14751
14752    // Check RHS for neg
14753    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14754        isZero(N1.getOperand(0)))
14755      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14756
14757    // Check LHS for X-1
14758    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14759        isAllOnes(N0.getOperand(1)))
14760      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14761
14762    // Check RHS for X-1
14763    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14764        isAllOnes(N1.getOperand(1)))
14765      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14766
14767    return SDValue();
14768  }
14769
14770  // Want to form ANDNP nodes:
14771  // 1) In the hopes of then easily combining them with OR and AND nodes
14772  //    to form PBLEND/PSIGN.
14773  // 2) To match ANDN packed intrinsics
14774  if (VT != MVT::v2i64 && VT != MVT::v4i64)
14775    return SDValue();
14776
14777  SDValue N0 = N->getOperand(0);
14778  SDValue N1 = N->getOperand(1);
14779  DebugLoc DL = N->getDebugLoc();
14780
14781  // Check LHS for vnot
14782  if (N0.getOpcode() == ISD::XOR &&
14783      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14784      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14785    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14786
14787  // Check RHS for vnot
14788  if (N1.getOpcode() == ISD::XOR &&
14789      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14790      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14791    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14792
14793  return SDValue();
14794}
14795
14796static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14797                                TargetLowering::DAGCombinerInfo &DCI,
14798                                const X86Subtarget *Subtarget) {
14799  if (DCI.isBeforeLegalizeOps())
14800    return SDValue();
14801
14802  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14803  if (R.getNode())
14804    return R;
14805
14806  EVT VT = N->getValueType(0);
14807
14808  SDValue N0 = N->getOperand(0);
14809  SDValue N1 = N->getOperand(1);
14810
14811  // look for psign/blend
14812  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14813    if (!Subtarget->hasSSSE3() ||
14814        (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14815      return SDValue();
14816
14817    // Canonicalize pandn to RHS
14818    if (N0.getOpcode() == X86ISD::ANDNP)
14819      std::swap(N0, N1);
14820    // or (and (m, y), (pandn m, x))
14821    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14822      SDValue Mask = N1.getOperand(0);
14823      SDValue X    = N1.getOperand(1);
14824      SDValue Y;
14825      if (N0.getOperand(0) == Mask)
14826        Y = N0.getOperand(1);
14827      if (N0.getOperand(1) == Mask)
14828        Y = N0.getOperand(0);
14829
14830      // Check to see if the mask appeared in both the AND and ANDNP and
14831      if (!Y.getNode())
14832        return SDValue();
14833
14834      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14835      // Look through mask bitcast.
14836      if (Mask.getOpcode() == ISD::BITCAST)
14837        Mask = Mask.getOperand(0);
14838      if (X.getOpcode() == ISD::BITCAST)
14839        X = X.getOperand(0);
14840      if (Y.getOpcode() == ISD::BITCAST)
14841        Y = Y.getOperand(0);
14842
14843      EVT MaskVT = Mask.getValueType();
14844
14845      // Validate that the Mask operand is a vector sra node.
14846      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14847      // there is no psrai.b
14848      if (Mask.getOpcode() != X86ISD::VSRAI)
14849        return SDValue();
14850
14851      // Check that the SRA is all signbits.
14852      SDValue SraC = Mask.getOperand(1);
14853      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14854      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14855      if ((SraAmt + 1) != EltBits)
14856        return SDValue();
14857
14858      DebugLoc DL = N->getDebugLoc();
14859
14860      // Now we know we at least have a plendvb with the mask val.  See if
14861      // we can form a psignb/w/d.
14862      // psign = x.type == y.type == mask.type && y = sub(0, x);
14863      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14864          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14865          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14866        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14867               "Unsupported VT for PSIGN");
14868        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14869        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14870      }
14871      // PBLENDVB only available on SSE 4.1
14872      if (!Subtarget->hasSSE41())
14873        return SDValue();
14874
14875      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14876
14877      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14878      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14879      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14880      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14881      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14882    }
14883  }
14884
14885  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14886    return SDValue();
14887
14888  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14889  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14890    std::swap(N0, N1);
14891  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14892    return SDValue();
14893  if (!N0.hasOneUse() || !N1.hasOneUse())
14894    return SDValue();
14895
14896  SDValue ShAmt0 = N0.getOperand(1);
14897  if (ShAmt0.getValueType() != MVT::i8)
14898    return SDValue();
14899  SDValue ShAmt1 = N1.getOperand(1);
14900  if (ShAmt1.getValueType() != MVT::i8)
14901    return SDValue();
14902  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14903    ShAmt0 = ShAmt0.getOperand(0);
14904  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14905    ShAmt1 = ShAmt1.getOperand(0);
14906
14907  DebugLoc DL = N->getDebugLoc();
14908  unsigned Opc = X86ISD::SHLD;
14909  SDValue Op0 = N0.getOperand(0);
14910  SDValue Op1 = N1.getOperand(0);
14911  if (ShAmt0.getOpcode() == ISD::SUB) {
14912    Opc = X86ISD::SHRD;
14913    std::swap(Op0, Op1);
14914    std::swap(ShAmt0, ShAmt1);
14915  }
14916
14917  unsigned Bits = VT.getSizeInBits();
14918  if (ShAmt1.getOpcode() == ISD::SUB) {
14919    SDValue Sum = ShAmt1.getOperand(0);
14920    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14921      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14922      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14923        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14924      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14925        return DAG.getNode(Opc, DL, VT,
14926                           Op0, Op1,
14927                           DAG.getNode(ISD::TRUNCATE, DL,
14928                                       MVT::i8, ShAmt0));
14929    }
14930  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14931    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14932    if (ShAmt0C &&
14933        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14934      return DAG.getNode(Opc, DL, VT,
14935                         N0.getOperand(0), N1.getOperand(0),
14936                         DAG.getNode(ISD::TRUNCATE, DL,
14937                                       MVT::i8, ShAmt0));
14938  }
14939
14940  return SDValue();
14941}
14942
14943// Generate NEG and CMOV for integer abs.
14944static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14945  EVT VT = N->getValueType(0);
14946
14947  // Since X86 does not have CMOV for 8-bit integer, we don't convert
14948  // 8-bit integer abs to NEG and CMOV.
14949  if (VT.isInteger() && VT.getSizeInBits() == 8)
14950    return SDValue();
14951
14952  SDValue N0 = N->getOperand(0);
14953  SDValue N1 = N->getOperand(1);
14954  DebugLoc DL = N->getDebugLoc();
14955
14956  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14957  // and change it to SUB and CMOV.
14958  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14959      N0.getOpcode() == ISD::ADD &&
14960      N0.getOperand(1) == N1 &&
14961      N1.getOpcode() == ISD::SRA &&
14962      N1.getOperand(0) == N0.getOperand(0))
14963    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14964      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14965        // Generate SUB & CMOV.
14966        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14967                                  DAG.getConstant(0, VT), N0.getOperand(0));
14968
14969        SDValue Ops[] = { N0.getOperand(0), Neg,
14970                          DAG.getConstant(X86::COND_GE, MVT::i8),
14971                          SDValue(Neg.getNode(), 1) };
14972        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14973                           Ops, array_lengthof(Ops));
14974      }
14975  return SDValue();
14976}
14977
14978// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14979static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14980                                 TargetLowering::DAGCombinerInfo &DCI,
14981                                 const X86Subtarget *Subtarget) {
14982  if (DCI.isBeforeLegalizeOps())
14983    return SDValue();
14984
14985  if (Subtarget->hasCMov()) {
14986    SDValue RV = performIntegerAbsCombine(N, DAG);
14987    if (RV.getNode())
14988      return RV;
14989  }
14990
14991  // Try forming BMI if it is available.
14992  if (!Subtarget->hasBMI())
14993    return SDValue();
14994
14995  EVT VT = N->getValueType(0);
14996
14997  if (VT != MVT::i32 && VT != MVT::i64)
14998    return SDValue();
14999
15000  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15001
15002  // Create BLSMSK instructions by finding X ^ (X-1)
15003  SDValue N0 = N->getOperand(0);
15004  SDValue N1 = N->getOperand(1);
15005  DebugLoc DL = N->getDebugLoc();
15006
15007  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15008      isAllOnes(N0.getOperand(1)))
15009    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15010
15011  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15012      isAllOnes(N1.getOperand(1)))
15013    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15014
15015  return SDValue();
15016}
15017
15018/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15019static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15020                                  TargetLowering::DAGCombinerInfo &DCI,
15021                                  const X86Subtarget *Subtarget) {
15022  LoadSDNode *Ld = cast<LoadSDNode>(N);
15023  EVT RegVT = Ld->getValueType(0);
15024  EVT MemVT = Ld->getMemoryVT();
15025  DebugLoc dl = Ld->getDebugLoc();
15026  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15027
15028  ISD::LoadExtType Ext = Ld->getExtensionType();
15029
15030  // If this is a vector EXT Load then attempt to optimize it using a
15031  // shuffle. We need SSE4 for the shuffles.
15032  // TODO: It is possible to support ZExt by zeroing the undef values
15033  // during the shuffle phase or after the shuffle.
15034  if (RegVT.isVector() && RegVT.isInteger() &&
15035      Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15036    assert(MemVT != RegVT && "Cannot extend to the same type");
15037    assert(MemVT.isVector() && "Must load a vector from memory");
15038
15039    unsigned NumElems = RegVT.getVectorNumElements();
15040    unsigned RegSz = RegVT.getSizeInBits();
15041    unsigned MemSz = MemVT.getSizeInBits();
15042    assert(RegSz > MemSz && "Register size must be greater than the mem size");
15043
15044    // All sizes must be a power of two.
15045    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15046      return SDValue();
15047
15048    // Attempt to load the original value using scalar loads.
15049    // Find the largest scalar type that divides the total loaded size.
15050    MVT SclrLoadTy = MVT::i8;
15051    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15052         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15053      MVT Tp = (MVT::SimpleValueType)tp;
15054      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15055        SclrLoadTy = Tp;
15056      }
15057    }
15058
15059    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15060    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15061        (64 <= MemSz))
15062      SclrLoadTy = MVT::f64;
15063
15064    // Calculate the number of scalar loads that we need to perform
15065    // in order to load our vector from memory.
15066    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15067
15068    // Represent our vector as a sequence of elements which are the
15069    // largest scalar that we can load.
15070    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15071      RegSz/SclrLoadTy.getSizeInBits());
15072
15073    // Represent the data using the same element type that is stored in
15074    // memory. In practice, we ''widen'' MemVT.
15075    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15076                                  RegSz/MemVT.getScalarType().getSizeInBits());
15077
15078    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15079      "Invalid vector type");
15080
15081    // We can't shuffle using an illegal type.
15082    if (!TLI.isTypeLegal(WideVecVT))
15083      return SDValue();
15084
15085    SmallVector<SDValue, 8> Chains;
15086    SDValue Ptr = Ld->getBasePtr();
15087    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15088                                        TLI.getPointerTy());
15089    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15090
15091    for (unsigned i = 0; i < NumLoads; ++i) {
15092      // Perform a single load.
15093      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15094                                       Ptr, Ld->getPointerInfo(),
15095                                       Ld->isVolatile(), Ld->isNonTemporal(),
15096                                       Ld->isInvariant(), Ld->getAlignment());
15097      Chains.push_back(ScalarLoad.getValue(1));
15098      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15099      // another round of DAGCombining.
15100      if (i == 0)
15101        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15102      else
15103        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15104                          ScalarLoad, DAG.getIntPtrConstant(i));
15105
15106      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15107    }
15108
15109    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15110                               Chains.size());
15111
15112    // Bitcast the loaded value to a vector of the original element type, in
15113    // the size of the target vector type.
15114    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15115    unsigned SizeRatio = RegSz/MemSz;
15116
15117    // Redistribute the loaded elements into the different locations.
15118    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15119    for (unsigned i = 0; i != NumElems; ++i)
15120      ShuffleVec[i*SizeRatio] = i;
15121
15122    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15123                                         DAG.getUNDEF(WideVecVT),
15124                                         &ShuffleVec[0]);
15125
15126    // Bitcast to the requested type.
15127    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15128    // Replace the original load with the new sequence
15129    // and return the new chain.
15130    return DCI.CombineTo(N, Shuff, TF, true);
15131  }
15132
15133  return SDValue();
15134}
15135
15136/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15137static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15138                                   const X86Subtarget *Subtarget) {
15139  StoreSDNode *St = cast<StoreSDNode>(N);
15140  EVT VT = St->getValue().getValueType();
15141  EVT StVT = St->getMemoryVT();
15142  DebugLoc dl = St->getDebugLoc();
15143  SDValue StoredVal = St->getOperand(1);
15144  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15145
15146  // If we are saving a concatenation of two XMM registers, perform two stores.
15147  // On Sandy Bridge, 256-bit memory operations are executed by two
15148  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15149  // memory  operation.
15150  if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15151      StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15152      StoredVal.getNumOperands() == 2) {
15153    SDValue Value0 = StoredVal.getOperand(0);
15154    SDValue Value1 = StoredVal.getOperand(1);
15155
15156    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15157    SDValue Ptr0 = St->getBasePtr();
15158    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15159
15160    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15161                                St->getPointerInfo(), St->isVolatile(),
15162                                St->isNonTemporal(), St->getAlignment());
15163    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15164                                St->getPointerInfo(), St->isVolatile(),
15165                                St->isNonTemporal(), St->getAlignment());
15166    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15167  }
15168
15169  // Optimize trunc store (of multiple scalars) to shuffle and store.
15170  // First, pack all of the elements in one place. Next, store to memory
15171  // in fewer chunks.
15172  if (St->isTruncatingStore() && VT.isVector()) {
15173    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15174    unsigned NumElems = VT.getVectorNumElements();
15175    assert(StVT != VT && "Cannot truncate to the same type");
15176    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15177    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15178
15179    // From, To sizes and ElemCount must be pow of two
15180    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15181    // We are going to use the original vector elt for storing.
15182    // Accumulated smaller vector elements must be a multiple of the store size.
15183    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15184
15185    unsigned SizeRatio  = FromSz / ToSz;
15186
15187    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15188
15189    // Create a type on which we perform the shuffle
15190    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15191            StVT.getScalarType(), NumElems*SizeRatio);
15192
15193    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15194
15195    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15196    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15197    for (unsigned i = 0; i != NumElems; ++i)
15198      ShuffleVec[i] = i * SizeRatio;
15199
15200    // Can't shuffle using an illegal type.
15201    if (!TLI.isTypeLegal(WideVecVT))
15202      return SDValue();
15203
15204    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15205                                         DAG.getUNDEF(WideVecVT),
15206                                         &ShuffleVec[0]);
15207    // At this point all of the data is stored at the bottom of the
15208    // register. We now need to save it to mem.
15209
15210    // Find the largest store unit
15211    MVT StoreType = MVT::i8;
15212    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15213         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15214      MVT Tp = (MVT::SimpleValueType)tp;
15215      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15216        StoreType = Tp;
15217    }
15218
15219    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15220    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15221        (64 <= NumElems * ToSz))
15222      StoreType = MVT::f64;
15223
15224    // Bitcast the original vector into a vector of store-size units
15225    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15226            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15227    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15228    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15229    SmallVector<SDValue, 8> Chains;
15230    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15231                                        TLI.getPointerTy());
15232    SDValue Ptr = St->getBasePtr();
15233
15234    // Perform one or more big stores into memory.
15235    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15236      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15237                                   StoreType, ShuffWide,
15238                                   DAG.getIntPtrConstant(i));
15239      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15240                                St->getPointerInfo(), St->isVolatile(),
15241                                St->isNonTemporal(), St->getAlignment());
15242      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15243      Chains.push_back(Ch);
15244    }
15245
15246    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15247                               Chains.size());
15248  }
15249
15250
15251  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15252  // the FP state in cases where an emms may be missing.
15253  // A preferable solution to the general problem is to figure out the right
15254  // places to insert EMMS.  This qualifies as a quick hack.
15255
15256  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15257  if (VT.getSizeInBits() != 64)
15258    return SDValue();
15259
15260  const Function *F = DAG.getMachineFunction().getFunction();
15261  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15262  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15263                     && Subtarget->hasSSE2();
15264  if ((VT.isVector() ||
15265       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15266      isa<LoadSDNode>(St->getValue()) &&
15267      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15268      St->getChain().hasOneUse() && !St->isVolatile()) {
15269    SDNode* LdVal = St->getValue().getNode();
15270    LoadSDNode *Ld = 0;
15271    int TokenFactorIndex = -1;
15272    SmallVector<SDValue, 8> Ops;
15273    SDNode* ChainVal = St->getChain().getNode();
15274    // Must be a store of a load.  We currently handle two cases:  the load
15275    // is a direct child, and it's under an intervening TokenFactor.  It is
15276    // possible to dig deeper under nested TokenFactors.
15277    if (ChainVal == LdVal)
15278      Ld = cast<LoadSDNode>(St->getChain());
15279    else if (St->getValue().hasOneUse() &&
15280             ChainVal->getOpcode() == ISD::TokenFactor) {
15281      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15282        if (ChainVal->getOperand(i).getNode() == LdVal) {
15283          TokenFactorIndex = i;
15284          Ld = cast<LoadSDNode>(St->getValue());
15285        } else
15286          Ops.push_back(ChainVal->getOperand(i));
15287      }
15288    }
15289
15290    if (!Ld || !ISD::isNormalLoad(Ld))
15291      return SDValue();
15292
15293    // If this is not the MMX case, i.e. we are just turning i64 load/store
15294    // into f64 load/store, avoid the transformation if there are multiple
15295    // uses of the loaded value.
15296    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15297      return SDValue();
15298
15299    DebugLoc LdDL = Ld->getDebugLoc();
15300    DebugLoc StDL = N->getDebugLoc();
15301    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15302    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15303    // pair instead.
15304    if (Subtarget->is64Bit() || F64IsLegal) {
15305      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15306      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15307                                  Ld->getPointerInfo(), Ld->isVolatile(),
15308                                  Ld->isNonTemporal(), Ld->isInvariant(),
15309                                  Ld->getAlignment());
15310      SDValue NewChain = NewLd.getValue(1);
15311      if (TokenFactorIndex != -1) {
15312        Ops.push_back(NewChain);
15313        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15314                               Ops.size());
15315      }
15316      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15317                          St->getPointerInfo(),
15318                          St->isVolatile(), St->isNonTemporal(),
15319                          St->getAlignment());
15320    }
15321
15322    // Otherwise, lower to two pairs of 32-bit loads / stores.
15323    SDValue LoAddr = Ld->getBasePtr();
15324    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15325                                 DAG.getConstant(4, MVT::i32));
15326
15327    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15328                               Ld->getPointerInfo(),
15329                               Ld->isVolatile(), Ld->isNonTemporal(),
15330                               Ld->isInvariant(), Ld->getAlignment());
15331    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15332                               Ld->getPointerInfo().getWithOffset(4),
15333                               Ld->isVolatile(), Ld->isNonTemporal(),
15334                               Ld->isInvariant(),
15335                               MinAlign(Ld->getAlignment(), 4));
15336
15337    SDValue NewChain = LoLd.getValue(1);
15338    if (TokenFactorIndex != -1) {
15339      Ops.push_back(LoLd);
15340      Ops.push_back(HiLd);
15341      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15342                             Ops.size());
15343    }
15344
15345    LoAddr = St->getBasePtr();
15346    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15347                         DAG.getConstant(4, MVT::i32));
15348
15349    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15350                                St->getPointerInfo(),
15351                                St->isVolatile(), St->isNonTemporal(),
15352                                St->getAlignment());
15353    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15354                                St->getPointerInfo().getWithOffset(4),
15355                                St->isVolatile(),
15356                                St->isNonTemporal(),
15357                                MinAlign(St->getAlignment(), 4));
15358    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15359  }
15360  return SDValue();
15361}
15362
15363/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15364/// and return the operands for the horizontal operation in LHS and RHS.  A
15365/// horizontal operation performs the binary operation on successive elements
15366/// of its first operand, then on successive elements of its second operand,
15367/// returning the resulting values in a vector.  For example, if
15368///   A = < float a0, float a1, float a2, float a3 >
15369/// and
15370///   B = < float b0, float b1, float b2, float b3 >
15371/// then the result of doing a horizontal operation on A and B is
15372///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15373/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15374/// A horizontal-op B, for some already available A and B, and if so then LHS is
15375/// set to A, RHS to B, and the routine returns 'true'.
15376/// Note that the binary operation should have the property that if one of the
15377/// operands is UNDEF then the result is UNDEF.
15378static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15379  // Look for the following pattern: if
15380  //   A = < float a0, float a1, float a2, float a3 >
15381  //   B = < float b0, float b1, float b2, float b3 >
15382  // and
15383  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15384  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15385  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15386  // which is A horizontal-op B.
15387
15388  // At least one of the operands should be a vector shuffle.
15389  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15390      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15391    return false;
15392
15393  EVT VT = LHS.getValueType();
15394
15395  assert((VT.is128BitVector() || VT.is256BitVector()) &&
15396         "Unsupported vector type for horizontal add/sub");
15397
15398  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15399  // operate independently on 128-bit lanes.
15400  unsigned NumElts = VT.getVectorNumElements();
15401  unsigned NumLanes = VT.getSizeInBits()/128;
15402  unsigned NumLaneElts = NumElts / NumLanes;
15403  assert((NumLaneElts % 2 == 0) &&
15404         "Vector type should have an even number of elements in each lane");
15405  unsigned HalfLaneElts = NumLaneElts/2;
15406
15407  // View LHS in the form
15408  //   LHS = VECTOR_SHUFFLE A, B, LMask
15409  // If LHS is not a shuffle then pretend it is the shuffle
15410  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15411  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15412  // type VT.
15413  SDValue A, B;
15414  SmallVector<int, 16> LMask(NumElts);
15415  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15416    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15417      A = LHS.getOperand(0);
15418    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15419      B = LHS.getOperand(1);
15420    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15421    std::copy(Mask.begin(), Mask.end(), LMask.begin());
15422  } else {
15423    if (LHS.getOpcode() != ISD::UNDEF)
15424      A = LHS;
15425    for (unsigned i = 0; i != NumElts; ++i)
15426      LMask[i] = i;
15427  }
15428
15429  // Likewise, view RHS in the form
15430  //   RHS = VECTOR_SHUFFLE C, D, RMask
15431  SDValue C, D;
15432  SmallVector<int, 16> RMask(NumElts);
15433  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15434    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15435      C = RHS.getOperand(0);
15436    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15437      D = RHS.getOperand(1);
15438    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15439    std::copy(Mask.begin(), Mask.end(), RMask.begin());
15440  } else {
15441    if (RHS.getOpcode() != ISD::UNDEF)
15442      C = RHS;
15443    for (unsigned i = 0; i != NumElts; ++i)
15444      RMask[i] = i;
15445  }
15446
15447  // Check that the shuffles are both shuffling the same vectors.
15448  if (!(A == C && B == D) && !(A == D && B == C))
15449    return false;
15450
15451  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15452  if (!A.getNode() && !B.getNode())
15453    return false;
15454
15455  // If A and B occur in reverse order in RHS, then "swap" them (which means
15456  // rewriting the mask).
15457  if (A != C)
15458    CommuteVectorShuffleMask(RMask, NumElts);
15459
15460  // At this point LHS and RHS are equivalent to
15461  //   LHS = VECTOR_SHUFFLE A, B, LMask
15462  //   RHS = VECTOR_SHUFFLE A, B, RMask
15463  // Check that the masks correspond to performing a horizontal operation.
15464  for (unsigned i = 0; i != NumElts; ++i) {
15465    int LIdx = LMask[i], RIdx = RMask[i];
15466
15467    // Ignore any UNDEF components.
15468    if (LIdx < 0 || RIdx < 0 ||
15469        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15470        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15471      continue;
15472
15473    // Check that successive elements are being operated on.  If not, this is
15474    // not a horizontal operation.
15475    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15476    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15477    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15478    if (!(LIdx == Index && RIdx == Index + 1) &&
15479        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15480      return false;
15481  }
15482
15483  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15484  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15485  return true;
15486}
15487
15488/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15489static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15490                                  const X86Subtarget *Subtarget) {
15491  EVT VT = N->getValueType(0);
15492  SDValue LHS = N->getOperand(0);
15493  SDValue RHS = N->getOperand(1);
15494
15495  // Try to synthesize horizontal adds from adds of shuffles.
15496  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15497       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15498      isHorizontalBinOp(LHS, RHS, true))
15499    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15500  return SDValue();
15501}
15502
15503/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15504static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15505                                  const X86Subtarget *Subtarget) {
15506  EVT VT = N->getValueType(0);
15507  SDValue LHS = N->getOperand(0);
15508  SDValue RHS = N->getOperand(1);
15509
15510  // Try to synthesize horizontal subs from subs of shuffles.
15511  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15512       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15513      isHorizontalBinOp(LHS, RHS, false))
15514    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15515  return SDValue();
15516}
15517
15518/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15519/// X86ISD::FXOR nodes.
15520static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15521  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15522  // F[X]OR(0.0, x) -> x
15523  // F[X]OR(x, 0.0) -> x
15524  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15525    if (C->getValueAPF().isPosZero())
15526      return N->getOperand(1);
15527  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15528    if (C->getValueAPF().isPosZero())
15529      return N->getOperand(0);
15530  return SDValue();
15531}
15532
15533/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15534/// X86ISD::FMAX nodes.
15535static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15536  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15537
15538  // Only perform optimizations if UnsafeMath is used.
15539  if (!DAG.getTarget().Options.UnsafeFPMath)
15540    return SDValue();
15541
15542  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15543  // into FMINC and FMAXC, which are Commutative operations.
15544  unsigned NewOp = 0;
15545  switch (N->getOpcode()) {
15546    default: llvm_unreachable("unknown opcode");
15547    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15548    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15549  }
15550
15551  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15552                     N->getOperand(0), N->getOperand(1));
15553}
15554
15555
15556/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15557static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15558  // FAND(0.0, x) -> 0.0
15559  // FAND(x, 0.0) -> 0.0
15560  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15561    if (C->getValueAPF().isPosZero())
15562      return N->getOperand(0);
15563  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15564    if (C->getValueAPF().isPosZero())
15565      return N->getOperand(1);
15566  return SDValue();
15567}
15568
15569static SDValue PerformBTCombine(SDNode *N,
15570                                SelectionDAG &DAG,
15571                                TargetLowering::DAGCombinerInfo &DCI) {
15572  // BT ignores high bits in the bit index operand.
15573  SDValue Op1 = N->getOperand(1);
15574  if (Op1.hasOneUse()) {
15575    unsigned BitWidth = Op1.getValueSizeInBits();
15576    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15577    APInt KnownZero, KnownOne;
15578    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15579                                          !DCI.isBeforeLegalizeOps());
15580    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15581    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15582        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15583      DCI.CommitTargetLoweringOpt(TLO);
15584  }
15585  return SDValue();
15586}
15587
15588static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15589  SDValue Op = N->getOperand(0);
15590  if (Op.getOpcode() == ISD::BITCAST)
15591    Op = Op.getOperand(0);
15592  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15593  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15594      VT.getVectorElementType().getSizeInBits() ==
15595      OpVT.getVectorElementType().getSizeInBits()) {
15596    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15597  }
15598  return SDValue();
15599}
15600
15601static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15602                                  TargetLowering::DAGCombinerInfo &DCI,
15603                                  const X86Subtarget *Subtarget) {
15604  if (!DCI.isBeforeLegalizeOps())
15605    return SDValue();
15606
15607  if (!Subtarget->hasAVX())
15608    return SDValue();
15609
15610  EVT VT = N->getValueType(0);
15611  SDValue Op = N->getOperand(0);
15612  EVT OpVT = Op.getValueType();
15613  DebugLoc dl = N->getDebugLoc();
15614
15615  if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15616      (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15617
15618    if (Subtarget->hasAVX2())
15619      return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15620
15621    // Optimize vectors in AVX mode
15622    // Sign extend  v8i16 to v8i32 and
15623    //              v4i32 to v4i64
15624    //
15625    // Divide input vector into two parts
15626    // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15627    // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15628    // concat the vectors to original VT
15629
15630    unsigned NumElems = OpVT.getVectorNumElements();
15631    SDValue Undef = DAG.getUNDEF(OpVT);
15632
15633    SmallVector<int,8> ShufMask1(NumElems, -1);
15634    for (unsigned i = 0; i != NumElems/2; ++i)
15635      ShufMask1[i] = i;
15636
15637    SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15638
15639    SmallVector<int,8> ShufMask2(NumElems, -1);
15640    for (unsigned i = 0; i != NumElems/2; ++i)
15641      ShufMask2[i] = i + NumElems/2;
15642
15643    SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15644
15645    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15646                                  VT.getVectorNumElements()/2);
15647
15648    OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15649    OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15650
15651    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15652  }
15653  return SDValue();
15654}
15655
15656static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15657                                 const X86Subtarget* Subtarget) {
15658  DebugLoc dl = N->getDebugLoc();
15659  EVT VT = N->getValueType(0);
15660
15661  // Let legalize expand this if it isn't a legal type yet.
15662  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15663    return SDValue();
15664
15665  EVT ScalarVT = VT.getScalarType();
15666  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15667      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15668    return SDValue();
15669
15670  SDValue A = N->getOperand(0);
15671  SDValue B = N->getOperand(1);
15672  SDValue C = N->getOperand(2);
15673
15674  bool NegA = (A.getOpcode() == ISD::FNEG);
15675  bool NegB = (B.getOpcode() == ISD::FNEG);
15676  bool NegC = (C.getOpcode() == ISD::FNEG);
15677
15678  // Negative multiplication when NegA xor NegB
15679  bool NegMul = (NegA != NegB);
15680  if (NegA)
15681    A = A.getOperand(0);
15682  if (NegB)
15683    B = B.getOperand(0);
15684  if (NegC)
15685    C = C.getOperand(0);
15686
15687  unsigned Opcode;
15688  if (!NegMul)
15689    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15690  else
15691    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15692
15693  return DAG.getNode(Opcode, dl, VT, A, B, C);
15694}
15695
15696static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15697                                  TargetLowering::DAGCombinerInfo &DCI,
15698                                  const X86Subtarget *Subtarget) {
15699  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15700  //           (and (i32 x86isd::setcc_carry), 1)
15701  // This eliminates the zext. This transformation is necessary because
15702  // ISD::SETCC is always legalized to i8.
15703  DebugLoc dl = N->getDebugLoc();
15704  SDValue N0 = N->getOperand(0);
15705  EVT VT = N->getValueType(0);
15706  EVT OpVT = N0.getValueType();
15707
15708  if (N0.getOpcode() == ISD::AND &&
15709      N0.hasOneUse() &&
15710      N0.getOperand(0).hasOneUse()) {
15711    SDValue N00 = N0.getOperand(0);
15712    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15713      return SDValue();
15714    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15715    if (!C || C->getZExtValue() != 1)
15716      return SDValue();
15717    return DAG.getNode(ISD::AND, dl, VT,
15718                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15719                                   N00.getOperand(0), N00.getOperand(1)),
15720                       DAG.getConstant(1, VT));
15721  }
15722
15723  // Optimize vectors in AVX mode:
15724  //
15725  //   v8i16 -> v8i32
15726  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15727  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15728  //   Concat upper and lower parts.
15729  //
15730  //   v4i32 -> v4i64
15731  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15732  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15733  //   Concat upper and lower parts.
15734  //
15735  if (!DCI.isBeforeLegalizeOps())
15736    return SDValue();
15737
15738  if (!Subtarget->hasAVX())
15739    return SDValue();
15740
15741  if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15742      ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15743
15744    if (Subtarget->hasAVX2())
15745      return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15746
15747    SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15748    SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15749    SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15750
15751    EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15752                               VT.getVectorNumElements()/2);
15753
15754    OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15755    OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15756
15757    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15758  }
15759
15760  return SDValue();
15761}
15762
15763// Optimize x == -y --> x+y == 0
15764//          x != -y --> x+y != 0
15765static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15766  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15767  SDValue LHS = N->getOperand(0);
15768  SDValue RHS = N->getOperand(1);
15769
15770  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15771    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15772      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15773        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15774                                   LHS.getValueType(), RHS, LHS.getOperand(1));
15775        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15776                            addV, DAG.getConstant(0, addV.getValueType()), CC);
15777      }
15778  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15779    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15780      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15781        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15782                                   RHS.getValueType(), LHS, RHS.getOperand(1));
15783        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15784                            addV, DAG.getConstant(0, addV.getValueType()), CC);
15785      }
15786  return SDValue();
15787}
15788
15789// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15790static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15791                                   TargetLowering::DAGCombinerInfo &DCI,
15792                                   const X86Subtarget *Subtarget) {
15793  DebugLoc DL = N->getDebugLoc();
15794  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15795  SDValue EFLAGS = N->getOperand(1);
15796
15797  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15798  // a zext and produces an all-ones bit which is more useful than 0/1 in some
15799  // cases.
15800  if (CC == X86::COND_B)
15801    return DAG.getNode(ISD::AND, DL, MVT::i8,
15802                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15803                                   DAG.getConstant(CC, MVT::i8), EFLAGS),
15804                       DAG.getConstant(1, MVT::i8));
15805
15806  SDValue Flags;
15807
15808  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15809  if (Flags.getNode()) {
15810    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15811    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15812  }
15813
15814  Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15815  if (Flags.getNode()) {
15816    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15817    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15818  }
15819
15820  return SDValue();
15821}
15822
15823// Optimize branch condition evaluation.
15824//
15825static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15826                                    TargetLowering::DAGCombinerInfo &DCI,
15827                                    const X86Subtarget *Subtarget) {
15828  DebugLoc DL = N->getDebugLoc();
15829  SDValue Chain = N->getOperand(0);
15830  SDValue Dest = N->getOperand(1);
15831  SDValue EFLAGS = N->getOperand(3);
15832  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15833
15834  SDValue Flags;
15835
15836  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15837  if (Flags.getNode()) {
15838    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15839    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15840                       Flags);
15841  }
15842
15843  Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15844  if (Flags.getNode()) {
15845    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15846    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15847                       Flags);
15848  }
15849
15850  return SDValue();
15851}
15852
15853static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15854  SDValue Op0 = N->getOperand(0);
15855  EVT InVT = Op0->getValueType(0);
15856
15857  // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15858  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15859    DebugLoc dl = N->getDebugLoc();
15860    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15861    SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15862    // Notice that we use SINT_TO_FP because we know that the high bits
15863    // are zero and SINT_TO_FP is better supported by the hardware.
15864    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15865  }
15866
15867  return SDValue();
15868}
15869
15870static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15871                                        const X86TargetLowering *XTLI) {
15872  SDValue Op0 = N->getOperand(0);
15873  EVT InVT = Op0->getValueType(0);
15874
15875  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15876  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15877    DebugLoc dl = N->getDebugLoc();
15878    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15879    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15880    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15881  }
15882
15883  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15884  // a 32-bit target where SSE doesn't support i64->FP operations.
15885  if (Op0.getOpcode() == ISD::LOAD) {
15886    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15887    EVT VT = Ld->getValueType(0);
15888    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15889        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15890        !XTLI->getSubtarget()->is64Bit() &&
15891        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15892      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15893                                          Ld->getChain(), Op0, DAG);
15894      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15895      return FILDChain;
15896    }
15897  }
15898  return SDValue();
15899}
15900
15901static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15902  EVT VT = N->getValueType(0);
15903
15904  // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15905  if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15906    DebugLoc dl = N->getDebugLoc();
15907    MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15908    SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15909    return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15910  }
15911
15912  return SDValue();
15913}
15914
15915// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15916static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15917                                 X86TargetLowering::DAGCombinerInfo &DCI) {
15918  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15919  // the result is either zero or one (depending on the input carry bit).
15920  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15921  if (X86::isZeroNode(N->getOperand(0)) &&
15922      X86::isZeroNode(N->getOperand(1)) &&
15923      // We don't have a good way to replace an EFLAGS use, so only do this when
15924      // dead right now.
15925      SDValue(N, 1).use_empty()) {
15926    DebugLoc DL = N->getDebugLoc();
15927    EVT VT = N->getValueType(0);
15928    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15929    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15930                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15931                                           DAG.getConstant(X86::COND_B,MVT::i8),
15932                                           N->getOperand(2)),
15933                               DAG.getConstant(1, VT));
15934    return DCI.CombineTo(N, Res1, CarryOut);
15935  }
15936
15937  return SDValue();
15938}
15939
15940// fold (add Y, (sete  X, 0)) -> adc  0, Y
15941//      (add Y, (setne X, 0)) -> sbb -1, Y
15942//      (sub (sete  X, 0), Y) -> sbb  0, Y
15943//      (sub (setne X, 0), Y) -> adc -1, Y
15944static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15945  DebugLoc DL = N->getDebugLoc();
15946
15947  // Look through ZExts.
15948  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15949  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15950    return SDValue();
15951
15952  SDValue SetCC = Ext.getOperand(0);
15953  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15954    return SDValue();
15955
15956  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15957  if (CC != X86::COND_E && CC != X86::COND_NE)
15958    return SDValue();
15959
15960  SDValue Cmp = SetCC.getOperand(1);
15961  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15962      !X86::isZeroNode(Cmp.getOperand(1)) ||
15963      !Cmp.getOperand(0).getValueType().isInteger())
15964    return SDValue();
15965
15966  SDValue CmpOp0 = Cmp.getOperand(0);
15967  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15968                               DAG.getConstant(1, CmpOp0.getValueType()));
15969
15970  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15971  if (CC == X86::COND_NE)
15972    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15973                       DL, OtherVal.getValueType(), OtherVal,
15974                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15975  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15976                     DL, OtherVal.getValueType(), OtherVal,
15977                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15978}
15979
15980/// PerformADDCombine - Do target-specific dag combines on integer adds.
15981static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15982                                 const X86Subtarget *Subtarget) {
15983  EVT VT = N->getValueType(0);
15984  SDValue Op0 = N->getOperand(0);
15985  SDValue Op1 = N->getOperand(1);
15986
15987  // Try to synthesize horizontal adds from adds of shuffles.
15988  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15989       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15990      isHorizontalBinOp(Op0, Op1, true))
15991    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15992
15993  return OptimizeConditionalInDecrement(N, DAG);
15994}
15995
15996static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15997                                 const X86Subtarget *Subtarget) {
15998  SDValue Op0 = N->getOperand(0);
15999  SDValue Op1 = N->getOperand(1);
16000
16001  // X86 can't encode an immediate LHS of a sub. See if we can push the
16002  // negation into a preceding instruction.
16003  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16004    // If the RHS of the sub is a XOR with one use and a constant, invert the
16005    // immediate. Then add one to the LHS of the sub so we can turn
16006    // X-Y -> X+~Y+1, saving one register.
16007    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16008        isa<ConstantSDNode>(Op1.getOperand(1))) {
16009      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16010      EVT VT = Op0.getValueType();
16011      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16012                                   Op1.getOperand(0),
16013                                   DAG.getConstant(~XorC, VT));
16014      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16015                         DAG.getConstant(C->getAPIntValue()+1, VT));
16016    }
16017  }
16018
16019  // Try to synthesize horizontal adds from adds of shuffles.
16020  EVT VT = N->getValueType(0);
16021  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16022       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16023      isHorizontalBinOp(Op0, Op1, true))
16024    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16025
16026  return OptimizeConditionalInDecrement(N, DAG);
16027}
16028
16029SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16030                                             DAGCombinerInfo &DCI) const {
16031  SelectionDAG &DAG = DCI.DAG;
16032  switch (N->getOpcode()) {
16033  default: break;
16034  case ISD::EXTRACT_VECTOR_ELT:
16035    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16036  case ISD::VSELECT:
16037  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16038  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16039  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16040  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16041  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16042  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16043  case ISD::SHL:
16044  case ISD::SRA:
16045  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16046  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16047  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16048  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16049  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16050  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16051  case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16052  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16053  case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16054  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16055  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16056  case X86ISD::FXOR:
16057  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16058  case X86ISD::FMIN:
16059  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16060  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16061  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16062  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16063  case ISD::ANY_EXTEND:
16064  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16065  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16066  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16067  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16068  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16069  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16070  case X86ISD::SHUFP:       // Handle all target specific shuffles
16071  case X86ISD::PALIGN:
16072  case X86ISD::UNPCKH:
16073  case X86ISD::UNPCKL:
16074  case X86ISD::MOVHLPS:
16075  case X86ISD::MOVLHPS:
16076  case X86ISD::PSHUFD:
16077  case X86ISD::PSHUFHW:
16078  case X86ISD::PSHUFLW:
16079  case X86ISD::MOVSS:
16080  case X86ISD::MOVSD:
16081  case X86ISD::VPERMILP:
16082  case X86ISD::VPERM2X128:
16083  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16084  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16085  }
16086
16087  return SDValue();
16088}
16089
16090/// isTypeDesirableForOp - Return true if the target has native support for
16091/// the specified value type and it is 'desirable' to use the type for the
16092/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16093/// instruction encodings are longer and some i16 instructions are slow.
16094bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16095  if (!isTypeLegal(VT))
16096    return false;
16097  if (VT != MVT::i16)
16098    return true;
16099
16100  switch (Opc) {
16101  default:
16102    return true;
16103  case ISD::LOAD:
16104  case ISD::SIGN_EXTEND:
16105  case ISD::ZERO_EXTEND:
16106  case ISD::ANY_EXTEND:
16107  case ISD::SHL:
16108  case ISD::SRL:
16109  case ISD::SUB:
16110  case ISD::ADD:
16111  case ISD::MUL:
16112  case ISD::AND:
16113  case ISD::OR:
16114  case ISD::XOR:
16115    return false;
16116  }
16117}
16118
16119/// IsDesirableToPromoteOp - This method query the target whether it is
16120/// beneficial for dag combiner to promote the specified node. If true, it
16121/// should return the desired promotion type by reference.
16122bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16123  EVT VT = Op.getValueType();
16124  if (VT != MVT::i16)
16125    return false;
16126
16127  bool Promote = false;
16128  bool Commute = false;
16129  switch (Op.getOpcode()) {
16130  default: break;
16131  case ISD::LOAD: {
16132    LoadSDNode *LD = cast<LoadSDNode>(Op);
16133    // If the non-extending load has a single use and it's not live out, then it
16134    // might be folded.
16135    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16136                                                     Op.hasOneUse()*/) {
16137      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16138             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16139        // The only case where we'd want to promote LOAD (rather then it being
16140        // promoted as an operand is when it's only use is liveout.
16141        if (UI->getOpcode() != ISD::CopyToReg)
16142          return false;
16143      }
16144    }
16145    Promote = true;
16146    break;
16147  }
16148  case ISD::SIGN_EXTEND:
16149  case ISD::ZERO_EXTEND:
16150  case ISD::ANY_EXTEND:
16151    Promote = true;
16152    break;
16153  case ISD::SHL:
16154  case ISD::SRL: {
16155    SDValue N0 = Op.getOperand(0);
16156    // Look out for (store (shl (load), x)).
16157    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16158      return false;
16159    Promote = true;
16160    break;
16161  }
16162  case ISD::ADD:
16163  case ISD::MUL:
16164  case ISD::AND:
16165  case ISD::OR:
16166  case ISD::XOR:
16167    Commute = true;
16168    // fallthrough
16169  case ISD::SUB: {
16170    SDValue N0 = Op.getOperand(0);
16171    SDValue N1 = Op.getOperand(1);
16172    if (!Commute && MayFoldLoad(N1))
16173      return false;
16174    // Avoid disabling potential load folding opportunities.
16175    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16176      return false;
16177    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16178      return false;
16179    Promote = true;
16180  }
16181  }
16182
16183  PVT = MVT::i32;
16184  return Promote;
16185}
16186
16187//===----------------------------------------------------------------------===//
16188//                           X86 Inline Assembly Support
16189//===----------------------------------------------------------------------===//
16190
16191namespace {
16192  // Helper to match a string separated by whitespace.
16193  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16194    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16195
16196    for (unsigned i = 0, e = args.size(); i != e; ++i) {
16197      StringRef piece(*args[i]);
16198      if (!s.startswith(piece)) // Check if the piece matches.
16199        return false;
16200
16201      s = s.substr(piece.size());
16202      StringRef::size_type pos = s.find_first_not_of(" \t");
16203      if (pos == 0) // We matched a prefix.
16204        return false;
16205
16206      s = s.substr(pos);
16207    }
16208
16209    return s.empty();
16210  }
16211  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16212}
16213
16214bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16215  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16216
16217  std::string AsmStr = IA->getAsmString();
16218
16219  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16220  if (!Ty || Ty->getBitWidth() % 16 != 0)
16221    return false;
16222
16223  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16224  SmallVector<StringRef, 4> AsmPieces;
16225  SplitString(AsmStr, AsmPieces, ";\n");
16226
16227  switch (AsmPieces.size()) {
16228  default: return false;
16229  case 1:
16230    // FIXME: this should verify that we are targeting a 486 or better.  If not,
16231    // we will turn this bswap into something that will be lowered to logical
16232    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16233    // lower so don't worry about this.
16234    // bswap $0
16235    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16236        matchAsm(AsmPieces[0], "bswapl", "$0") ||
16237        matchAsm(AsmPieces[0], "bswapq", "$0") ||
16238        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16239        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16240        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16241      // No need to check constraints, nothing other than the equivalent of
16242      // "=r,0" would be valid here.
16243      return IntrinsicLowering::LowerToByteSwap(CI);
16244    }
16245
16246    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16247    if (CI->getType()->isIntegerTy(16) &&
16248        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16249        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16250         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16251      AsmPieces.clear();
16252      const std::string &ConstraintsStr = IA->getConstraintString();
16253      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16254      std::sort(AsmPieces.begin(), AsmPieces.end());
16255      if (AsmPieces.size() == 4 &&
16256          AsmPieces[0] == "~{cc}" &&
16257          AsmPieces[1] == "~{dirflag}" &&
16258          AsmPieces[2] == "~{flags}" &&
16259          AsmPieces[3] == "~{fpsr}")
16260      return IntrinsicLowering::LowerToByteSwap(CI);
16261    }
16262    break;
16263  case 3:
16264    if (CI->getType()->isIntegerTy(32) &&
16265        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16266        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16267        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16268        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16269      AsmPieces.clear();
16270      const std::string &ConstraintsStr = IA->getConstraintString();
16271      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16272      std::sort(AsmPieces.begin(), AsmPieces.end());
16273      if (AsmPieces.size() == 4 &&
16274          AsmPieces[0] == "~{cc}" &&
16275          AsmPieces[1] == "~{dirflag}" &&
16276          AsmPieces[2] == "~{flags}" &&
16277          AsmPieces[3] == "~{fpsr}")
16278        return IntrinsicLowering::LowerToByteSwap(CI);
16279    }
16280
16281    if (CI->getType()->isIntegerTy(64)) {
16282      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16283      if (Constraints.size() >= 2 &&
16284          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16285          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16286        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16287        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16288            matchAsm(AsmPieces[1], "bswap", "%edx") &&
16289            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16290          return IntrinsicLowering::LowerToByteSwap(CI);
16291      }
16292    }
16293    break;
16294  }
16295  return false;
16296}
16297
16298
16299
16300/// getConstraintType - Given a constraint letter, return the type of
16301/// constraint it is for this target.
16302X86TargetLowering::ConstraintType
16303X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16304  if (Constraint.size() == 1) {
16305    switch (Constraint[0]) {
16306    case 'R':
16307    case 'q':
16308    case 'Q':
16309    case 'f':
16310    case 't':
16311    case 'u':
16312    case 'y':
16313    case 'x':
16314    case 'Y':
16315    case 'l':
16316      return C_RegisterClass;
16317    case 'a':
16318    case 'b':
16319    case 'c':
16320    case 'd':
16321    case 'S':
16322    case 'D':
16323    case 'A':
16324      return C_Register;
16325    case 'I':
16326    case 'J':
16327    case 'K':
16328    case 'L':
16329    case 'M':
16330    case 'N':
16331    case 'G':
16332    case 'C':
16333    case 'e':
16334    case 'Z':
16335      return C_Other;
16336    default:
16337      break;
16338    }
16339  }
16340  return TargetLowering::getConstraintType(Constraint);
16341}
16342
16343/// Examine constraint type and operand type and determine a weight value.
16344/// This object must already have been set up with the operand type
16345/// and the current alternative constraint selected.
16346TargetLowering::ConstraintWeight
16347  X86TargetLowering::getSingleConstraintMatchWeight(
16348    AsmOperandInfo &info, const char *constraint) const {
16349  ConstraintWeight weight = CW_Invalid;
16350  Value *CallOperandVal = info.CallOperandVal;
16351    // If we don't have a value, we can't do a match,
16352    // but allow it at the lowest weight.
16353  if (CallOperandVal == NULL)
16354    return CW_Default;
16355  Type *type = CallOperandVal->getType();
16356  // Look at the constraint type.
16357  switch (*constraint) {
16358  default:
16359    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16360  case 'R':
16361  case 'q':
16362  case 'Q':
16363  case 'a':
16364  case 'b':
16365  case 'c':
16366  case 'd':
16367  case 'S':
16368  case 'D':
16369  case 'A':
16370    if (CallOperandVal->getType()->isIntegerTy())
16371      weight = CW_SpecificReg;
16372    break;
16373  case 'f':
16374  case 't':
16375  case 'u':
16376      if (type->isFloatingPointTy())
16377        weight = CW_SpecificReg;
16378      break;
16379  case 'y':
16380      if (type->isX86_MMXTy() && Subtarget->hasMMX())
16381        weight = CW_SpecificReg;
16382      break;
16383  case 'x':
16384  case 'Y':
16385    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16386        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16387      weight = CW_Register;
16388    break;
16389  case 'I':
16390    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16391      if (C->getZExtValue() <= 31)
16392        weight = CW_Constant;
16393    }
16394    break;
16395  case 'J':
16396    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16397      if (C->getZExtValue() <= 63)
16398        weight = CW_Constant;
16399    }
16400    break;
16401  case 'K':
16402    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16403      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16404        weight = CW_Constant;
16405    }
16406    break;
16407  case 'L':
16408    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16409      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16410        weight = CW_Constant;
16411    }
16412    break;
16413  case 'M':
16414    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16415      if (C->getZExtValue() <= 3)
16416        weight = CW_Constant;
16417    }
16418    break;
16419  case 'N':
16420    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16421      if (C->getZExtValue() <= 0xff)
16422        weight = CW_Constant;
16423    }
16424    break;
16425  case 'G':
16426  case 'C':
16427    if (dyn_cast<ConstantFP>(CallOperandVal)) {
16428      weight = CW_Constant;
16429    }
16430    break;
16431  case 'e':
16432    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16433      if ((C->getSExtValue() >= -0x80000000LL) &&
16434          (C->getSExtValue() <= 0x7fffffffLL))
16435        weight = CW_Constant;
16436    }
16437    break;
16438  case 'Z':
16439    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16440      if (C->getZExtValue() <= 0xffffffff)
16441        weight = CW_Constant;
16442    }
16443    break;
16444  }
16445  return weight;
16446}
16447
16448/// LowerXConstraint - try to replace an X constraint, which matches anything,
16449/// with another that has more specific requirements based on the type of the
16450/// corresponding operand.
16451const char *X86TargetLowering::
16452LowerXConstraint(EVT ConstraintVT) const {
16453  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16454  // 'f' like normal targets.
16455  if (ConstraintVT.isFloatingPoint()) {
16456    if (Subtarget->hasSSE2())
16457      return "Y";
16458    if (Subtarget->hasSSE1())
16459      return "x";
16460  }
16461
16462  return TargetLowering::LowerXConstraint(ConstraintVT);
16463}
16464
16465/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16466/// vector.  If it is invalid, don't add anything to Ops.
16467void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16468                                                     std::string &Constraint,
16469                                                     std::vector<SDValue>&Ops,
16470                                                     SelectionDAG &DAG) const {
16471  SDValue Result(0, 0);
16472
16473  // Only support length 1 constraints for now.
16474  if (Constraint.length() > 1) return;
16475
16476  char ConstraintLetter = Constraint[0];
16477  switch (ConstraintLetter) {
16478  default: break;
16479  case 'I':
16480    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16481      if (C->getZExtValue() <= 31) {
16482        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16483        break;
16484      }
16485    }
16486    return;
16487  case 'J':
16488    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16489      if (C->getZExtValue() <= 63) {
16490        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16491        break;
16492      }
16493    }
16494    return;
16495  case 'K':
16496    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16497      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16498        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16499        break;
16500      }
16501    }
16502    return;
16503  case 'N':
16504    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16505      if (C->getZExtValue() <= 255) {
16506        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16507        break;
16508      }
16509    }
16510    return;
16511  case 'e': {
16512    // 32-bit signed value
16513    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16514      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16515                                           C->getSExtValue())) {
16516        // Widen to 64 bits here to get it sign extended.
16517        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16518        break;
16519      }
16520    // FIXME gcc accepts some relocatable values here too, but only in certain
16521    // memory models; it's complicated.
16522    }
16523    return;
16524  }
16525  case 'Z': {
16526    // 32-bit unsigned value
16527    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16528      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16529                                           C->getZExtValue())) {
16530        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16531        break;
16532      }
16533    }
16534    // FIXME gcc accepts some relocatable values here too, but only in certain
16535    // memory models; it's complicated.
16536    return;
16537  }
16538  case 'i': {
16539    // Literal immediates are always ok.
16540    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16541      // Widen to 64 bits here to get it sign extended.
16542      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16543      break;
16544    }
16545
16546    // In any sort of PIC mode addresses need to be computed at runtime by
16547    // adding in a register or some sort of table lookup.  These can't
16548    // be used as immediates.
16549    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16550      return;
16551
16552    // If we are in non-pic codegen mode, we allow the address of a global (with
16553    // an optional displacement) to be used with 'i'.
16554    GlobalAddressSDNode *GA = 0;
16555    int64_t Offset = 0;
16556
16557    // Match either (GA), (GA+C), (GA+C1+C2), etc.
16558    while (1) {
16559      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16560        Offset += GA->getOffset();
16561        break;
16562      } else if (Op.getOpcode() == ISD::ADD) {
16563        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16564          Offset += C->getZExtValue();
16565          Op = Op.getOperand(0);
16566          continue;
16567        }
16568      } else if (Op.getOpcode() == ISD::SUB) {
16569        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16570          Offset += -C->getZExtValue();
16571          Op = Op.getOperand(0);
16572          continue;
16573        }
16574      }
16575
16576      // Otherwise, this isn't something we can handle, reject it.
16577      return;
16578    }
16579
16580    const GlobalValue *GV = GA->getGlobal();
16581    // If we require an extra load to get this address, as in PIC mode, we
16582    // can't accept it.
16583    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16584                                                        getTargetMachine())))
16585      return;
16586
16587    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16588                                        GA->getValueType(0), Offset);
16589    break;
16590  }
16591  }
16592
16593  if (Result.getNode()) {
16594    Ops.push_back(Result);
16595    return;
16596  }
16597  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16598}
16599
16600std::pair<unsigned, const TargetRegisterClass*>
16601X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16602                                                EVT VT) const {
16603  // First, see if this is a constraint that directly corresponds to an LLVM
16604  // register class.
16605  if (Constraint.size() == 1) {
16606    // GCC Constraint Letters
16607    switch (Constraint[0]) {
16608    default: break;
16609      // TODO: Slight differences here in allocation order and leaving
16610      // RIP in the class. Do they matter any more here than they do
16611      // in the normal allocation?
16612    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16613      if (Subtarget->is64Bit()) {
16614        if (VT == MVT::i32 || VT == MVT::f32)
16615          return std::make_pair(0U, &X86::GR32RegClass);
16616        if (VT == MVT::i16)
16617          return std::make_pair(0U, &X86::GR16RegClass);
16618        if (VT == MVT::i8 || VT == MVT::i1)
16619          return std::make_pair(0U, &X86::GR8RegClass);
16620        if (VT == MVT::i64 || VT == MVT::f64)
16621          return std::make_pair(0U, &X86::GR64RegClass);
16622        break;
16623      }
16624      // 32-bit fallthrough
16625    case 'Q':   // Q_REGS
16626      if (VT == MVT::i32 || VT == MVT::f32)
16627        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16628      if (VT == MVT::i16)
16629        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16630      if (VT == MVT::i8 || VT == MVT::i1)
16631        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16632      if (VT == MVT::i64)
16633        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16634      break;
16635    case 'r':   // GENERAL_REGS
16636    case 'l':   // INDEX_REGS
16637      if (VT == MVT::i8 || VT == MVT::i1)
16638        return std::make_pair(0U, &X86::GR8RegClass);
16639      if (VT == MVT::i16)
16640        return std::make_pair(0U, &X86::GR16RegClass);
16641      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16642        return std::make_pair(0U, &X86::GR32RegClass);
16643      return std::make_pair(0U, &X86::GR64RegClass);
16644    case 'R':   // LEGACY_REGS
16645      if (VT == MVT::i8 || VT == MVT::i1)
16646        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16647      if (VT == MVT::i16)
16648        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16649      if (VT == MVT::i32 || !Subtarget->is64Bit())
16650        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16651      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16652    case 'f':  // FP Stack registers.
16653      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16654      // value to the correct fpstack register class.
16655      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16656        return std::make_pair(0U, &X86::RFP32RegClass);
16657      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16658        return std::make_pair(0U, &X86::RFP64RegClass);
16659      return std::make_pair(0U, &X86::RFP80RegClass);
16660    case 'y':   // MMX_REGS if MMX allowed.
16661      if (!Subtarget->hasMMX()) break;
16662      return std::make_pair(0U, &X86::VR64RegClass);
16663    case 'Y':   // SSE_REGS if SSE2 allowed
16664      if (!Subtarget->hasSSE2()) break;
16665      // FALL THROUGH.
16666    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16667      if (!Subtarget->hasSSE1()) break;
16668
16669      switch (VT.getSimpleVT().SimpleTy) {
16670      default: break;
16671      // Scalar SSE types.
16672      case MVT::f32:
16673      case MVT::i32:
16674        return std::make_pair(0U, &X86::FR32RegClass);
16675      case MVT::f64:
16676      case MVT::i64:
16677        return std::make_pair(0U, &X86::FR64RegClass);
16678      // Vector types.
16679      case MVT::v16i8:
16680      case MVT::v8i16:
16681      case MVT::v4i32:
16682      case MVT::v2i64:
16683      case MVT::v4f32:
16684      case MVT::v2f64:
16685        return std::make_pair(0U, &X86::VR128RegClass);
16686      // AVX types.
16687      case MVT::v32i8:
16688      case MVT::v16i16:
16689      case MVT::v8i32:
16690      case MVT::v4i64:
16691      case MVT::v8f32:
16692      case MVT::v4f64:
16693        return std::make_pair(0U, &X86::VR256RegClass);
16694      }
16695      break;
16696    }
16697  }
16698
16699  // Use the default implementation in TargetLowering to convert the register
16700  // constraint into a member of a register class.
16701  std::pair<unsigned, const TargetRegisterClass*> Res;
16702  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16703
16704  // Not found as a standard register?
16705  if (Res.second == 0) {
16706    // Map st(0) -> st(7) -> ST0
16707    if (Constraint.size() == 7 && Constraint[0] == '{' &&
16708        tolower(Constraint[1]) == 's' &&
16709        tolower(Constraint[2]) == 't' &&
16710        Constraint[3] == '(' &&
16711        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16712        Constraint[5] == ')' &&
16713        Constraint[6] == '}') {
16714
16715      Res.first = X86::ST0+Constraint[4]-'0';
16716      Res.second = &X86::RFP80RegClass;
16717      return Res;
16718    }
16719
16720    // GCC allows "st(0)" to be called just plain "st".
16721    if (StringRef("{st}").equals_lower(Constraint)) {
16722      Res.first = X86::ST0;
16723      Res.second = &X86::RFP80RegClass;
16724      return Res;
16725    }
16726
16727    // flags -> EFLAGS
16728    if (StringRef("{flags}").equals_lower(Constraint)) {
16729      Res.first = X86::EFLAGS;
16730      Res.second = &X86::CCRRegClass;
16731      return Res;
16732    }
16733
16734    // 'A' means EAX + EDX.
16735    if (Constraint == "A") {
16736      Res.first = X86::EAX;
16737      Res.second = &X86::GR32_ADRegClass;
16738      return Res;
16739    }
16740    return Res;
16741  }
16742
16743  // Otherwise, check to see if this is a register class of the wrong value
16744  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16745  // turn into {ax},{dx}.
16746  if (Res.second->hasType(VT))
16747    return Res;   // Correct type already, nothing to do.
16748
16749  // All of the single-register GCC register classes map their values onto
16750  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16751  // really want an 8-bit or 32-bit register, map to the appropriate register
16752  // class and return the appropriate register.
16753  if (Res.second == &X86::GR16RegClass) {
16754    if (VT == MVT::i8) {
16755      unsigned DestReg = 0;
16756      switch (Res.first) {
16757      default: break;
16758      case X86::AX: DestReg = X86::AL; break;
16759      case X86::DX: DestReg = X86::DL; break;
16760      case X86::CX: DestReg = X86::CL; break;
16761      case X86::BX: DestReg = X86::BL; break;
16762      }
16763      if (DestReg) {
16764        Res.first = DestReg;
16765        Res.second = &X86::GR8RegClass;
16766      }
16767    } else if (VT == MVT::i32) {
16768      unsigned DestReg = 0;
16769      switch (Res.first) {
16770      default: break;
16771      case X86::AX: DestReg = X86::EAX; break;
16772      case X86::DX: DestReg = X86::EDX; break;
16773      case X86::CX: DestReg = X86::ECX; break;
16774      case X86::BX: DestReg = X86::EBX; break;
16775      case X86::SI: DestReg = X86::ESI; break;
16776      case X86::DI: DestReg = X86::EDI; break;
16777      case X86::BP: DestReg = X86::EBP; break;
16778      case X86::SP: DestReg = X86::ESP; break;
16779      }
16780      if (DestReg) {
16781        Res.first = DestReg;
16782        Res.second = &X86::GR32RegClass;
16783      }
16784    } else if (VT == MVT::i64) {
16785      unsigned DestReg = 0;
16786      switch (Res.first) {
16787      default: break;
16788      case X86::AX: DestReg = X86::RAX; break;
16789      case X86::DX: DestReg = X86::RDX; break;
16790      case X86::CX: DestReg = X86::RCX; break;
16791      case X86::BX: DestReg = X86::RBX; break;
16792      case X86::SI: DestReg = X86::RSI; break;
16793      case X86::DI: DestReg = X86::RDI; break;
16794      case X86::BP: DestReg = X86::RBP; break;
16795      case X86::SP: DestReg = X86::RSP; break;
16796      }
16797      if (DestReg) {
16798        Res.first = DestReg;
16799        Res.second = &X86::GR64RegClass;
16800      }
16801    }
16802  } else if (Res.second == &X86::FR32RegClass ||
16803             Res.second == &X86::FR64RegClass ||
16804             Res.second == &X86::VR128RegClass) {
16805    // Handle references to XMM physical registers that got mapped into the
16806    // wrong class.  This can happen with constraints like {xmm0} where the
16807    // target independent register mapper will just pick the first match it can
16808    // find, ignoring the required type.
16809
16810    if (VT == MVT::f32 || VT == MVT::i32)
16811      Res.second = &X86::FR32RegClass;
16812    else if (VT == MVT::f64 || VT == MVT::i64)
16813      Res.second = &X86::FR64RegClass;
16814    else if (X86::VR128RegClass.hasType(VT))
16815      Res.second = &X86::VR128RegClass;
16816    else if (X86::VR256RegClass.hasType(VT))
16817      Res.second = &X86::VR256RegClass;
16818  }
16819
16820  return Res;
16821}
16822