X86ISelLowering.cpp revision c26392aa5d9c2dbca2909d6874d181455f8aeb8f
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86ISelLowering.h"
17#include "Utils/X86ShuffleDecode.h"
18#include "X86.h"
19#include "X86InstrBuilder.h"
20#include "X86TargetMachine.h"
21#include "X86TargetObjectFile.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/VariadicFunction.h"
26#include "llvm/CodeGen/IntrinsicLowering.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineJumpTableInfo.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/IR/CallingConv.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/MC/MCAsmInfo.h"
43#include "llvm/MC/MCContext.h"
44#include "llvm/MC/MCExpr.h"
45#include "llvm/MC/MCSymbol.h"
46#include "llvm/Support/CallSite.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/Target/TargetOptions.h"
51#include <bitset>
52#include <cctype>
53using namespace llvm;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56
57// Forward declarations.
58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                       SDValue V2);
60
61/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62/// sets things up to match to an AVX VEXTRACTF128 instruction or a
63/// simple subregister reference.  Idx is an index in the 128 bits we
64/// want.  It need not be aligned to a 128-bit bounday.  That makes
65/// lowering EXTRACT_VECTOR_ELT operations easier.
66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                   SelectionDAG &DAG, DebugLoc dl) {
68  EVT VT = Vec.getValueType();
69  assert(VT.is256BitVector() && "Unexpected vector size!");
70  EVT ElVT = VT.getVectorElementType();
71  unsigned Factor = VT.getSizeInBits()/128;
72  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                  VT.getVectorNumElements()/Factor);
74
75  // Extract from UNDEF is UNDEF.
76  if (Vec.getOpcode() == ISD::UNDEF)
77    return DAG.getUNDEF(ResultVT);
78
79  // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80  // we can match to VEXTRACTF128.
81  unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83  // This is the index of the first element of the 128-bit chunk
84  // we want.
85  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                               * ElemsPerChunk);
87
88  // If the input is a buildvector just emit a smaller one.
89  if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90    return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91                       Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
92
93  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94  SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95                               VecIdx);
96
97  return Result;
98}
99
100/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
101/// sets things up to match to an AVX VINSERTF128 instruction or a
102/// simple superregister reference.  Idx is an index in the 128 bits
103/// we want.  It need not be aligned to a 128-bit bounday.  That makes
104/// lowering INSERT_VECTOR_ELT operations easier.
105static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106                                  unsigned IdxVal, SelectionDAG &DAG,
107                                  DebugLoc dl) {
108  // Inserting UNDEF is Result
109  if (Vec.getOpcode() == ISD::UNDEF)
110    return Result;
111
112  EVT VT = Vec.getValueType();
113  assert(VT.is128BitVector() && "Unexpected vector size!");
114
115  EVT ElVT = VT.getVectorElementType();
116  EVT ResultVT = Result.getValueType();
117
118  // Insert the relevant 128 bits.
119  unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
120
121  // This is the index of the first element of the 128-bit chunk
122  // we want.
123  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
124                               * ElemsPerChunk);
125
126  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127  return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
128                     VecIdx);
129}
130
131/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132/// instructions. This is used because creating CONCAT_VECTOR nodes of
133/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134/// large BUILD_VECTORS.
135static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136                                   unsigned NumElems, SelectionDAG &DAG,
137                                   DebugLoc dl) {
138  SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139  return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
140}
141
142static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144  bool is64Bit = Subtarget->is64Bit();
145
146  if (Subtarget->isTargetEnvMacho()) {
147    if (is64Bit)
148      return new X86_64MachoTargetObjectFile();
149    return new TargetLoweringObjectFileMachO();
150  }
151
152  if (Subtarget->isTargetLinux())
153    return new X86LinuxTargetObjectFile();
154  if (Subtarget->isTargetELF())
155    return new TargetLoweringObjectFileELF();
156  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157    return new TargetLoweringObjectFileCOFF();
158  llvm_unreachable("unknown subtarget type");
159}
160
161X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162  : TargetLowering(TM, createTLOF(TM)) {
163  Subtarget = &TM.getSubtarget<X86Subtarget>();
164  X86ScalarSSEf64 = Subtarget->hasSSE2();
165  X86ScalarSSEf32 = Subtarget->hasSSE1();
166
167  RegInfo = TM.getRegisterInfo();
168  TD = getDataLayout();
169
170  // Set up the TargetLowering object.
171  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
172
173  // X86 is weird, it always uses i8 for shift amounts and setcc results.
174  setBooleanContents(ZeroOrOneBooleanContent);
175  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
176  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177
178  // For 64-bit since we have so many registers use the ILP scheduler, for
179  // 32-bit code use the register pressure specific scheduling.
180  // For Atom, always use ILP scheduling.
181  if (Subtarget->isAtom())
182    setSchedulingPreference(Sched::ILP);
183  else if (Subtarget->is64Bit())
184    setSchedulingPreference(Sched::ILP);
185  else
186    setSchedulingPreference(Sched::RegPressure);
187  setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
188
189  // Bypass expensive divides on Atom when compiling with O2
190  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
191    addBypassSlowDiv(32, 8);
192    if (Subtarget->is64Bit())
193      addBypassSlowDiv(64, 16);
194  }
195
196  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
197    // Setup Windows compiler runtime calls.
198    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
199    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
200    setLibcallName(RTLIB::SREM_I64, "_allrem");
201    setLibcallName(RTLIB::UREM_I64, "_aullrem");
202    setLibcallName(RTLIB::MUL_I64, "_allmul");
203    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208
209    // The _ftol2 runtime function has an unusual calling conv, which
210    // is modeled by a special pseudo-instruction.
211    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
212    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
213    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
214    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
215  }
216
217  if (Subtarget->isTargetDarwin()) {
218    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
219    setUseUnderscoreSetJmp(false);
220    setUseUnderscoreLongJmp(false);
221  } else if (Subtarget->isTargetMingw()) {
222    // MS runtime is weird: it exports _setjmp, but longjmp!
223    setUseUnderscoreSetJmp(true);
224    setUseUnderscoreLongJmp(false);
225  } else {
226    setUseUnderscoreSetJmp(true);
227    setUseUnderscoreLongJmp(true);
228  }
229
230  // Set up the register classes.
231  addRegisterClass(MVT::i8, &X86::GR8RegClass);
232  addRegisterClass(MVT::i16, &X86::GR16RegClass);
233  addRegisterClass(MVT::i32, &X86::GR32RegClass);
234  if (Subtarget->is64Bit())
235    addRegisterClass(MVT::i64, &X86::GR64RegClass);
236
237  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
238
239  // We don't accept any truncstore of integer registers.
240  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
241  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
242  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
243  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
244  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
245  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
246
247  // SETOEQ and SETUNE require checking two conditions.
248  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
249  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
250  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
251  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
252  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
253  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
254
255  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
256  // operation.
257  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
258  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
259  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
260
261  if (Subtarget->is64Bit()) {
262    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
263    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264  } else if (!TM.Options.UseSoftFloat) {
265    // We have an algorithm for SSE2->double, and we turn this into a
266    // 64-bit FILD followed by conditional FADD for other targets.
267    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
268    // We have an algorithm for SSE2, and we turn this into a 64-bit
269    // FILD for other targets.
270    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
271  }
272
273  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
274  // this operation.
275  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
276  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
277
278  if (!TM.Options.UseSoftFloat) {
279    // SSE has no i16 to fp conversion, only i32
280    if (X86ScalarSSEf32) {
281      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282      // f32 and f64 cases are Legal, f80 case is not
283      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
284    } else {
285      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
286      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
287    }
288  } else {
289    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
290    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
291  }
292
293  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
294  // are Legal, f80 is custom lowered.
295  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
296  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
297
298  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
299  // this operation.
300  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
301  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
302
303  if (X86ScalarSSEf32) {
304    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
305    // f32 and f64 cases are Legal, f80 case is not
306    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
307  } else {
308    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
309    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
310  }
311
312  // Handle FP_TO_UINT by promoting the destination to a larger signed
313  // conversion.
314  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
315  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
316  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
317
318  if (Subtarget->is64Bit()) {
319    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
320    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
321  } else if (!TM.Options.UseSoftFloat) {
322    // Since AVX is a superset of SSE3, only check for SSE here.
323    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
324      // Expand FP_TO_UINT into a select.
325      // FIXME: We would like to use a Custom expander here eventually to do
326      // the optimal thing for SSE vs. the default expansion in the legalizer.
327      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
328    else
329      // With SSE3 we can use fisttpll to convert to a signed i64; without
330      // SSE, we're stuck with a fistpll.
331      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
332  }
333
334  if (isTargetFTOL()) {
335    // Use the _ftol2 runtime function, which has a pseudo-instruction
336    // to handle its weird calling convention.
337    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
338  }
339
340  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
341  if (!X86ScalarSSEf64) {
342    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
343    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
344    if (Subtarget->is64Bit()) {
345      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
346      // Without SSE, i64->f64 goes through memory.
347      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
348    }
349  }
350
351  // Scalar integer divide and remainder are lowered to use operations that
352  // produce two results, to match the available instructions. This exposes
353  // the two-result form to trivial CSE, which is able to combine x/y and x%y
354  // into a single instruction.
355  //
356  // Scalar integer multiply-high is also lowered to use two-result
357  // operations, to match the available instructions. However, plain multiply
358  // (low) operations are left as Legal, as there are single-result
359  // instructions for this in x86. Using the two-result multiply instructions
360  // when both high and low results are needed must be arranged by dagcombine.
361  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
362    MVT VT = IntVTs[i];
363    setOperationAction(ISD::MULHS, VT, Expand);
364    setOperationAction(ISD::MULHU, VT, Expand);
365    setOperationAction(ISD::SDIV, VT, Expand);
366    setOperationAction(ISD::UDIV, VT, Expand);
367    setOperationAction(ISD::SREM, VT, Expand);
368    setOperationAction(ISD::UREM, VT, Expand);
369
370    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
371    setOperationAction(ISD::ADDC, VT, Custom);
372    setOperationAction(ISD::ADDE, VT, Custom);
373    setOperationAction(ISD::SUBC, VT, Custom);
374    setOperationAction(ISD::SUBE, VT, Custom);
375  }
376
377  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
378  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
379  setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
380  setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
381  setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
382  setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
383  setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
384  setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
385  setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
386  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
387  if (Subtarget->is64Bit())
388    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
389  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
390  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
391  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
392  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
393  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
394  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
395  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
396  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
397
398  // Promote the i8 variants and force them on up to i32 which has a shorter
399  // encoding.
400  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
401  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
402  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
403  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
404  if (Subtarget->hasBMI()) {
405    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
406    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
407    if (Subtarget->is64Bit())
408      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
409  } else {
410    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
411    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
412    if (Subtarget->is64Bit())
413      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
414  }
415
416  if (Subtarget->hasLZCNT()) {
417    // When promoting the i8 variants, force them to i32 for a shorter
418    // encoding.
419    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
420    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
421    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
422    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
423    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
424    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
425    if (Subtarget->is64Bit())
426      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
427  } else {
428    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
429    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
430    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
431    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
432    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
433    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
434    if (Subtarget->is64Bit()) {
435      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
436      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
437    }
438  }
439
440  if (Subtarget->hasPOPCNT()) {
441    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
442  } else {
443    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
444    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
445    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
446    if (Subtarget->is64Bit())
447      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
448  }
449
450  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
451  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
452
453  // These should be promoted to a larger select which is supported.
454  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
455  // X86 wants to expand cmov itself.
456  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
457  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
458  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
459  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
460  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
461  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
462  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
463  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
464  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
465  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
466  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
467  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
468  if (Subtarget->is64Bit()) {
469    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
470    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
471  }
472  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
473  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
474  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
475  // support continuation, user-level threading, and etc.. As a result, no
476  // other SjLj exception interfaces are implemented and please don't build
477  // your own exception handling based on them.
478  // LLVM/Clang supports zero-cost DWARF exception handling.
479  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
480  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
481
482  // Darwin ABI issue.
483  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
484  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
485  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
486  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
487  if (Subtarget->is64Bit())
488    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
489  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
490  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
491  if (Subtarget->is64Bit()) {
492    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
493    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
494    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
495    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
496    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
497  }
498  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
499  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
500  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
501  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
502  if (Subtarget->is64Bit()) {
503    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
504    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
505    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
506  }
507
508  if (Subtarget->hasSSE1())
509    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
510
511  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
512  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
513
514  // On X86 and X86-64, atomic operations are lowered to locked instructions.
515  // Locked instructions, in turn, have implicit fence semantics (all memory
516  // operations are flushed before issuing the locked instruction, and they
517  // are not buffered), so we can fold away the common pattern of
518  // fence-atomic-fence.
519  setShouldFoldAtomicFences(true);
520
521  // Expand certain atomics
522  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
523    MVT VT = IntVTs[i];
524    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
525    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
526    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
527  }
528
529  if (!Subtarget->is64Bit()) {
530    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
531    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
532    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
533    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
534    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
535    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
536    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
537    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
538    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
539    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
540    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
541    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
542  }
543
544  if (Subtarget->hasCmpxchg16b()) {
545    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
546  }
547
548  // FIXME - use subtarget debug flags
549  if (!Subtarget->isTargetDarwin() &&
550      !Subtarget->isTargetELF() &&
551      !Subtarget->isTargetCygMing()) {
552    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
553  }
554
555  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
556  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
557  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
558  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
559  if (Subtarget->is64Bit()) {
560    setExceptionPointerRegister(X86::RAX);
561    setExceptionSelectorRegister(X86::RDX);
562  } else {
563    setExceptionPointerRegister(X86::EAX);
564    setExceptionSelectorRegister(X86::EDX);
565  }
566  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
567  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
568
569  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
570  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
571
572  setOperationAction(ISD::TRAP, MVT::Other, Legal);
573  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
574
575  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
576  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
577  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
578  if (Subtarget->is64Bit()) {
579    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
580    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
581  } else {
582    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
583    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
584  }
585
586  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
587  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
588
589  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
590    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
591                       MVT::i64 : MVT::i32, Custom);
592  else if (TM.Options.EnableSegmentedStacks)
593    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
594                       MVT::i64 : MVT::i32, Custom);
595  else
596    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
597                       MVT::i64 : MVT::i32, Expand);
598
599  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
600    // f32 and f64 use SSE.
601    // Set up the FP register classes.
602    addRegisterClass(MVT::f32, &X86::FR32RegClass);
603    addRegisterClass(MVT::f64, &X86::FR64RegClass);
604
605    // Use ANDPD to simulate FABS.
606    setOperationAction(ISD::FABS , MVT::f64, Custom);
607    setOperationAction(ISD::FABS , MVT::f32, Custom);
608
609    // Use XORP to simulate FNEG.
610    setOperationAction(ISD::FNEG , MVT::f64, Custom);
611    setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613    // Use ANDPD and ORPD to simulate FCOPYSIGN.
614    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
615    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
616
617    // Lower this to FGETSIGNx86 plus an AND.
618    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
619    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
620
621    // We don't support sin/cos/fmod
622    setOperationAction(ISD::FSIN   , MVT::f64, Expand);
623    setOperationAction(ISD::FCOS   , MVT::f64, Expand);
624    setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
625    setOperationAction(ISD::FSIN   , MVT::f32, Expand);
626    setOperationAction(ISD::FCOS   , MVT::f32, Expand);
627    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
628
629    // Expand FP immediates into loads from the stack, except for the special
630    // cases we handle.
631    addLegalFPImmediate(APFloat(+0.0)); // xorpd
632    addLegalFPImmediate(APFloat(+0.0f)); // xorps
633  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
634    // Use SSE for f32, x87 for f64.
635    // Set up the FP register classes.
636    addRegisterClass(MVT::f32, &X86::FR32RegClass);
637    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638
639    // Use ANDPS to simulate FABS.
640    setOperationAction(ISD::FABS , MVT::f32, Custom);
641
642    // Use XORP to simulate FNEG.
643    setOperationAction(ISD::FNEG , MVT::f32, Custom);
644
645    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
646
647    // Use ANDPS and ORPS to simulate FCOPYSIGN.
648    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
649    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
650
651    // We don't support sin/cos/fmod
652    setOperationAction(ISD::FSIN   , MVT::f32, Expand);
653    setOperationAction(ISD::FCOS   , MVT::f32, Expand);
654    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
655
656    // Special cases we handle for FP constants.
657    addLegalFPImmediate(APFloat(+0.0f)); // xorps
658    addLegalFPImmediate(APFloat(+0.0)); // FLD0
659    addLegalFPImmediate(APFloat(+1.0)); // FLD1
660    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
661    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
662
663    if (!TM.Options.UnsafeFPMath) {
664      setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665      setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666      setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667    }
668  } else if (!TM.Options.UseSoftFloat) {
669    // f32 and f64 in x87.
670    // Set up the FP register classes.
671    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
672    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
673
674    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
675    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
676    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
677    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
678
679    if (!TM.Options.UnsafeFPMath) {
680      setOperationAction(ISD::FSIN   , MVT::f64, Expand);
681      setOperationAction(ISD::FSIN   , MVT::f32, Expand);
682      setOperationAction(ISD::FCOS   , MVT::f64, Expand);
683      setOperationAction(ISD::FCOS   , MVT::f32, Expand);
684      setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
685      setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
686    }
687    addLegalFPImmediate(APFloat(+0.0)); // FLD0
688    addLegalFPImmediate(APFloat(+1.0)); // FLD1
689    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
691    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
692    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
693    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
694    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
695  }
696
697  // We don't support FMA.
698  setOperationAction(ISD::FMA, MVT::f64, Expand);
699  setOperationAction(ISD::FMA, MVT::f32, Expand);
700
701  // Long double always uses X87.
702  if (!TM.Options.UseSoftFloat) {
703    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
704    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
705    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
706    {
707      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
708      addLegalFPImmediate(TmpFlt);  // FLD0
709      TmpFlt.changeSign();
710      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
711
712      bool ignored;
713      APFloat TmpFlt2(+1.0);
714      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
715                      &ignored);
716      addLegalFPImmediate(TmpFlt2);  // FLD1
717      TmpFlt2.changeSign();
718      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
719    }
720
721    if (!TM.Options.UnsafeFPMath) {
722      setOperationAction(ISD::FSIN   , MVT::f80, Expand);
723      setOperationAction(ISD::FCOS   , MVT::f80, Expand);
724      setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
725    }
726
727    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
728    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
729    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
730    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
731    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
732    setOperationAction(ISD::FMA, MVT::f80, Expand);
733  }
734
735  // Always use a library call for pow.
736  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
737  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
738  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
739
740  setOperationAction(ISD::FLOG, MVT::f80, Expand);
741  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
742  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
743  setOperationAction(ISD::FEXP, MVT::f80, Expand);
744  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
745
746  // First set operation action for all vector types to either promote
747  // (for widening) or expand (for scalarization). Then we will selectively
748  // turn on ones that can be effectively codegen'd.
749  for (int i = MVT::FIRST_VECTOR_VALUETYPE;
750           i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
751    MVT VT = (MVT::SimpleValueType)i;
752    setOperationAction(ISD::ADD , VT, Expand);
753    setOperationAction(ISD::SUB , VT, Expand);
754    setOperationAction(ISD::FADD, VT, Expand);
755    setOperationAction(ISD::FNEG, VT, Expand);
756    setOperationAction(ISD::FSUB, VT, Expand);
757    setOperationAction(ISD::MUL , VT, Expand);
758    setOperationAction(ISD::FMUL, VT, Expand);
759    setOperationAction(ISD::SDIV, VT, Expand);
760    setOperationAction(ISD::UDIV, VT, Expand);
761    setOperationAction(ISD::FDIV, VT, Expand);
762    setOperationAction(ISD::SREM, VT, Expand);
763    setOperationAction(ISD::UREM, VT, Expand);
764    setOperationAction(ISD::LOAD, VT, Expand);
765    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
766    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
767    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
768    setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
769    setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
770    setOperationAction(ISD::FABS, VT, Expand);
771    setOperationAction(ISD::FSIN, VT, Expand);
772    setOperationAction(ISD::FSINCOS, VT, Expand);
773    setOperationAction(ISD::FCOS, VT, Expand);
774    setOperationAction(ISD::FSINCOS, VT, Expand);
775    setOperationAction(ISD::FREM, VT, Expand);
776    setOperationAction(ISD::FMA,  VT, Expand);
777    setOperationAction(ISD::FPOWI, VT, Expand);
778    setOperationAction(ISD::FSQRT, VT, Expand);
779    setOperationAction(ISD::FCOPYSIGN, VT, Expand);
780    setOperationAction(ISD::FFLOOR, VT, Expand);
781    setOperationAction(ISD::FCEIL, VT, Expand);
782    setOperationAction(ISD::FTRUNC, VT, Expand);
783    setOperationAction(ISD::FRINT, VT, Expand);
784    setOperationAction(ISD::FNEARBYINT, VT, Expand);
785    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
786    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
787    setOperationAction(ISD::SDIVREM, VT, Expand);
788    setOperationAction(ISD::UDIVREM, VT, Expand);
789    setOperationAction(ISD::FPOW, VT, Expand);
790    setOperationAction(ISD::CTPOP, VT, Expand);
791    setOperationAction(ISD::CTTZ, VT, Expand);
792    setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
793    setOperationAction(ISD::CTLZ, VT, Expand);
794    setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
795    setOperationAction(ISD::SHL, VT, Expand);
796    setOperationAction(ISD::SRA, VT, Expand);
797    setOperationAction(ISD::SRL, VT, Expand);
798    setOperationAction(ISD::ROTL, VT, Expand);
799    setOperationAction(ISD::ROTR, VT, Expand);
800    setOperationAction(ISD::BSWAP, VT, Expand);
801    setOperationAction(ISD::SETCC, VT, Expand);
802    setOperationAction(ISD::FLOG, VT, Expand);
803    setOperationAction(ISD::FLOG2, VT, Expand);
804    setOperationAction(ISD::FLOG10, VT, Expand);
805    setOperationAction(ISD::FEXP, VT, Expand);
806    setOperationAction(ISD::FEXP2, VT, Expand);
807    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
808    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
809    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
810    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
811    setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
812    setOperationAction(ISD::TRUNCATE, VT, Expand);
813    setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
814    setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
815    setOperationAction(ISD::ANY_EXTEND, VT, Expand);
816    setOperationAction(ISD::VSELECT, VT, Expand);
817    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
818             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
819      setTruncStoreAction(VT,
820                          (MVT::SimpleValueType)InnerVT, Expand);
821    setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
822    setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
823    setLoadExtAction(ISD::EXTLOAD, VT, Expand);
824  }
825
826  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
827  // with -msoft-float, disable use of MMX as well.
828  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
829    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
830    // No operations on x86mmx supported, everything uses intrinsics.
831  }
832
833  // MMX-sized vectors (other than x86mmx) are expected to be expanded
834  // into smaller operations.
835  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
836  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
837  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
838  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
839  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
840  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
841  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
842  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
843  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
844  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
845  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
846  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
847  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
848  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
849  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
850  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
851  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
852  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
853  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
854  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
855  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
856  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
857  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
858  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
859  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
860  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
861  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
862  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
863  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
864
865  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
866    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
867
868    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
869    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
870    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
871    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
872    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
873    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
874    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
875    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
876    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
877    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
878    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
879    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
880  }
881
882  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
883    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
884
885    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
886    // registers cannot be used even for integer operations.
887    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
888    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
889    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
890    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
891
892    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
893    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
894    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
895    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
896    setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
897    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
898    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
899    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
900    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
901    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
902    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
903    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
904    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
905    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
906    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
907    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
908    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
909    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
910
911    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
912    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
913    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
914    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
915
916    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
917    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
918    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
919    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
920    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
921
922    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
923    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
924      MVT VT = (MVT::SimpleValueType)i;
925      // Do not attempt to custom lower non-power-of-2 vectors
926      if (!isPowerOf2_32(VT.getVectorNumElements()))
927        continue;
928      // Do not attempt to custom lower non-128-bit vectors
929      if (!VT.is128BitVector())
930        continue;
931      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
932      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
933      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
934    }
935
936    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
937    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
938    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
939    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
940    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
941    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
942
943    if (Subtarget->is64Bit()) {
944      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
945      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
946    }
947
948    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
949    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
950      MVT VT = (MVT::SimpleValueType)i;
951
952      // Do not attempt to promote non-128-bit vectors
953      if (!VT.is128BitVector())
954        continue;
955
956      setOperationAction(ISD::AND,    VT, Promote);
957      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
958      setOperationAction(ISD::OR,     VT, Promote);
959      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
960      setOperationAction(ISD::XOR,    VT, Promote);
961      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
962      setOperationAction(ISD::LOAD,   VT, Promote);
963      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
964      setOperationAction(ISD::SELECT, VT, Promote);
965      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
966    }
967
968    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
969
970    // Custom lower v2i64 and v2f64 selects.
971    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
972    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
973    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
974    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
975
976    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
977    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
978
979    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
980    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
981    // As there is no 64-bit GPR available, we need build a special custom
982    // sequence to convert from v2i32 to v2f32.
983    if (!Subtarget->is64Bit())
984      setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
985
986    setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
987    setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
988
989    setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
990  }
991
992  if (Subtarget->hasSSE41()) {
993    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
994    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
995    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
996    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
997    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
998    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
999    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1000    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1001    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1002    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1003
1004    setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1005    setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1006    setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1007    setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1008    setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1009    setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1010    setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1011    setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1012    setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1013    setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1014
1015    // FIXME: Do we need to handle scalar-to-vector here?
1016    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1017
1018    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1019    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1020    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1021    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1022    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1023
1024    // i8 and i16 vectors are custom , because the source register and source
1025    // source memory operand types are not the same width.  f32 vectors are
1026    // custom since the immediate controlling the insert encodes additional
1027    // information.
1028    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1029    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1030    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1031    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1032
1033    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1034    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1035    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1036    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1037
1038    // FIXME: these should be Legal but thats only for the case where
1039    // the index is constant.  For now custom expand to deal with that.
1040    if (Subtarget->is64Bit()) {
1041      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1042      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1043    }
1044  }
1045
1046  if (Subtarget->hasSSE2()) {
1047    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1048    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1049
1050    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1051    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1052
1053    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1054    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1055
1056    // In the customized shift lowering, the legal cases in AVX2 will be
1057    // recognized.
1058    setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1059    setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1060
1061    setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1062    setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1063
1064    setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1065
1066    setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1067    setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1068  }
1069
1070  if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1071    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1072    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1073    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1074    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1075    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1076    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1077
1078    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1079    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1080    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1081
1082    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1083    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1084    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1085    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1086    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1087    setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1088    setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1089    setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1090    setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1091    setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1092    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1093    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1094
1095    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1096    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1097    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1098    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1099    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1100    setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1101    setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1102    setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1103    setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1104    setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1105    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1106    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1107
1108    setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1109    setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1110
1111    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1112
1113    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1114    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1115    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1116
1117    setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1118    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1119    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1120
1121    setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1122
1123    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1124    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1125
1126    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1127    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1128
1129    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1130    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1131
1132    setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1133
1134    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1135    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1136    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1137    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1138
1139    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1140    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1141    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1142
1143    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1144    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1145    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1146    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1147
1148    setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1149    setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1150    setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1151    setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1152    setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1153    setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1154
1155    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1156      setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1157      setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1158      setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1159      setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1160      setOperationAction(ISD::FMA,             MVT::f32, Legal);
1161      setOperationAction(ISD::FMA,             MVT::f64, Legal);
1162    }
1163
1164    if (Subtarget->hasInt256()) {
1165      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1166      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1167      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1168      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1169
1170      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1171      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1172      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1173      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1174
1175      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1176      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1177      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1178      // Don't lower v32i8 because there is no 128-bit byte mul
1179
1180      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1181
1182      setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1183    } else {
1184      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1185      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1186      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1187      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1188
1189      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1190      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1191      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1192      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1193
1194      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1195      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1196      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1197      // Don't lower v32i8 because there is no 128-bit byte mul
1198    }
1199
1200    // In the customized shift lowering, the legal cases in AVX2 will be
1201    // recognized.
1202    setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1203    setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1204
1205    setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1206    setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1207
1208    setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1209
1210    // Custom lower several nodes for 256-bit types.
1211    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1212             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1213      MVT VT = (MVT::SimpleValueType)i;
1214
1215      // Extract subvector is special because the value type
1216      // (result) is 128-bit but the source is 256-bit wide.
1217      if (VT.is128BitVector())
1218        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1219
1220      // Do not attempt to custom lower other non-256-bit vectors
1221      if (!VT.is256BitVector())
1222        continue;
1223
1224      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1225      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1226      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1227      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1228      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1229      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1230      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1231    }
1232
1233    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1234    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1235      MVT VT = (MVT::SimpleValueType)i;
1236
1237      // Do not attempt to promote non-256-bit vectors
1238      if (!VT.is256BitVector())
1239        continue;
1240
1241      setOperationAction(ISD::AND,    VT, Promote);
1242      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1243      setOperationAction(ISD::OR,     VT, Promote);
1244      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1245      setOperationAction(ISD::XOR,    VT, Promote);
1246      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1247      setOperationAction(ISD::LOAD,   VT, Promote);
1248      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1249      setOperationAction(ISD::SELECT, VT, Promote);
1250      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1251    }
1252  }
1253
1254  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1255  // of this type with custom code.
1256  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1257           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1258    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1259                       Custom);
1260  }
1261
1262  // We want to custom lower some of our intrinsics.
1263  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1264  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1265
1266  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1267  // handle type legalization for these operations here.
1268  //
1269  // FIXME: We really should do custom legalization for addition and
1270  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1271  // than generic legalization for 64-bit multiplication-with-overflow, though.
1272  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1273    // Add/Sub/Mul with overflow operations are custom lowered.
1274    MVT VT = IntVTs[i];
1275    setOperationAction(ISD::SADDO, VT, Custom);
1276    setOperationAction(ISD::UADDO, VT, Custom);
1277    setOperationAction(ISD::SSUBO, VT, Custom);
1278    setOperationAction(ISD::USUBO, VT, Custom);
1279    setOperationAction(ISD::SMULO, VT, Custom);
1280    setOperationAction(ISD::UMULO, VT, Custom);
1281  }
1282
1283  // There are no 8-bit 3-address imul/mul instructions
1284  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1285  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1286
1287  if (!Subtarget->is64Bit()) {
1288    // These libcalls are not available in 32-bit.
1289    setLibcallName(RTLIB::SHL_I128, 0);
1290    setLibcallName(RTLIB::SRL_I128, 0);
1291    setLibcallName(RTLIB::SRA_I128, 0);
1292  }
1293
1294  // Combine sin / cos into one node or libcall if possible.
1295  if (Subtarget->hasSinCos()) {
1296    setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1297    setLibcallName(RTLIB::SINCOS_F64, "sincos");
1298    if (Subtarget->isTargetDarwin()) {
1299      // For MacOSX, we don't want to the normal expansion of a libcall to
1300      // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1301      // traffic.
1302      setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1303      setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1304    }
1305  }
1306
1307  // We have target-specific dag combine patterns for the following nodes:
1308  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1309  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1310  setTargetDAGCombine(ISD::VSELECT);
1311  setTargetDAGCombine(ISD::SELECT);
1312  setTargetDAGCombine(ISD::SHL);
1313  setTargetDAGCombine(ISD::SRA);
1314  setTargetDAGCombine(ISD::SRL);
1315  setTargetDAGCombine(ISD::OR);
1316  setTargetDAGCombine(ISD::AND);
1317  setTargetDAGCombine(ISD::ADD);
1318  setTargetDAGCombine(ISD::FADD);
1319  setTargetDAGCombine(ISD::FSUB);
1320  setTargetDAGCombine(ISD::FMA);
1321  setTargetDAGCombine(ISD::SUB);
1322  setTargetDAGCombine(ISD::LOAD);
1323  setTargetDAGCombine(ISD::STORE);
1324  setTargetDAGCombine(ISD::ZERO_EXTEND);
1325  setTargetDAGCombine(ISD::ANY_EXTEND);
1326  setTargetDAGCombine(ISD::SIGN_EXTEND);
1327  setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1328  setTargetDAGCombine(ISD::TRUNCATE);
1329  setTargetDAGCombine(ISD::SINT_TO_FP);
1330  setTargetDAGCombine(ISD::SETCC);
1331  if (Subtarget->is64Bit())
1332    setTargetDAGCombine(ISD::MUL);
1333  setTargetDAGCombine(ISD::XOR);
1334
1335  computeRegisterProperties();
1336
1337  // On Darwin, -Os means optimize for size without hurting performance,
1338  // do not reduce the limit.
1339  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1340  MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1341  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1342  MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1343  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1344  MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1345  setPrefLoopAlignment(4); // 2^4 bytes.
1346  BenefitFromCodePlacementOpt = true;
1347
1348  // Predictable cmov don't hurt on atom because it's in-order.
1349  PredictableSelectIsExpensive = !Subtarget->isAtom();
1350
1351  setPrefFunctionAlignment(4); // 2^4 bytes.
1352}
1353
1354EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1355  if (!VT.isVector()) return MVT::i8;
1356  return VT.changeVectorElementTypeToInteger();
1357}
1358
1359/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1360/// the desired ByVal argument alignment.
1361static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1362  if (MaxAlign == 16)
1363    return;
1364  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1365    if (VTy->getBitWidth() == 128)
1366      MaxAlign = 16;
1367  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1368    unsigned EltAlign = 0;
1369    getMaxByValAlign(ATy->getElementType(), EltAlign);
1370    if (EltAlign > MaxAlign)
1371      MaxAlign = EltAlign;
1372  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1373    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1374      unsigned EltAlign = 0;
1375      getMaxByValAlign(STy->getElementType(i), EltAlign);
1376      if (EltAlign > MaxAlign)
1377        MaxAlign = EltAlign;
1378      if (MaxAlign == 16)
1379        break;
1380    }
1381  }
1382}
1383
1384/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1385/// function arguments in the caller parameter area. For X86, aggregates
1386/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1387/// are at 4-byte boundaries.
1388unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1389  if (Subtarget->is64Bit()) {
1390    // Max of 8 and alignment of type.
1391    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1392    if (TyAlign > 8)
1393      return TyAlign;
1394    return 8;
1395  }
1396
1397  unsigned Align = 4;
1398  if (Subtarget->hasSSE1())
1399    getMaxByValAlign(Ty, Align);
1400  return Align;
1401}
1402
1403/// getOptimalMemOpType - Returns the target specific optimal type for load
1404/// and store operations as a result of memset, memcpy, and memmove
1405/// lowering. If DstAlign is zero that means it's safe to destination
1406/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1407/// means there isn't a need to check it against alignment requirement,
1408/// probably because the source does not need to be loaded. If 'IsMemset' is
1409/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1410/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1411/// source is constant so it does not need to be loaded.
1412/// It returns EVT::Other if the type should be determined using generic
1413/// target-independent logic.
1414EVT
1415X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1416                                       unsigned DstAlign, unsigned SrcAlign,
1417                                       bool IsMemset, bool ZeroMemset,
1418                                       bool MemcpyStrSrc,
1419                                       MachineFunction &MF) const {
1420  const Function *F = MF.getFunction();
1421  if ((!IsMemset || ZeroMemset) &&
1422      !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1423                                       Attribute::NoImplicitFloat)) {
1424    if (Size >= 16 &&
1425        (Subtarget->isUnalignedMemAccessFast() ||
1426         ((DstAlign == 0 || DstAlign >= 16) &&
1427          (SrcAlign == 0 || SrcAlign >= 16)))) {
1428      if (Size >= 32) {
1429        if (Subtarget->hasInt256())
1430          return MVT::v8i32;
1431        if (Subtarget->hasFp256())
1432          return MVT::v8f32;
1433      }
1434      if (Subtarget->hasSSE2())
1435        return MVT::v4i32;
1436      if (Subtarget->hasSSE1())
1437        return MVT::v4f32;
1438    } else if (!MemcpyStrSrc && Size >= 8 &&
1439               !Subtarget->is64Bit() &&
1440               Subtarget->hasSSE2()) {
1441      // Do not use f64 to lower memcpy if source is string constant. It's
1442      // better to use i32 to avoid the loads.
1443      return MVT::f64;
1444    }
1445  }
1446  if (Subtarget->is64Bit() && Size >= 8)
1447    return MVT::i64;
1448  return MVT::i32;
1449}
1450
1451bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1452  if (VT == MVT::f32)
1453    return X86ScalarSSEf32;
1454  else if (VT == MVT::f64)
1455    return X86ScalarSSEf64;
1456  return true;
1457}
1458
1459bool
1460X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1461  if (Fast)
1462    *Fast = Subtarget->isUnalignedMemAccessFast();
1463  return true;
1464}
1465
1466/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1467/// current function.  The returned value is a member of the
1468/// MachineJumpTableInfo::JTEntryKind enum.
1469unsigned X86TargetLowering::getJumpTableEncoding() const {
1470  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1471  // symbol.
1472  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1473      Subtarget->isPICStyleGOT())
1474    return MachineJumpTableInfo::EK_Custom32;
1475
1476  // Otherwise, use the normal jump table encoding heuristics.
1477  return TargetLowering::getJumpTableEncoding();
1478}
1479
1480const MCExpr *
1481X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1482                                             const MachineBasicBlock *MBB,
1483                                             unsigned uid,MCContext &Ctx) const{
1484  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1485         Subtarget->isPICStyleGOT());
1486  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1487  // entries.
1488  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1489                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1490}
1491
1492/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1493/// jumptable.
1494SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1495                                                    SelectionDAG &DAG) const {
1496  if (!Subtarget->is64Bit())
1497    // This doesn't have DebugLoc associated with it, but is not really the
1498    // same as a Register.
1499    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1500  return Table;
1501}
1502
1503/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1504/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1505/// MCExpr.
1506const MCExpr *X86TargetLowering::
1507getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1508                             MCContext &Ctx) const {
1509  // X86-64 uses RIP relative addressing based on the jump table label.
1510  if (Subtarget->isPICStyleRIPRel())
1511    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1512
1513  // Otherwise, the reference is relative to the PIC base.
1514  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1515}
1516
1517// FIXME: Why this routine is here? Move to RegInfo!
1518std::pair<const TargetRegisterClass*, uint8_t>
1519X86TargetLowering::findRepresentativeClass(MVT VT) const{
1520  const TargetRegisterClass *RRC = 0;
1521  uint8_t Cost = 1;
1522  switch (VT.SimpleTy) {
1523  default:
1524    return TargetLowering::findRepresentativeClass(VT);
1525  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1526    RRC = Subtarget->is64Bit() ?
1527      (const TargetRegisterClass*)&X86::GR64RegClass :
1528      (const TargetRegisterClass*)&X86::GR32RegClass;
1529    break;
1530  case MVT::x86mmx:
1531    RRC = &X86::VR64RegClass;
1532    break;
1533  case MVT::f32: case MVT::f64:
1534  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1535  case MVT::v4f32: case MVT::v2f64:
1536  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1537  case MVT::v4f64:
1538    RRC = &X86::VR128RegClass;
1539    break;
1540  }
1541  return std::make_pair(RRC, Cost);
1542}
1543
1544bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1545                                               unsigned &Offset) const {
1546  if (!Subtarget->isTargetLinux())
1547    return false;
1548
1549  if (Subtarget->is64Bit()) {
1550    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1551    Offset = 0x28;
1552    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1553      AddressSpace = 256;
1554    else
1555      AddressSpace = 257;
1556  } else {
1557    // %gs:0x14 on i386
1558    Offset = 0x14;
1559    AddressSpace = 256;
1560  }
1561  return true;
1562}
1563
1564//===----------------------------------------------------------------------===//
1565//               Return Value Calling Convention Implementation
1566//===----------------------------------------------------------------------===//
1567
1568#include "X86GenCallingConv.inc"
1569
1570bool
1571X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1572                                  MachineFunction &MF, bool isVarArg,
1573                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1574                        LLVMContext &Context) const {
1575  SmallVector<CCValAssign, 16> RVLocs;
1576  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1577                 RVLocs, Context);
1578  return CCInfo.CheckReturn(Outs, RetCC_X86);
1579}
1580
1581SDValue
1582X86TargetLowering::LowerReturn(SDValue Chain,
1583                               CallingConv::ID CallConv, bool isVarArg,
1584                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1585                               const SmallVectorImpl<SDValue> &OutVals,
1586                               DebugLoc dl, SelectionDAG &DAG) const {
1587  MachineFunction &MF = DAG.getMachineFunction();
1588  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1589
1590  SmallVector<CCValAssign, 16> RVLocs;
1591  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1592                 RVLocs, *DAG.getContext());
1593  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1594
1595  SDValue Flag;
1596  SmallVector<SDValue, 6> RetOps;
1597  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1598  // Operand #1 = Bytes To Pop
1599  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1600                   MVT::i16));
1601
1602  // Copy the result values into the output registers.
1603  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604    CCValAssign &VA = RVLocs[i];
1605    assert(VA.isRegLoc() && "Can only return in registers!");
1606    SDValue ValToCopy = OutVals[i];
1607    EVT ValVT = ValToCopy.getValueType();
1608
1609    // Promote values to the appropriate types
1610    if (VA.getLocInfo() == CCValAssign::SExt)
1611      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1612    else if (VA.getLocInfo() == CCValAssign::ZExt)
1613      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1614    else if (VA.getLocInfo() == CCValAssign::AExt)
1615      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1616    else if (VA.getLocInfo() == CCValAssign::BCvt)
1617      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1618
1619    // If this is x86-64, and we disabled SSE, we can't return FP values,
1620    // or SSE or MMX vectors.
1621    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1622         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1623          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1624      report_fatal_error("SSE register return with SSE disabled");
1625    }
1626    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1627    // llvm-gcc has never done it right and no one has noticed, so this
1628    // should be OK for now.
1629    if (ValVT == MVT::f64 &&
1630        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1631      report_fatal_error("SSE2 register return with SSE2 disabled");
1632
1633    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1634    // the RET instruction and handled by the FP Stackifier.
1635    if (VA.getLocReg() == X86::ST0 ||
1636        VA.getLocReg() == X86::ST1) {
1637      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1638      // change the value to the FP stack register class.
1639      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1640        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1641      RetOps.push_back(ValToCopy);
1642      // Don't emit a copytoreg.
1643      continue;
1644    }
1645
1646    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1647    // which is returned in RAX / RDX.
1648    if (Subtarget->is64Bit()) {
1649      if (ValVT == MVT::x86mmx) {
1650        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1651          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1652          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1653                                  ValToCopy);
1654          // If we don't have SSE2 available, convert to v4f32 so the generated
1655          // register is legal.
1656          if (!Subtarget->hasSSE2())
1657            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1658        }
1659      }
1660    }
1661
1662    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1663    Flag = Chain.getValue(1);
1664    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1665  }
1666
1667  // The x86-64 ABIs require that for returning structs by value we copy
1668  // the sret argument into %rax/%eax (depending on ABI) for the return.
1669  // Win32 requires us to put the sret argument to %eax as well.
1670  // We saved the argument into a virtual register in the entry block,
1671  // so now we copy the value out and into %rax/%eax.
1672  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1673      (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1674    MachineFunction &MF = DAG.getMachineFunction();
1675    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1676    unsigned Reg = FuncInfo->getSRetReturnReg();
1677    assert(Reg &&
1678           "SRetReturnReg should have been set in LowerFormalArguments().");
1679    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1680
1681    unsigned RetValReg
1682        = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1683          X86::RAX : X86::EAX;
1684    Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1685    Flag = Chain.getValue(1);
1686
1687    // RAX/EAX now acts like a return value.
1688    RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1689  }
1690
1691  RetOps[0] = Chain;  // Update chain.
1692
1693  // Add the flag if we have it.
1694  if (Flag.getNode())
1695    RetOps.push_back(Flag);
1696
1697  return DAG.getNode(X86ISD::RET_FLAG, dl,
1698                     MVT::Other, &RetOps[0], RetOps.size());
1699}
1700
1701bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1702  if (N->getNumValues() != 1)
1703    return false;
1704  if (!N->hasNUsesOfValue(1, 0))
1705    return false;
1706
1707  SDValue TCChain = Chain;
1708  SDNode *Copy = *N->use_begin();
1709  if (Copy->getOpcode() == ISD::CopyToReg) {
1710    // If the copy has a glue operand, we conservatively assume it isn't safe to
1711    // perform a tail call.
1712    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1713      return false;
1714    TCChain = Copy->getOperand(0);
1715  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1716    return false;
1717
1718  bool HasRet = false;
1719  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1720       UI != UE; ++UI) {
1721    if (UI->getOpcode() != X86ISD::RET_FLAG)
1722      return false;
1723    HasRet = true;
1724  }
1725
1726  if (!HasRet)
1727    return false;
1728
1729  Chain = TCChain;
1730  return true;
1731}
1732
1733MVT
1734X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1735                                            ISD::NodeType ExtendKind) const {
1736  MVT ReturnMVT;
1737  // TODO: Is this also valid on 32-bit?
1738  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1739    ReturnMVT = MVT::i8;
1740  else
1741    ReturnMVT = MVT::i32;
1742
1743  MVT MinVT = getRegisterType(ReturnMVT);
1744  return VT.bitsLT(MinVT) ? MinVT : VT;
1745}
1746
1747/// LowerCallResult - Lower the result values of a call into the
1748/// appropriate copies out of appropriate physical registers.
1749///
1750SDValue
1751X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1752                                   CallingConv::ID CallConv, bool isVarArg,
1753                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1754                                   DebugLoc dl, SelectionDAG &DAG,
1755                                   SmallVectorImpl<SDValue> &InVals) const {
1756
1757  // Assign locations to each value returned by this call.
1758  SmallVector<CCValAssign, 16> RVLocs;
1759  bool Is64Bit = Subtarget->is64Bit();
1760  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1761                 getTargetMachine(), RVLocs, *DAG.getContext());
1762  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1763
1764  // Copy all of the result registers out of their specified physreg.
1765  for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1766    CCValAssign &VA = RVLocs[i];
1767    EVT CopyVT = VA.getValVT();
1768
1769    // If this is x86-64, and we disabled SSE, we can't return FP values
1770    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1771        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1772      report_fatal_error("SSE register return with SSE disabled");
1773    }
1774
1775    SDValue Val;
1776
1777    // If this is a call to a function that returns an fp value on the floating
1778    // point stack, we must guarantee the value is popped from the stack, so
1779    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1780    // if the return value is not used. We use the FpPOP_RETVAL instruction
1781    // instead.
1782    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1783      // If we prefer to use the value in xmm registers, copy it out as f80 and
1784      // use a truncate to move it from fp stack reg to xmm reg.
1785      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1786      SDValue Ops[] = { Chain, InFlag };
1787      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1788                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1789      Val = Chain.getValue(0);
1790
1791      // Round the f80 to the right size, which also moves it to the appropriate
1792      // xmm register.
1793      if (CopyVT != VA.getValVT())
1794        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1795                          // This truncation won't change the value.
1796                          DAG.getIntPtrConstant(1));
1797    } else {
1798      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1799                                 CopyVT, InFlag).getValue(1);
1800      Val = Chain.getValue(0);
1801    }
1802    InFlag = Chain.getValue(2);
1803    InVals.push_back(Val);
1804  }
1805
1806  return Chain;
1807}
1808
1809//===----------------------------------------------------------------------===//
1810//                C & StdCall & Fast Calling Convention implementation
1811//===----------------------------------------------------------------------===//
1812//  StdCall calling convention seems to be standard for many Windows' API
1813//  routines and around. It differs from C calling convention just a little:
1814//  callee should clean up the stack, not caller. Symbols should be also
1815//  decorated in some fancy way :) It doesn't support any vector arguments.
1816//  For info on fast calling convention see Fast Calling Convention (tail call)
1817//  implementation LowerX86_32FastCCCallTo.
1818
1819/// CallIsStructReturn - Determines whether a call uses struct return
1820/// semantics.
1821enum StructReturnType {
1822  NotStructReturn,
1823  RegStructReturn,
1824  StackStructReturn
1825};
1826static StructReturnType
1827callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1828  if (Outs.empty())
1829    return NotStructReturn;
1830
1831  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1832  if (!Flags.isSRet())
1833    return NotStructReturn;
1834  if (Flags.isInReg())
1835    return RegStructReturn;
1836  return StackStructReturn;
1837}
1838
1839/// ArgsAreStructReturn - Determines whether a function uses struct
1840/// return semantics.
1841static StructReturnType
1842argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1843  if (Ins.empty())
1844    return NotStructReturn;
1845
1846  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1847  if (!Flags.isSRet())
1848    return NotStructReturn;
1849  if (Flags.isInReg())
1850    return RegStructReturn;
1851  return StackStructReturn;
1852}
1853
1854/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1855/// by "Src" to address "Dst" with size and alignment information specified by
1856/// the specific parameter attribute. The copy will be passed as a byval
1857/// function parameter.
1858static SDValue
1859CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1860                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1861                          DebugLoc dl) {
1862  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1863
1864  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1865                       /*isVolatile*/false, /*AlwaysInline=*/true,
1866                       MachinePointerInfo(), MachinePointerInfo());
1867}
1868
1869/// IsTailCallConvention - Return true if the calling convention is one that
1870/// supports tail call optimization.
1871static bool IsTailCallConvention(CallingConv::ID CC) {
1872  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1873          CC == CallingConv::HiPE);
1874}
1875
1876bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1877  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1878    return false;
1879
1880  CallSite CS(CI);
1881  CallingConv::ID CalleeCC = CS.getCallingConv();
1882  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1883    return false;
1884
1885  return true;
1886}
1887
1888/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1889/// a tailcall target by changing its ABI.
1890static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1891                                   bool GuaranteedTailCallOpt) {
1892  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1893}
1894
1895SDValue
1896X86TargetLowering::LowerMemArgument(SDValue Chain,
1897                                    CallingConv::ID CallConv,
1898                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1899                                    DebugLoc dl, SelectionDAG &DAG,
1900                                    const CCValAssign &VA,
1901                                    MachineFrameInfo *MFI,
1902                                    unsigned i) const {
1903  // Create the nodes corresponding to a load from this parameter slot.
1904  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1905  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1906                              getTargetMachine().Options.GuaranteedTailCallOpt);
1907  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1908  EVT ValVT;
1909
1910  // If value is passed by pointer we have address passed instead of the value
1911  // itself.
1912  if (VA.getLocInfo() == CCValAssign::Indirect)
1913    ValVT = VA.getLocVT();
1914  else
1915    ValVT = VA.getValVT();
1916
1917  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1918  // changed with more analysis.
1919  // In case of tail call optimization mark all arguments mutable. Since they
1920  // could be overwritten by lowering of arguments in case of a tail call.
1921  if (Flags.isByVal()) {
1922    unsigned Bytes = Flags.getByValSize();
1923    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1924    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1925    return DAG.getFrameIndex(FI, getPointerTy());
1926  } else {
1927    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1928                                    VA.getLocMemOffset(), isImmutable);
1929    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1930    return DAG.getLoad(ValVT, dl, Chain, FIN,
1931                       MachinePointerInfo::getFixedStack(FI),
1932                       false, false, false, 0);
1933  }
1934}
1935
1936SDValue
1937X86TargetLowering::LowerFormalArguments(SDValue Chain,
1938                                        CallingConv::ID CallConv,
1939                                        bool isVarArg,
1940                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1941                                        DebugLoc dl,
1942                                        SelectionDAG &DAG,
1943                                        SmallVectorImpl<SDValue> &InVals)
1944                                          const {
1945  MachineFunction &MF = DAG.getMachineFunction();
1946  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1947
1948  const Function* Fn = MF.getFunction();
1949  if (Fn->hasExternalLinkage() &&
1950      Subtarget->isTargetCygMing() &&
1951      Fn->getName() == "main")
1952    FuncInfo->setForceFramePointer(true);
1953
1954  MachineFrameInfo *MFI = MF.getFrameInfo();
1955  bool Is64Bit = Subtarget->is64Bit();
1956  bool IsWindows = Subtarget->isTargetWindows();
1957  bool IsWin64 = Subtarget->isTargetWin64();
1958
1959  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1960         "Var args not supported with calling convention fastcc, ghc or hipe");
1961
1962  // Assign locations to all of the incoming arguments.
1963  SmallVector<CCValAssign, 16> ArgLocs;
1964  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1965                 ArgLocs, *DAG.getContext());
1966
1967  // Allocate shadow area for Win64
1968  if (IsWin64) {
1969    CCInfo.AllocateStack(32, 8);
1970  }
1971
1972  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1973
1974  unsigned LastVal = ~0U;
1975  SDValue ArgValue;
1976  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1977    CCValAssign &VA = ArgLocs[i];
1978    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1979    // places.
1980    assert(VA.getValNo() != LastVal &&
1981           "Don't support value assigned to multiple locs yet");
1982    (void)LastVal;
1983    LastVal = VA.getValNo();
1984
1985    if (VA.isRegLoc()) {
1986      EVT RegVT = VA.getLocVT();
1987      const TargetRegisterClass *RC;
1988      if (RegVT == MVT::i32)
1989        RC = &X86::GR32RegClass;
1990      else if (Is64Bit && RegVT == MVT::i64)
1991        RC = &X86::GR64RegClass;
1992      else if (RegVT == MVT::f32)
1993        RC = &X86::FR32RegClass;
1994      else if (RegVT == MVT::f64)
1995        RC = &X86::FR64RegClass;
1996      else if (RegVT.is256BitVector())
1997        RC = &X86::VR256RegClass;
1998      else if (RegVT.is128BitVector())
1999        RC = &X86::VR128RegClass;
2000      else if (RegVT == MVT::x86mmx)
2001        RC = &X86::VR64RegClass;
2002      else
2003        llvm_unreachable("Unknown argument type!");
2004
2005      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2006      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2007
2008      // If this is an 8 or 16-bit value, it is really passed promoted to 32
2009      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2010      // right size.
2011      if (VA.getLocInfo() == CCValAssign::SExt)
2012        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2013                               DAG.getValueType(VA.getValVT()));
2014      else if (VA.getLocInfo() == CCValAssign::ZExt)
2015        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2016                               DAG.getValueType(VA.getValVT()));
2017      else if (VA.getLocInfo() == CCValAssign::BCvt)
2018        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2019
2020      if (VA.isExtInLoc()) {
2021        // Handle MMX values passed in XMM regs.
2022        if (RegVT.isVector())
2023          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2024        else
2025          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2026      }
2027    } else {
2028      assert(VA.isMemLoc());
2029      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2030    }
2031
2032    // If value is passed via pointer - do a load.
2033    if (VA.getLocInfo() == CCValAssign::Indirect)
2034      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2035                             MachinePointerInfo(), false, false, false, 0);
2036
2037    InVals.push_back(ArgValue);
2038  }
2039
2040  // The x86-64 ABIs require that for returning structs by value we copy
2041  // the sret argument into %rax/%eax (depending on ABI) for the return.
2042  // Win32 requires us to put the sret argument to %eax as well.
2043  // Save the argument into a virtual register so that we can access it
2044  // from the return points.
2045  if (MF.getFunction()->hasStructRetAttr() &&
2046      (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2047    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2048    unsigned Reg = FuncInfo->getSRetReturnReg();
2049    if (!Reg) {
2050      MVT PtrTy = getPointerTy();
2051      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2052      FuncInfo->setSRetReturnReg(Reg);
2053    }
2054    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2055    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2056  }
2057
2058  unsigned StackSize = CCInfo.getNextStackOffset();
2059  // Align stack specially for tail calls.
2060  if (FuncIsMadeTailCallSafe(CallConv,
2061                             MF.getTarget().Options.GuaranteedTailCallOpt))
2062    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2063
2064  // If the function takes variable number of arguments, make a frame index for
2065  // the start of the first vararg value... for expansion of llvm.va_start.
2066  if (isVarArg) {
2067    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2068                    CallConv != CallingConv::X86_ThisCall)) {
2069      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2070    }
2071    if (Is64Bit) {
2072      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2073
2074      // FIXME: We should really autogenerate these arrays
2075      static const uint16_t GPR64ArgRegsWin64[] = {
2076        X86::RCX, X86::RDX, X86::R8,  X86::R9
2077      };
2078      static const uint16_t GPR64ArgRegs64Bit[] = {
2079        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2080      };
2081      static const uint16_t XMMArgRegs64Bit[] = {
2082        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2083        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2084      };
2085      const uint16_t *GPR64ArgRegs;
2086      unsigned NumXMMRegs = 0;
2087
2088      if (IsWin64) {
2089        // The XMM registers which might contain var arg parameters are shadowed
2090        // in their paired GPR.  So we only need to save the GPR to their home
2091        // slots.
2092        TotalNumIntRegs = 4;
2093        GPR64ArgRegs = GPR64ArgRegsWin64;
2094      } else {
2095        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2096        GPR64ArgRegs = GPR64ArgRegs64Bit;
2097
2098        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2099                                                TotalNumXMMRegs);
2100      }
2101      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2102                                                       TotalNumIntRegs);
2103
2104      bool NoImplicitFloatOps = Fn->getAttributes().
2105        hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2106      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2107             "SSE register cannot be used when SSE is disabled!");
2108      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2109               NoImplicitFloatOps) &&
2110             "SSE register cannot be used when SSE is disabled!");
2111      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2112          !Subtarget->hasSSE1())
2113        // Kernel mode asks for SSE to be disabled, so don't push them
2114        // on the stack.
2115        TotalNumXMMRegs = 0;
2116
2117      if (IsWin64) {
2118        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2119        // Get to the caller-allocated home save location.  Add 8 to account
2120        // for the return address.
2121        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2122        FuncInfo->setRegSaveFrameIndex(
2123          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2124        // Fixup to set vararg frame on shadow area (4 x i64).
2125        if (NumIntRegs < 4)
2126          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2127      } else {
2128        // For X86-64, if there are vararg parameters that are passed via
2129        // registers, then we must store them to their spots on the stack so
2130        // they may be loaded by deferencing the result of va_next.
2131        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2132        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2133        FuncInfo->setRegSaveFrameIndex(
2134          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2135                               false));
2136      }
2137
2138      // Store the integer parameter registers.
2139      SmallVector<SDValue, 8> MemOps;
2140      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2141                                        getPointerTy());
2142      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2143      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2144        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2145                                  DAG.getIntPtrConstant(Offset));
2146        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2147                                     &X86::GR64RegClass);
2148        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2149        SDValue Store =
2150          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2151                       MachinePointerInfo::getFixedStack(
2152                         FuncInfo->getRegSaveFrameIndex(), Offset),
2153                       false, false, 0);
2154        MemOps.push_back(Store);
2155        Offset += 8;
2156      }
2157
2158      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2159        // Now store the XMM (fp + vector) parameter registers.
2160        SmallVector<SDValue, 11> SaveXMMOps;
2161        SaveXMMOps.push_back(Chain);
2162
2163        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2164        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2165        SaveXMMOps.push_back(ALVal);
2166
2167        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2168                               FuncInfo->getRegSaveFrameIndex()));
2169        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2170                               FuncInfo->getVarArgsFPOffset()));
2171
2172        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2173          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2174                                       &X86::VR128RegClass);
2175          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2176          SaveXMMOps.push_back(Val);
2177        }
2178        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2179                                     MVT::Other,
2180                                     &SaveXMMOps[0], SaveXMMOps.size()));
2181      }
2182
2183      if (!MemOps.empty())
2184        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2185                            &MemOps[0], MemOps.size());
2186    }
2187  }
2188
2189  // Some CCs need callee pop.
2190  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2191                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2192    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2193  } else {
2194    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2195    // If this is an sret function, the return should pop the hidden pointer.
2196    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2197        argsAreStructReturn(Ins) == StackStructReturn)
2198      FuncInfo->setBytesToPopOnReturn(4);
2199  }
2200
2201  if (!Is64Bit) {
2202    // RegSaveFrameIndex is X86-64 only.
2203    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2204    if (CallConv == CallingConv::X86_FastCall ||
2205        CallConv == CallingConv::X86_ThisCall)
2206      // fastcc functions can't have varargs.
2207      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2208  }
2209
2210  FuncInfo->setArgumentStackSize(StackSize);
2211
2212  return Chain;
2213}
2214
2215SDValue
2216X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2217                                    SDValue StackPtr, SDValue Arg,
2218                                    DebugLoc dl, SelectionDAG &DAG,
2219                                    const CCValAssign &VA,
2220                                    ISD::ArgFlagsTy Flags) const {
2221  unsigned LocMemOffset = VA.getLocMemOffset();
2222  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2223  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2224  if (Flags.isByVal())
2225    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2226
2227  return DAG.getStore(Chain, dl, Arg, PtrOff,
2228                      MachinePointerInfo::getStack(LocMemOffset),
2229                      false, false, 0);
2230}
2231
2232/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2233/// optimization is performed and it is required.
2234SDValue
2235X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2236                                           SDValue &OutRetAddr, SDValue Chain,
2237                                           bool IsTailCall, bool Is64Bit,
2238                                           int FPDiff, DebugLoc dl) const {
2239  // Adjust the Return address stack slot.
2240  EVT VT = getPointerTy();
2241  OutRetAddr = getReturnAddressFrameIndex(DAG);
2242
2243  // Load the "old" Return address.
2244  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2245                           false, false, false, 0);
2246  return SDValue(OutRetAddr.getNode(), 1);
2247}
2248
2249/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2250/// optimization is performed and it is required (FPDiff!=0).
2251static SDValue
2252EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2253                         SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2254                         unsigned SlotSize, int FPDiff, DebugLoc dl) {
2255  // Store the return address to the appropriate stack slot.
2256  if (!FPDiff) return Chain;
2257  // Calculate the new stack slot for the return address.
2258  int NewReturnAddrFI =
2259    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2260  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2261  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2262                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2263                       false, false, 0);
2264  return Chain;
2265}
2266
2267SDValue
2268X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2269                             SmallVectorImpl<SDValue> &InVals) const {
2270  SelectionDAG &DAG                     = CLI.DAG;
2271  DebugLoc &dl                          = CLI.DL;
2272  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2273  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2274  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2275  SDValue Chain                         = CLI.Chain;
2276  SDValue Callee                        = CLI.Callee;
2277  CallingConv::ID CallConv              = CLI.CallConv;
2278  bool &isTailCall                      = CLI.IsTailCall;
2279  bool isVarArg                         = CLI.IsVarArg;
2280
2281  MachineFunction &MF = DAG.getMachineFunction();
2282  bool Is64Bit        = Subtarget->is64Bit();
2283  bool IsWin64        = Subtarget->isTargetWin64();
2284  bool IsWindows      = Subtarget->isTargetWindows();
2285  StructReturnType SR = callIsStructReturn(Outs);
2286  bool IsSibcall      = false;
2287
2288  if (MF.getTarget().Options.DisableTailCalls)
2289    isTailCall = false;
2290
2291  if (isTailCall) {
2292    // Check if it's really possible to do a tail call.
2293    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2294                    isVarArg, SR != NotStructReturn,
2295                    MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2296                    Outs, OutVals, Ins, DAG);
2297
2298    // Sibcalls are automatically detected tailcalls which do not require
2299    // ABI changes.
2300    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2301      IsSibcall = true;
2302
2303    if (isTailCall)
2304      ++NumTailCalls;
2305  }
2306
2307  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2308         "Var args not supported with calling convention fastcc, ghc or hipe");
2309
2310  // Analyze operands of the call, assigning locations to each operand.
2311  SmallVector<CCValAssign, 16> ArgLocs;
2312  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2313                 ArgLocs, *DAG.getContext());
2314
2315  // Allocate shadow area for Win64
2316  if (IsWin64) {
2317    CCInfo.AllocateStack(32, 8);
2318  }
2319
2320  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2321
2322  // Get a count of how many bytes are to be pushed on the stack.
2323  unsigned NumBytes = CCInfo.getNextStackOffset();
2324  if (IsSibcall)
2325    // This is a sibcall. The memory operands are available in caller's
2326    // own caller's stack.
2327    NumBytes = 0;
2328  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2329           IsTailCallConvention(CallConv))
2330    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2331
2332  int FPDiff = 0;
2333  if (isTailCall && !IsSibcall) {
2334    // Lower arguments at fp - stackoffset + fpdiff.
2335    X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2336    unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2337
2338    FPDiff = NumBytesCallerPushed - NumBytes;
2339
2340    // Set the delta of movement of the returnaddr stackslot.
2341    // But only set if delta is greater than previous delta.
2342    if (FPDiff < X86Info->getTCReturnAddrDelta())
2343      X86Info->setTCReturnAddrDelta(FPDiff);
2344  }
2345
2346  if (!IsSibcall)
2347    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2348
2349  SDValue RetAddrFrIdx;
2350  // Load return address for tail calls.
2351  if (isTailCall && FPDiff)
2352    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2353                                    Is64Bit, FPDiff, dl);
2354
2355  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2356  SmallVector<SDValue, 8> MemOpChains;
2357  SDValue StackPtr;
2358
2359  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2360  // of tail call optimization arguments are handle later.
2361  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2362    CCValAssign &VA = ArgLocs[i];
2363    EVT RegVT = VA.getLocVT();
2364    SDValue Arg = OutVals[i];
2365    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2366    bool isByVal = Flags.isByVal();
2367
2368    // Promote the value if needed.
2369    switch (VA.getLocInfo()) {
2370    default: llvm_unreachable("Unknown loc info!");
2371    case CCValAssign::Full: break;
2372    case CCValAssign::SExt:
2373      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2374      break;
2375    case CCValAssign::ZExt:
2376      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2377      break;
2378    case CCValAssign::AExt:
2379      if (RegVT.is128BitVector()) {
2380        // Special case: passing MMX values in XMM registers.
2381        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2382        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2383        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2384      } else
2385        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2386      break;
2387    case CCValAssign::BCvt:
2388      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2389      break;
2390    case CCValAssign::Indirect: {
2391      // Store the argument.
2392      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2393      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2394      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2395                           MachinePointerInfo::getFixedStack(FI),
2396                           false, false, 0);
2397      Arg = SpillSlot;
2398      break;
2399    }
2400    }
2401
2402    if (VA.isRegLoc()) {
2403      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2404      if (isVarArg && IsWin64) {
2405        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2406        // shadow reg if callee is a varargs function.
2407        unsigned ShadowReg = 0;
2408        switch (VA.getLocReg()) {
2409        case X86::XMM0: ShadowReg = X86::RCX; break;
2410        case X86::XMM1: ShadowReg = X86::RDX; break;
2411        case X86::XMM2: ShadowReg = X86::R8; break;
2412        case X86::XMM3: ShadowReg = X86::R9; break;
2413        }
2414        if (ShadowReg)
2415          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2416      }
2417    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2418      assert(VA.isMemLoc());
2419      if (StackPtr.getNode() == 0)
2420        StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2421                                      getPointerTy());
2422      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2423                                             dl, DAG, VA, Flags));
2424    }
2425  }
2426
2427  if (!MemOpChains.empty())
2428    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2429                        &MemOpChains[0], MemOpChains.size());
2430
2431  if (Subtarget->isPICStyleGOT()) {
2432    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2433    // GOT pointer.
2434    if (!isTailCall) {
2435      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2436               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2437    } else {
2438      // If we are tail calling and generating PIC/GOT style code load the
2439      // address of the callee into ECX. The value in ecx is used as target of
2440      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2441      // for tail calls on PIC/GOT architectures. Normally we would just put the
2442      // address of GOT into ebx and then call target@PLT. But for tail calls
2443      // ebx would be restored (since ebx is callee saved) before jumping to the
2444      // target@PLT.
2445
2446      // Note: The actual moving to ECX is done further down.
2447      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2448      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2449          !G->getGlobal()->hasProtectedVisibility())
2450        Callee = LowerGlobalAddress(Callee, DAG);
2451      else if (isa<ExternalSymbolSDNode>(Callee))
2452        Callee = LowerExternalSymbol(Callee, DAG);
2453    }
2454  }
2455
2456  if (Is64Bit && isVarArg && !IsWin64) {
2457    // From AMD64 ABI document:
2458    // For calls that may call functions that use varargs or stdargs
2459    // (prototype-less calls or calls to functions containing ellipsis (...) in
2460    // the declaration) %al is used as hidden argument to specify the number
2461    // of SSE registers used. The contents of %al do not need to match exactly
2462    // the number of registers, but must be an ubound on the number of SSE
2463    // registers used and is in the range 0 - 8 inclusive.
2464
2465    // Count the number of XMM registers allocated.
2466    static const uint16_t XMMArgRegs[] = {
2467      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2468      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2469    };
2470    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2471    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2472           && "SSE registers cannot be used when SSE is disabled");
2473
2474    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2475                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2476  }
2477
2478  // For tail calls lower the arguments to the 'real' stack slot.
2479  if (isTailCall) {
2480    // Force all the incoming stack arguments to be loaded from the stack
2481    // before any new outgoing arguments are stored to the stack, because the
2482    // outgoing stack slots may alias the incoming argument stack slots, and
2483    // the alias isn't otherwise explicit. This is slightly more conservative
2484    // than necessary, because it means that each store effectively depends
2485    // on every argument instead of just those arguments it would clobber.
2486    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2487
2488    SmallVector<SDValue, 8> MemOpChains2;
2489    SDValue FIN;
2490    int FI = 0;
2491    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2492      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2493        CCValAssign &VA = ArgLocs[i];
2494        if (VA.isRegLoc())
2495          continue;
2496        assert(VA.isMemLoc());
2497        SDValue Arg = OutVals[i];
2498        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2499        // Create frame index.
2500        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2501        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2502        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2503        FIN = DAG.getFrameIndex(FI, getPointerTy());
2504
2505        if (Flags.isByVal()) {
2506          // Copy relative to framepointer.
2507          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2508          if (StackPtr.getNode() == 0)
2509            StackPtr = DAG.getCopyFromReg(Chain, dl,
2510                                          RegInfo->getStackRegister(),
2511                                          getPointerTy());
2512          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2513
2514          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2515                                                           ArgChain,
2516                                                           Flags, DAG, dl));
2517        } else {
2518          // Store relative to framepointer.
2519          MemOpChains2.push_back(
2520            DAG.getStore(ArgChain, dl, Arg, FIN,
2521                         MachinePointerInfo::getFixedStack(FI),
2522                         false, false, 0));
2523        }
2524      }
2525    }
2526
2527    if (!MemOpChains2.empty())
2528      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2529                          &MemOpChains2[0], MemOpChains2.size());
2530
2531    // Store the return address to the appropriate stack slot.
2532    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2533                                     getPointerTy(), RegInfo->getSlotSize(),
2534                                     FPDiff, dl);
2535  }
2536
2537  // Build a sequence of copy-to-reg nodes chained together with token chain
2538  // and flag operands which copy the outgoing args into registers.
2539  SDValue InFlag;
2540  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2541    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2542                             RegsToPass[i].second, InFlag);
2543    InFlag = Chain.getValue(1);
2544  }
2545
2546  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2547    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2548    // In the 64-bit large code model, we have to make all calls
2549    // through a register, since the call instruction's 32-bit
2550    // pc-relative offset may not be large enough to hold the whole
2551    // address.
2552  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2553    // If the callee is a GlobalAddress node (quite common, every direct call
2554    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2555    // it.
2556
2557    // We should use extra load for direct calls to dllimported functions in
2558    // non-JIT mode.
2559    const GlobalValue *GV = G->getGlobal();
2560    if (!GV->hasDLLImportLinkage()) {
2561      unsigned char OpFlags = 0;
2562      bool ExtraLoad = false;
2563      unsigned WrapperKind = ISD::DELETED_NODE;
2564
2565      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2566      // external symbols most go through the PLT in PIC mode.  If the symbol
2567      // has hidden or protected visibility, or if it is static or local, then
2568      // we don't need to use the PLT - we can directly call it.
2569      if (Subtarget->isTargetELF() &&
2570          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2571          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2572        OpFlags = X86II::MO_PLT;
2573      } else if (Subtarget->isPICStyleStubAny() &&
2574                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2575                 (!Subtarget->getTargetTriple().isMacOSX() ||
2576                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2577        // PC-relative references to external symbols should go through $stub,
2578        // unless we're building with the leopard linker or later, which
2579        // automatically synthesizes these stubs.
2580        OpFlags = X86II::MO_DARWIN_STUB;
2581      } else if (Subtarget->isPICStyleRIPRel() &&
2582                 isa<Function>(GV) &&
2583                 cast<Function>(GV)->getAttributes().
2584                   hasAttribute(AttributeSet::FunctionIndex,
2585                                Attribute::NonLazyBind)) {
2586        // If the function is marked as non-lazy, generate an indirect call
2587        // which loads from the GOT directly. This avoids runtime overhead
2588        // at the cost of eager binding (and one extra byte of encoding).
2589        OpFlags = X86II::MO_GOTPCREL;
2590        WrapperKind = X86ISD::WrapperRIP;
2591        ExtraLoad = true;
2592      }
2593
2594      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2595                                          G->getOffset(), OpFlags);
2596
2597      // Add a wrapper if needed.
2598      if (WrapperKind != ISD::DELETED_NODE)
2599        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2600      // Add extra indirection if needed.
2601      if (ExtraLoad)
2602        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2603                             MachinePointerInfo::getGOT(),
2604                             false, false, false, 0);
2605    }
2606  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2607    unsigned char OpFlags = 0;
2608
2609    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2610    // external symbols should go through the PLT.
2611    if (Subtarget->isTargetELF() &&
2612        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2613      OpFlags = X86II::MO_PLT;
2614    } else if (Subtarget->isPICStyleStubAny() &&
2615               (!Subtarget->getTargetTriple().isMacOSX() ||
2616                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2617      // PC-relative references to external symbols should go through $stub,
2618      // unless we're building with the leopard linker or later, which
2619      // automatically synthesizes these stubs.
2620      OpFlags = X86II::MO_DARWIN_STUB;
2621    }
2622
2623    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2624                                         OpFlags);
2625  }
2626
2627  // Returns a chain & a flag for retval copy to use.
2628  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2629  SmallVector<SDValue, 8> Ops;
2630
2631  if (!IsSibcall && isTailCall) {
2632    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2633                           DAG.getIntPtrConstant(0, true), InFlag);
2634    InFlag = Chain.getValue(1);
2635  }
2636
2637  Ops.push_back(Chain);
2638  Ops.push_back(Callee);
2639
2640  if (isTailCall)
2641    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2642
2643  // Add argument registers to the end of the list so that they are known live
2644  // into the call.
2645  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2646    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2647                                  RegsToPass[i].second.getValueType()));
2648
2649  // Add a register mask operand representing the call-preserved registers.
2650  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2651  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2652  assert(Mask && "Missing call preserved mask for calling convention");
2653  Ops.push_back(DAG.getRegisterMask(Mask));
2654
2655  if (InFlag.getNode())
2656    Ops.push_back(InFlag);
2657
2658  if (isTailCall) {
2659    // We used to do:
2660    //// If this is the first return lowered for this function, add the regs
2661    //// to the liveout set for the function.
2662    // This isn't right, although it's probably harmless on x86; liveouts
2663    // should be computed from returns not tail calls.  Consider a void
2664    // function making a tail call to a function returning int.
2665    return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2666  }
2667
2668  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2669  InFlag = Chain.getValue(1);
2670
2671  // Create the CALLSEQ_END node.
2672  unsigned NumBytesForCalleeToPush;
2673  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2674                       getTargetMachine().Options.GuaranteedTailCallOpt))
2675    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2676  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2677           SR == StackStructReturn)
2678    // If this is a call to a struct-return function, the callee
2679    // pops the hidden struct pointer, so we have to push it back.
2680    // This is common for Darwin/X86, Linux & Mingw32 targets.
2681    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2682    NumBytesForCalleeToPush = 4;
2683  else
2684    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2685
2686  // Returns a flag for retval copy to use.
2687  if (!IsSibcall) {
2688    Chain = DAG.getCALLSEQ_END(Chain,
2689                               DAG.getIntPtrConstant(NumBytes, true),
2690                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2691                                                     true),
2692                               InFlag);
2693    InFlag = Chain.getValue(1);
2694  }
2695
2696  // Handle result values, copying them out of physregs into vregs that we
2697  // return.
2698  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2699                         Ins, dl, DAG, InVals);
2700}
2701
2702//===----------------------------------------------------------------------===//
2703//                Fast Calling Convention (tail call) implementation
2704//===----------------------------------------------------------------------===//
2705
2706//  Like std call, callee cleans arguments, convention except that ECX is
2707//  reserved for storing the tail called function address. Only 2 registers are
2708//  free for argument passing (inreg). Tail call optimization is performed
2709//  provided:
2710//                * tailcallopt is enabled
2711//                * caller/callee are fastcc
2712//  On X86_64 architecture with GOT-style position independent code only local
2713//  (within module) calls are supported at the moment.
2714//  To keep the stack aligned according to platform abi the function
2715//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2716//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2717//  If a tail called function callee has more arguments than the caller the
2718//  caller needs to make sure that there is room to move the RETADDR to. This is
2719//  achieved by reserving an area the size of the argument delta right after the
2720//  original REtADDR, but before the saved framepointer or the spilled registers
2721//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2722//  stack layout:
2723//    arg1
2724//    arg2
2725//    RETADDR
2726//    [ new RETADDR
2727//      move area ]
2728//    (possible EBP)
2729//    ESI
2730//    EDI
2731//    local1 ..
2732
2733/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2734/// for a 16 byte align requirement.
2735unsigned
2736X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2737                                               SelectionDAG& DAG) const {
2738  MachineFunction &MF = DAG.getMachineFunction();
2739  const TargetMachine &TM = MF.getTarget();
2740  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2741  unsigned StackAlignment = TFI.getStackAlignment();
2742  uint64_t AlignMask = StackAlignment - 1;
2743  int64_t Offset = StackSize;
2744  unsigned SlotSize = RegInfo->getSlotSize();
2745  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2746    // Number smaller than 12 so just add the difference.
2747    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2748  } else {
2749    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2750    Offset = ((~AlignMask) & Offset) + StackAlignment +
2751      (StackAlignment-SlotSize);
2752  }
2753  return Offset;
2754}
2755
2756/// MatchingStackOffset - Return true if the given stack call argument is
2757/// already available in the same position (relatively) of the caller's
2758/// incoming argument stack.
2759static
2760bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2761                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2762                         const X86InstrInfo *TII) {
2763  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2764  int FI = INT_MAX;
2765  if (Arg.getOpcode() == ISD::CopyFromReg) {
2766    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2767    if (!TargetRegisterInfo::isVirtualRegister(VR))
2768      return false;
2769    MachineInstr *Def = MRI->getVRegDef(VR);
2770    if (!Def)
2771      return false;
2772    if (!Flags.isByVal()) {
2773      if (!TII->isLoadFromStackSlot(Def, FI))
2774        return false;
2775    } else {
2776      unsigned Opcode = Def->getOpcode();
2777      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2778          Def->getOperand(1).isFI()) {
2779        FI = Def->getOperand(1).getIndex();
2780        Bytes = Flags.getByValSize();
2781      } else
2782        return false;
2783    }
2784  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2785    if (Flags.isByVal())
2786      // ByVal argument is passed in as a pointer but it's now being
2787      // dereferenced. e.g.
2788      // define @foo(%struct.X* %A) {
2789      //   tail call @bar(%struct.X* byval %A)
2790      // }
2791      return false;
2792    SDValue Ptr = Ld->getBasePtr();
2793    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2794    if (!FINode)
2795      return false;
2796    FI = FINode->getIndex();
2797  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2798    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2799    FI = FINode->getIndex();
2800    Bytes = Flags.getByValSize();
2801  } else
2802    return false;
2803
2804  assert(FI != INT_MAX);
2805  if (!MFI->isFixedObjectIndex(FI))
2806    return false;
2807  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2808}
2809
2810/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2811/// for tail call optimization. Targets which want to do tail call
2812/// optimization should implement this function.
2813bool
2814X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2815                                                     CallingConv::ID CalleeCC,
2816                                                     bool isVarArg,
2817                                                     bool isCalleeStructRet,
2818                                                     bool isCallerStructRet,
2819                                                     Type *RetTy,
2820                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2821                                    const SmallVectorImpl<SDValue> &OutVals,
2822                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2823                                                     SelectionDAG &DAG) const {
2824  if (!IsTailCallConvention(CalleeCC) &&
2825      CalleeCC != CallingConv::C)
2826    return false;
2827
2828  // If -tailcallopt is specified, make fastcc functions tail-callable.
2829  const MachineFunction &MF = DAG.getMachineFunction();
2830  const Function *CallerF = DAG.getMachineFunction().getFunction();
2831
2832  // If the function return type is x86_fp80 and the callee return type is not,
2833  // then the FP_EXTEND of the call result is not a nop. It's not safe to
2834  // perform a tailcall optimization here.
2835  if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2836    return false;
2837
2838  CallingConv::ID CallerCC = CallerF->getCallingConv();
2839  bool CCMatch = CallerCC == CalleeCC;
2840
2841  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2842    if (IsTailCallConvention(CalleeCC) && CCMatch)
2843      return true;
2844    return false;
2845  }
2846
2847  // Look for obvious safe cases to perform tail call optimization that do not
2848  // require ABI changes. This is what gcc calls sibcall.
2849
2850  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2851  // emit a special epilogue.
2852  if (RegInfo->needsStackRealignment(MF))
2853    return false;
2854
2855  // Also avoid sibcall optimization if either caller or callee uses struct
2856  // return semantics.
2857  if (isCalleeStructRet || isCallerStructRet)
2858    return false;
2859
2860  // An stdcall caller is expected to clean up its arguments; the callee
2861  // isn't going to do that.
2862  if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2863    return false;
2864
2865  // Do not sibcall optimize vararg calls unless all arguments are passed via
2866  // registers.
2867  if (isVarArg && !Outs.empty()) {
2868
2869    // Optimizing for varargs on Win64 is unlikely to be safe without
2870    // additional testing.
2871    if (Subtarget->isTargetWin64())
2872      return false;
2873
2874    SmallVector<CCValAssign, 16> ArgLocs;
2875    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2876                   getTargetMachine(), ArgLocs, *DAG.getContext());
2877
2878    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2879    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2880      if (!ArgLocs[i].isRegLoc())
2881        return false;
2882  }
2883
2884  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2885  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2886  // this into a sibcall.
2887  bool Unused = false;
2888  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2889    if (!Ins[i].Used) {
2890      Unused = true;
2891      break;
2892    }
2893  }
2894  if (Unused) {
2895    SmallVector<CCValAssign, 16> RVLocs;
2896    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2897                   getTargetMachine(), RVLocs, *DAG.getContext());
2898    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2899    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2900      CCValAssign &VA = RVLocs[i];
2901      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2902        return false;
2903    }
2904  }
2905
2906  // If the calling conventions do not match, then we'd better make sure the
2907  // results are returned in the same way as what the caller expects.
2908  if (!CCMatch) {
2909    SmallVector<CCValAssign, 16> RVLocs1;
2910    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2911                    getTargetMachine(), RVLocs1, *DAG.getContext());
2912    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2913
2914    SmallVector<CCValAssign, 16> RVLocs2;
2915    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2916                    getTargetMachine(), RVLocs2, *DAG.getContext());
2917    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2918
2919    if (RVLocs1.size() != RVLocs2.size())
2920      return false;
2921    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2922      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2923        return false;
2924      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2925        return false;
2926      if (RVLocs1[i].isRegLoc()) {
2927        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2928          return false;
2929      } else {
2930        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2931          return false;
2932      }
2933    }
2934  }
2935
2936  // If the callee takes no arguments then go on to check the results of the
2937  // call.
2938  if (!Outs.empty()) {
2939    // Check if stack adjustment is needed. For now, do not do this if any
2940    // argument is passed on the stack.
2941    SmallVector<CCValAssign, 16> ArgLocs;
2942    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2943                   getTargetMachine(), ArgLocs, *DAG.getContext());
2944
2945    // Allocate shadow area for Win64
2946    if (Subtarget->isTargetWin64()) {
2947      CCInfo.AllocateStack(32, 8);
2948    }
2949
2950    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2951    if (CCInfo.getNextStackOffset()) {
2952      MachineFunction &MF = DAG.getMachineFunction();
2953      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2954        return false;
2955
2956      // Check if the arguments are already laid out in the right way as
2957      // the caller's fixed stack objects.
2958      MachineFrameInfo *MFI = MF.getFrameInfo();
2959      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2960      const X86InstrInfo *TII =
2961        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2962      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2963        CCValAssign &VA = ArgLocs[i];
2964        SDValue Arg = OutVals[i];
2965        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2966        if (VA.getLocInfo() == CCValAssign::Indirect)
2967          return false;
2968        if (!VA.isRegLoc()) {
2969          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2970                                   MFI, MRI, TII))
2971            return false;
2972        }
2973      }
2974    }
2975
2976    // If the tailcall address may be in a register, then make sure it's
2977    // possible to register allocate for it. In 32-bit, the call address can
2978    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2979    // callee-saved registers are restored. These happen to be the same
2980    // registers used to pass 'inreg' arguments so watch out for those.
2981    if (!Subtarget->is64Bit() &&
2982        ((!isa<GlobalAddressSDNode>(Callee) &&
2983          !isa<ExternalSymbolSDNode>(Callee)) ||
2984         getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2985      unsigned NumInRegs = 0;
2986      // In PIC we need an extra register to formulate the address computation
2987      // for the callee.
2988      unsigned MaxInRegs =
2989          (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
2990
2991      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2992        CCValAssign &VA = ArgLocs[i];
2993        if (!VA.isRegLoc())
2994          continue;
2995        unsigned Reg = VA.getLocReg();
2996        switch (Reg) {
2997        default: break;
2998        case X86::EAX: case X86::EDX: case X86::ECX:
2999          if (++NumInRegs == MaxInRegs)
3000            return false;
3001          break;
3002        }
3003      }
3004    }
3005  }
3006
3007  return true;
3008}
3009
3010FastISel *
3011X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3012                                  const TargetLibraryInfo *libInfo) const {
3013  return X86::createFastISel(funcInfo, libInfo);
3014}
3015
3016//===----------------------------------------------------------------------===//
3017//                           Other Lowering Hooks
3018//===----------------------------------------------------------------------===//
3019
3020static bool MayFoldLoad(SDValue Op) {
3021  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3022}
3023
3024static bool MayFoldIntoStore(SDValue Op) {
3025  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3026}
3027
3028static bool isTargetShuffle(unsigned Opcode) {
3029  switch(Opcode) {
3030  default: return false;
3031  case X86ISD::PSHUFD:
3032  case X86ISD::PSHUFHW:
3033  case X86ISD::PSHUFLW:
3034  case X86ISD::SHUFP:
3035  case X86ISD::PALIGNR:
3036  case X86ISD::MOVLHPS:
3037  case X86ISD::MOVLHPD:
3038  case X86ISD::MOVHLPS:
3039  case X86ISD::MOVLPS:
3040  case X86ISD::MOVLPD:
3041  case X86ISD::MOVSHDUP:
3042  case X86ISD::MOVSLDUP:
3043  case X86ISD::MOVDDUP:
3044  case X86ISD::MOVSS:
3045  case X86ISD::MOVSD:
3046  case X86ISD::UNPCKL:
3047  case X86ISD::UNPCKH:
3048  case X86ISD::VPERMILP:
3049  case X86ISD::VPERM2X128:
3050  case X86ISD::VPERMI:
3051    return true;
3052  }
3053}
3054
3055static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3056                                    SDValue V1, SelectionDAG &DAG) {
3057  switch(Opc) {
3058  default: llvm_unreachable("Unknown x86 shuffle node");
3059  case X86ISD::MOVSHDUP:
3060  case X86ISD::MOVSLDUP:
3061  case X86ISD::MOVDDUP:
3062    return DAG.getNode(Opc, dl, VT, V1);
3063  }
3064}
3065
3066static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3067                                    SDValue V1, unsigned TargetMask,
3068                                    SelectionDAG &DAG) {
3069  switch(Opc) {
3070  default: llvm_unreachable("Unknown x86 shuffle node");
3071  case X86ISD::PSHUFD:
3072  case X86ISD::PSHUFHW:
3073  case X86ISD::PSHUFLW:
3074  case X86ISD::VPERMILP:
3075  case X86ISD::VPERMI:
3076    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3077  }
3078}
3079
3080static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3081                                    SDValue V1, SDValue V2, unsigned TargetMask,
3082                                    SelectionDAG &DAG) {
3083  switch(Opc) {
3084  default: llvm_unreachable("Unknown x86 shuffle node");
3085  case X86ISD::PALIGNR:
3086  case X86ISD::SHUFP:
3087  case X86ISD::VPERM2X128:
3088    return DAG.getNode(Opc, dl, VT, V1, V2,
3089                       DAG.getConstant(TargetMask, MVT::i8));
3090  }
3091}
3092
3093static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3094                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
3095  switch(Opc) {
3096  default: llvm_unreachable("Unknown x86 shuffle node");
3097  case X86ISD::MOVLHPS:
3098  case X86ISD::MOVLHPD:
3099  case X86ISD::MOVHLPS:
3100  case X86ISD::MOVLPS:
3101  case X86ISD::MOVLPD:
3102  case X86ISD::MOVSS:
3103  case X86ISD::MOVSD:
3104  case X86ISD::UNPCKL:
3105  case X86ISD::UNPCKH:
3106    return DAG.getNode(Opc, dl, VT, V1, V2);
3107  }
3108}
3109
3110SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3111  MachineFunction &MF = DAG.getMachineFunction();
3112  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3113  int ReturnAddrIndex = FuncInfo->getRAIndex();
3114
3115  if (ReturnAddrIndex == 0) {
3116    // Set up a frame object for the return address.
3117    unsigned SlotSize = RegInfo->getSlotSize();
3118    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3119                                                           false);
3120    FuncInfo->setRAIndex(ReturnAddrIndex);
3121  }
3122
3123  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3124}
3125
3126bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3127                                       bool hasSymbolicDisplacement) {
3128  // Offset should fit into 32 bit immediate field.
3129  if (!isInt<32>(Offset))
3130    return false;
3131
3132  // If we don't have a symbolic displacement - we don't have any extra
3133  // restrictions.
3134  if (!hasSymbolicDisplacement)
3135    return true;
3136
3137  // FIXME: Some tweaks might be needed for medium code model.
3138  if (M != CodeModel::Small && M != CodeModel::Kernel)
3139    return false;
3140
3141  // For small code model we assume that latest object is 16MB before end of 31
3142  // bits boundary. We may also accept pretty large negative constants knowing
3143  // that all objects are in the positive half of address space.
3144  if (M == CodeModel::Small && Offset < 16*1024*1024)
3145    return true;
3146
3147  // For kernel code model we know that all object resist in the negative half
3148  // of 32bits address space. We may not accept negative offsets, since they may
3149  // be just off and we may accept pretty large positive ones.
3150  if (M == CodeModel::Kernel && Offset > 0)
3151    return true;
3152
3153  return false;
3154}
3155
3156/// isCalleePop - Determines whether the callee is required to pop its
3157/// own arguments. Callee pop is necessary to support tail calls.
3158bool X86::isCalleePop(CallingConv::ID CallingConv,
3159                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3160  if (IsVarArg)
3161    return false;
3162
3163  switch (CallingConv) {
3164  default:
3165    return false;
3166  case CallingConv::X86_StdCall:
3167    return !is64Bit;
3168  case CallingConv::X86_FastCall:
3169    return !is64Bit;
3170  case CallingConv::X86_ThisCall:
3171    return !is64Bit;
3172  case CallingConv::Fast:
3173    return TailCallOpt;
3174  case CallingConv::GHC:
3175    return TailCallOpt;
3176  case CallingConv::HiPE:
3177    return TailCallOpt;
3178  }
3179}
3180
3181/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3182/// specific condition code, returning the condition code and the LHS/RHS of the
3183/// comparison to make.
3184static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3185                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3186  if (!isFP) {
3187    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3188      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3189        // X > -1   -> X == 0, jump !sign.
3190        RHS = DAG.getConstant(0, RHS.getValueType());
3191        return X86::COND_NS;
3192      }
3193      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3194        // X < 0   -> X == 0, jump on sign.
3195        return X86::COND_S;
3196      }
3197      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3198        // X < 1   -> X <= 0
3199        RHS = DAG.getConstant(0, RHS.getValueType());
3200        return X86::COND_LE;
3201      }
3202    }
3203
3204    switch (SetCCOpcode) {
3205    default: llvm_unreachable("Invalid integer condition!");
3206    case ISD::SETEQ:  return X86::COND_E;
3207    case ISD::SETGT:  return X86::COND_G;
3208    case ISD::SETGE:  return X86::COND_GE;
3209    case ISD::SETLT:  return X86::COND_L;
3210    case ISD::SETLE:  return X86::COND_LE;
3211    case ISD::SETNE:  return X86::COND_NE;
3212    case ISD::SETULT: return X86::COND_B;
3213    case ISD::SETUGT: return X86::COND_A;
3214    case ISD::SETULE: return X86::COND_BE;
3215    case ISD::SETUGE: return X86::COND_AE;
3216    }
3217  }
3218
3219  // First determine if it is required or is profitable to flip the operands.
3220
3221  // If LHS is a foldable load, but RHS is not, flip the condition.
3222  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3223      !ISD::isNON_EXTLoad(RHS.getNode())) {
3224    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3225    std::swap(LHS, RHS);
3226  }
3227
3228  switch (SetCCOpcode) {
3229  default: break;
3230  case ISD::SETOLT:
3231  case ISD::SETOLE:
3232  case ISD::SETUGT:
3233  case ISD::SETUGE:
3234    std::swap(LHS, RHS);
3235    break;
3236  }
3237
3238  // On a floating point condition, the flags are set as follows:
3239  // ZF  PF  CF   op
3240  //  0 | 0 | 0 | X > Y
3241  //  0 | 0 | 1 | X < Y
3242  //  1 | 0 | 0 | X == Y
3243  //  1 | 1 | 1 | unordered
3244  switch (SetCCOpcode) {
3245  default: llvm_unreachable("Condcode should be pre-legalized away");
3246  case ISD::SETUEQ:
3247  case ISD::SETEQ:   return X86::COND_E;
3248  case ISD::SETOLT:              // flipped
3249  case ISD::SETOGT:
3250  case ISD::SETGT:   return X86::COND_A;
3251  case ISD::SETOLE:              // flipped
3252  case ISD::SETOGE:
3253  case ISD::SETGE:   return X86::COND_AE;
3254  case ISD::SETUGT:              // flipped
3255  case ISD::SETULT:
3256  case ISD::SETLT:   return X86::COND_B;
3257  case ISD::SETUGE:              // flipped
3258  case ISD::SETULE:
3259  case ISD::SETLE:   return X86::COND_BE;
3260  case ISD::SETONE:
3261  case ISD::SETNE:   return X86::COND_NE;
3262  case ISD::SETUO:   return X86::COND_P;
3263  case ISD::SETO:    return X86::COND_NP;
3264  case ISD::SETOEQ:
3265  case ISD::SETUNE:  return X86::COND_INVALID;
3266  }
3267}
3268
3269/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3270/// code. Current x86 isa includes the following FP cmov instructions:
3271/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3272static bool hasFPCMov(unsigned X86CC) {
3273  switch (X86CC) {
3274  default:
3275    return false;
3276  case X86::COND_B:
3277  case X86::COND_BE:
3278  case X86::COND_E:
3279  case X86::COND_P:
3280  case X86::COND_A:
3281  case X86::COND_AE:
3282  case X86::COND_NE:
3283  case X86::COND_NP:
3284    return true;
3285  }
3286}
3287
3288/// isFPImmLegal - Returns true if the target can instruction select the
3289/// specified FP immediate natively. If false, the legalizer will
3290/// materialize the FP immediate as a load from a constant pool.
3291bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3292  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3293    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3294      return true;
3295  }
3296  return false;
3297}
3298
3299/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3300/// the specified range (L, H].
3301static bool isUndefOrInRange(int Val, int Low, int Hi) {
3302  return (Val < 0) || (Val >= Low && Val < Hi);
3303}
3304
3305/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3306/// specified value.
3307static bool isUndefOrEqual(int Val, int CmpVal) {
3308  return (Val < 0 || Val == CmpVal);
3309}
3310
3311/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3312/// from position Pos and ending in Pos+Size, falls within the specified
3313/// sequential range (L, L+Pos]. or is undef.
3314static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3315                                       unsigned Pos, unsigned Size, int Low) {
3316  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3317    if (!isUndefOrEqual(Mask[i], Low))
3318      return false;
3319  return true;
3320}
3321
3322/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3323/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3324/// the second operand.
3325static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3326  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3327    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3328  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3329    return (Mask[0] < 2 && Mask[1] < 2);
3330  return false;
3331}
3332
3333/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3334/// is suitable for input to PSHUFHW.
3335static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3336  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3337    return false;
3338
3339  // Lower quadword copied in order or undef.
3340  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3341    return false;
3342
3343  // Upper quadword shuffled.
3344  for (unsigned i = 4; i != 8; ++i)
3345    if (!isUndefOrInRange(Mask[i], 4, 8))
3346      return false;
3347
3348  if (VT == MVT::v16i16) {
3349    // Lower quadword copied in order or undef.
3350    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3351      return false;
3352
3353    // Upper quadword shuffled.
3354    for (unsigned i = 12; i != 16; ++i)
3355      if (!isUndefOrInRange(Mask[i], 12, 16))
3356        return false;
3357  }
3358
3359  return true;
3360}
3361
3362/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3363/// is suitable for input to PSHUFLW.
3364static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3365  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3366    return false;
3367
3368  // Upper quadword copied in order.
3369  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3370    return false;
3371
3372  // Lower quadword shuffled.
3373  for (unsigned i = 0; i != 4; ++i)
3374    if (!isUndefOrInRange(Mask[i], 0, 4))
3375      return false;
3376
3377  if (VT == MVT::v16i16) {
3378    // Upper quadword copied in order.
3379    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3380      return false;
3381
3382    // Lower quadword shuffled.
3383    for (unsigned i = 8; i != 12; ++i)
3384      if (!isUndefOrInRange(Mask[i], 8, 12))
3385        return false;
3386  }
3387
3388  return true;
3389}
3390
3391/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3392/// is suitable for input to PALIGNR.
3393static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3394                          const X86Subtarget *Subtarget) {
3395  if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3396      (VT.is256BitVector() && !Subtarget->hasInt256()))
3397    return false;
3398
3399  unsigned NumElts = VT.getVectorNumElements();
3400  unsigned NumLanes = VT.getSizeInBits()/128;
3401  unsigned NumLaneElts = NumElts/NumLanes;
3402
3403  // Do not handle 64-bit element shuffles with palignr.
3404  if (NumLaneElts == 2)
3405    return false;
3406
3407  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3408    unsigned i;
3409    for (i = 0; i != NumLaneElts; ++i) {
3410      if (Mask[i+l] >= 0)
3411        break;
3412    }
3413
3414    // Lane is all undef, go to next lane
3415    if (i == NumLaneElts)
3416      continue;
3417
3418    int Start = Mask[i+l];
3419
3420    // Make sure its in this lane in one of the sources
3421    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3422        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3423      return false;
3424
3425    // If not lane 0, then we must match lane 0
3426    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3427      return false;
3428
3429    // Correct second source to be contiguous with first source
3430    if (Start >= (int)NumElts)
3431      Start -= NumElts - NumLaneElts;
3432
3433    // Make sure we're shifting in the right direction.
3434    if (Start <= (int)(i+l))
3435      return false;
3436
3437    Start -= i;
3438
3439    // Check the rest of the elements to see if they are consecutive.
3440    for (++i; i != NumLaneElts; ++i) {
3441      int Idx = Mask[i+l];
3442
3443      // Make sure its in this lane
3444      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3445          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3446        return false;
3447
3448      // If not lane 0, then we must match lane 0
3449      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3450        return false;
3451
3452      if (Idx >= (int)NumElts)
3453        Idx -= NumElts - NumLaneElts;
3454
3455      if (!isUndefOrEqual(Idx, Start+i))
3456        return false;
3457
3458    }
3459  }
3460
3461  return true;
3462}
3463
3464/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3465/// the two vector operands have swapped position.
3466static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3467                                     unsigned NumElems) {
3468  for (unsigned i = 0; i != NumElems; ++i) {
3469    int idx = Mask[i];
3470    if (idx < 0)
3471      continue;
3472    else if (idx < (int)NumElems)
3473      Mask[i] = idx + NumElems;
3474    else
3475      Mask[i] = idx - NumElems;
3476  }
3477}
3478
3479/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3480/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3481/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3482/// reverse of what x86 shuffles want.
3483static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3484                        bool Commuted = false) {
3485  if (!HasFp256 && VT.is256BitVector())
3486    return false;
3487
3488  unsigned NumElems = VT.getVectorNumElements();
3489  unsigned NumLanes = VT.getSizeInBits()/128;
3490  unsigned NumLaneElems = NumElems/NumLanes;
3491
3492  if (NumLaneElems != 2 && NumLaneElems != 4)
3493    return false;
3494
3495  // VSHUFPSY divides the resulting vector into 4 chunks.
3496  // The sources are also splitted into 4 chunks, and each destination
3497  // chunk must come from a different source chunk.
3498  //
3499  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3500  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3501  //
3502  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3503  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3504  //
3505  // VSHUFPDY divides the resulting vector into 4 chunks.
3506  // The sources are also splitted into 4 chunks, and each destination
3507  // chunk must come from a different source chunk.
3508  //
3509  //  SRC1 =>      X3       X2       X1       X0
3510  //  SRC2 =>      Y3       Y2       Y1       Y0
3511  //
3512  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3513  //
3514  unsigned HalfLaneElems = NumLaneElems/2;
3515  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3516    for (unsigned i = 0; i != NumLaneElems; ++i) {
3517      int Idx = Mask[i+l];
3518      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3519      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3520        return false;
3521      // For VSHUFPSY, the mask of the second half must be the same as the
3522      // first but with the appropriate offsets. This works in the same way as
3523      // VPERMILPS works with masks.
3524      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3525        continue;
3526      if (!isUndefOrEqual(Idx, Mask[i]+l))
3527        return false;
3528    }
3529  }
3530
3531  return true;
3532}
3533
3534/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3535/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3536static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3537  if (!VT.is128BitVector())
3538    return false;
3539
3540  unsigned NumElems = VT.getVectorNumElements();
3541
3542  if (NumElems != 4)
3543    return false;
3544
3545  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3546  return isUndefOrEqual(Mask[0], 6) &&
3547         isUndefOrEqual(Mask[1], 7) &&
3548         isUndefOrEqual(Mask[2], 2) &&
3549         isUndefOrEqual(Mask[3], 3);
3550}
3551
3552/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3553/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3554/// <2, 3, 2, 3>
3555static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3556  if (!VT.is128BitVector())
3557    return false;
3558
3559  unsigned NumElems = VT.getVectorNumElements();
3560
3561  if (NumElems != 4)
3562    return false;
3563
3564  return isUndefOrEqual(Mask[0], 2) &&
3565         isUndefOrEqual(Mask[1], 3) &&
3566         isUndefOrEqual(Mask[2], 2) &&
3567         isUndefOrEqual(Mask[3], 3);
3568}
3569
3570/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3571/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3572static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3573  if (!VT.is128BitVector())
3574    return false;
3575
3576  unsigned NumElems = VT.getVectorNumElements();
3577
3578  if (NumElems != 2 && NumElems != 4)
3579    return false;
3580
3581  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3582    if (!isUndefOrEqual(Mask[i], i + NumElems))
3583      return false;
3584
3585  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3586    if (!isUndefOrEqual(Mask[i], i))
3587      return false;
3588
3589  return true;
3590}
3591
3592/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3593/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3594static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3595  if (!VT.is128BitVector())
3596    return false;
3597
3598  unsigned NumElems = VT.getVectorNumElements();
3599
3600  if (NumElems != 2 && NumElems != 4)
3601    return false;
3602
3603  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3604    if (!isUndefOrEqual(Mask[i], i))
3605      return false;
3606
3607  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3608    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3609      return false;
3610
3611  return true;
3612}
3613
3614//
3615// Some special combinations that can be optimized.
3616//
3617static
3618SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3619                               SelectionDAG &DAG) {
3620  MVT VT = SVOp->getValueType(0).getSimpleVT();
3621  DebugLoc dl = SVOp->getDebugLoc();
3622
3623  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3624    return SDValue();
3625
3626  ArrayRef<int> Mask = SVOp->getMask();
3627
3628  // These are the special masks that may be optimized.
3629  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3630  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3631  bool MatchEvenMask = true;
3632  bool MatchOddMask  = true;
3633  for (int i=0; i<8; ++i) {
3634    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3635      MatchEvenMask = false;
3636    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3637      MatchOddMask = false;
3638  }
3639
3640  if (!MatchEvenMask && !MatchOddMask)
3641    return SDValue();
3642
3643  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3644
3645  SDValue Op0 = SVOp->getOperand(0);
3646  SDValue Op1 = SVOp->getOperand(1);
3647
3648  if (MatchEvenMask) {
3649    // Shift the second operand right to 32 bits.
3650    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3651    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3652  } else {
3653    // Shift the first operand left to 32 bits.
3654    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3655    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3656  }
3657  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3658  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3659}
3660
3661/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3662/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3663static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3664                         bool HasInt256, bool V2IsSplat = false) {
3665  unsigned NumElts = VT.getVectorNumElements();
3666
3667  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3668         "Unsupported vector type for unpckh");
3669
3670  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3671      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3672    return false;
3673
3674  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3675  // independently on 128-bit lanes.
3676  unsigned NumLanes = VT.getSizeInBits()/128;
3677  unsigned NumLaneElts = NumElts/NumLanes;
3678
3679  for (unsigned l = 0; l != NumLanes; ++l) {
3680    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3681         i != (l+1)*NumLaneElts;
3682         i += 2, ++j) {
3683      int BitI  = Mask[i];
3684      int BitI1 = Mask[i+1];
3685      if (!isUndefOrEqual(BitI, j))
3686        return false;
3687      if (V2IsSplat) {
3688        if (!isUndefOrEqual(BitI1, NumElts))
3689          return false;
3690      } else {
3691        if (!isUndefOrEqual(BitI1, j + NumElts))
3692          return false;
3693      }
3694    }
3695  }
3696
3697  return true;
3698}
3699
3700/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3701/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3702static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3703                         bool HasInt256, bool V2IsSplat = false) {
3704  unsigned NumElts = VT.getVectorNumElements();
3705
3706  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3707         "Unsupported vector type for unpckh");
3708
3709  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3710      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3711    return false;
3712
3713  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3714  // independently on 128-bit lanes.
3715  unsigned NumLanes = VT.getSizeInBits()/128;
3716  unsigned NumLaneElts = NumElts/NumLanes;
3717
3718  for (unsigned l = 0; l != NumLanes; ++l) {
3719    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3720         i != (l+1)*NumLaneElts; i += 2, ++j) {
3721      int BitI  = Mask[i];
3722      int BitI1 = Mask[i+1];
3723      if (!isUndefOrEqual(BitI, j))
3724        return false;
3725      if (V2IsSplat) {
3726        if (isUndefOrEqual(BitI1, NumElts))
3727          return false;
3728      } else {
3729        if (!isUndefOrEqual(BitI1, j+NumElts))
3730          return false;
3731      }
3732    }
3733  }
3734  return true;
3735}
3736
3737/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3738/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3739/// <0, 0, 1, 1>
3740static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3741  unsigned NumElts = VT.getVectorNumElements();
3742  bool Is256BitVec = VT.is256BitVector();
3743
3744  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3745         "Unsupported vector type for unpckh");
3746
3747  if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3748      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3749    return false;
3750
3751  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3752  // FIXME: Need a better way to get rid of this, there's no latency difference
3753  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3754  // the former later. We should also remove the "_undef" special mask.
3755  if (NumElts == 4 && Is256BitVec)
3756    return false;
3757
3758  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3759  // independently on 128-bit lanes.
3760  unsigned NumLanes = VT.getSizeInBits()/128;
3761  unsigned NumLaneElts = NumElts/NumLanes;
3762
3763  for (unsigned l = 0; l != NumLanes; ++l) {
3764    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3765         i != (l+1)*NumLaneElts;
3766         i += 2, ++j) {
3767      int BitI  = Mask[i];
3768      int BitI1 = Mask[i+1];
3769
3770      if (!isUndefOrEqual(BitI, j))
3771        return false;
3772      if (!isUndefOrEqual(BitI1, j))
3773        return false;
3774    }
3775  }
3776
3777  return true;
3778}
3779
3780/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3781/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3782/// <2, 2, 3, 3>
3783static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3784  unsigned NumElts = VT.getVectorNumElements();
3785
3786  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3787         "Unsupported vector type for unpckh");
3788
3789  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3790      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3791    return false;
3792
3793  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3794  // independently on 128-bit lanes.
3795  unsigned NumLanes = VT.getSizeInBits()/128;
3796  unsigned NumLaneElts = NumElts/NumLanes;
3797
3798  for (unsigned l = 0; l != NumLanes; ++l) {
3799    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3800         i != (l+1)*NumLaneElts; i += 2, ++j) {
3801      int BitI  = Mask[i];
3802      int BitI1 = Mask[i+1];
3803      if (!isUndefOrEqual(BitI, j))
3804        return false;
3805      if (!isUndefOrEqual(BitI1, j))
3806        return false;
3807    }
3808  }
3809  return true;
3810}
3811
3812/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3813/// specifies a shuffle of elements that is suitable for input to MOVSS,
3814/// MOVSD, and MOVD, i.e. setting the lowest element.
3815static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3816  if (VT.getVectorElementType().getSizeInBits() < 32)
3817    return false;
3818  if (!VT.is128BitVector())
3819    return false;
3820
3821  unsigned NumElts = VT.getVectorNumElements();
3822
3823  if (!isUndefOrEqual(Mask[0], NumElts))
3824    return false;
3825
3826  for (unsigned i = 1; i != NumElts; ++i)
3827    if (!isUndefOrEqual(Mask[i], i))
3828      return false;
3829
3830  return true;
3831}
3832
3833/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3834/// as permutations between 128-bit chunks or halves. As an example: this
3835/// shuffle bellow:
3836///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3837/// The first half comes from the second half of V1 and the second half from the
3838/// the second half of V2.
3839static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3840  if (!HasFp256 || !VT.is256BitVector())
3841    return false;
3842
3843  // The shuffle result is divided into half A and half B. In total the two
3844  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3845  // B must come from C, D, E or F.
3846  unsigned HalfSize = VT.getVectorNumElements()/2;
3847  bool MatchA = false, MatchB = false;
3848
3849  // Check if A comes from one of C, D, E, F.
3850  for (unsigned Half = 0; Half != 4; ++Half) {
3851    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3852      MatchA = true;
3853      break;
3854    }
3855  }
3856
3857  // Check if B comes from one of C, D, E, F.
3858  for (unsigned Half = 0; Half != 4; ++Half) {
3859    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3860      MatchB = true;
3861      break;
3862    }
3863  }
3864
3865  return MatchA && MatchB;
3866}
3867
3868/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3869/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3870static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3871  MVT VT = SVOp->getValueType(0).getSimpleVT();
3872
3873  unsigned HalfSize = VT.getVectorNumElements()/2;
3874
3875  unsigned FstHalf = 0, SndHalf = 0;
3876  for (unsigned i = 0; i < HalfSize; ++i) {
3877    if (SVOp->getMaskElt(i) > 0) {
3878      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3879      break;
3880    }
3881  }
3882  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3883    if (SVOp->getMaskElt(i) > 0) {
3884      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3885      break;
3886    }
3887  }
3888
3889  return (FstHalf | (SndHalf << 4));
3890}
3891
3892/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3893/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3894/// Note that VPERMIL mask matching is different depending whether theunderlying
3895/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3896/// to the same elements of the low, but to the higher half of the source.
3897/// In VPERMILPD the two lanes could be shuffled independently of each other
3898/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3899static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3900  if (!HasFp256)
3901    return false;
3902
3903  unsigned NumElts = VT.getVectorNumElements();
3904  // Only match 256-bit with 32/64-bit types
3905  if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3906    return false;
3907
3908  unsigned NumLanes = VT.getSizeInBits()/128;
3909  unsigned LaneSize = NumElts/NumLanes;
3910  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3911    for (unsigned i = 0; i != LaneSize; ++i) {
3912      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3913        return false;
3914      if (NumElts != 8 || l == 0)
3915        continue;
3916      // VPERMILPS handling
3917      if (Mask[i] < 0)
3918        continue;
3919      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3920        return false;
3921    }
3922  }
3923
3924  return true;
3925}
3926
3927/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3928/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3929/// element of vector 2 and the other elements to come from vector 1 in order.
3930static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3931                               bool V2IsSplat = false, bool V2IsUndef = false) {
3932  if (!VT.is128BitVector())
3933    return false;
3934
3935  unsigned NumOps = VT.getVectorNumElements();
3936  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3937    return false;
3938
3939  if (!isUndefOrEqual(Mask[0], 0))
3940    return false;
3941
3942  for (unsigned i = 1; i != NumOps; ++i)
3943    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3944          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3945          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3946      return false;
3947
3948  return true;
3949}
3950
3951/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3952/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3953/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3954static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3955                           const X86Subtarget *Subtarget) {
3956  if (!Subtarget->hasSSE3())
3957    return false;
3958
3959  unsigned NumElems = VT.getVectorNumElements();
3960
3961  if ((VT.is128BitVector() && NumElems != 4) ||
3962      (VT.is256BitVector() && NumElems != 8))
3963    return false;
3964
3965  // "i+1" is the value the indexed mask element must have
3966  for (unsigned i = 0; i != NumElems; i += 2)
3967    if (!isUndefOrEqual(Mask[i], i+1) ||
3968        !isUndefOrEqual(Mask[i+1], i+1))
3969      return false;
3970
3971  return true;
3972}
3973
3974/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3975/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3976/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3977static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3978                           const X86Subtarget *Subtarget) {
3979  if (!Subtarget->hasSSE3())
3980    return false;
3981
3982  unsigned NumElems = VT.getVectorNumElements();
3983
3984  if ((VT.is128BitVector() && NumElems != 4) ||
3985      (VT.is256BitVector() && NumElems != 8))
3986    return false;
3987
3988  // "i" is the value the indexed mask element must have
3989  for (unsigned i = 0; i != NumElems; i += 2)
3990    if (!isUndefOrEqual(Mask[i], i) ||
3991        !isUndefOrEqual(Mask[i+1], i))
3992      return false;
3993
3994  return true;
3995}
3996
3997/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3998/// specifies a shuffle of elements that is suitable for input to 256-bit
3999/// version of MOVDDUP.
4000static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4001  if (!HasFp256 || !VT.is256BitVector())
4002    return false;
4003
4004  unsigned NumElts = VT.getVectorNumElements();
4005  if (NumElts != 4)
4006    return false;
4007
4008  for (unsigned i = 0; i != NumElts/2; ++i)
4009    if (!isUndefOrEqual(Mask[i], 0))
4010      return false;
4011  for (unsigned i = NumElts/2; i != NumElts; ++i)
4012    if (!isUndefOrEqual(Mask[i], NumElts/2))
4013      return false;
4014  return true;
4015}
4016
4017/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4018/// specifies a shuffle of elements that is suitable for input to 128-bit
4019/// version of MOVDDUP.
4020static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4021  if (!VT.is128BitVector())
4022    return false;
4023
4024  unsigned e = VT.getVectorNumElements() / 2;
4025  for (unsigned i = 0; i != e; ++i)
4026    if (!isUndefOrEqual(Mask[i], i))
4027      return false;
4028  for (unsigned i = 0; i != e; ++i)
4029    if (!isUndefOrEqual(Mask[e+i], i))
4030      return false;
4031  return true;
4032}
4033
4034/// isVEXTRACTF128Index - Return true if the specified
4035/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4036/// suitable for input to VEXTRACTF128.
4037bool X86::isVEXTRACTF128Index(SDNode *N) {
4038  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4039    return false;
4040
4041  // The index should be aligned on a 128-bit boundary.
4042  uint64_t Index =
4043    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4044
4045  MVT VT = N->getValueType(0).getSimpleVT();
4046  unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4047  bool Result = (Index * ElSize) % 128 == 0;
4048
4049  return Result;
4050}
4051
4052/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4053/// operand specifies a subvector insert that is suitable for input to
4054/// VINSERTF128.
4055bool X86::isVINSERTF128Index(SDNode *N) {
4056  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4057    return false;
4058
4059  // The index should be aligned on a 128-bit boundary.
4060  uint64_t Index =
4061    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4062
4063  MVT VT = N->getValueType(0).getSimpleVT();
4064  unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4065  bool Result = (Index * ElSize) % 128 == 0;
4066
4067  return Result;
4068}
4069
4070/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4071/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4072/// Handles 128-bit and 256-bit.
4073static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4074  MVT VT = N->getValueType(0).getSimpleVT();
4075
4076  assert((VT.is128BitVector() || VT.is256BitVector()) &&
4077         "Unsupported vector type for PSHUF/SHUFP");
4078
4079  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4080  // independently on 128-bit lanes.
4081  unsigned NumElts = VT.getVectorNumElements();
4082  unsigned NumLanes = VT.getSizeInBits()/128;
4083  unsigned NumLaneElts = NumElts/NumLanes;
4084
4085  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4086         "Only supports 2 or 4 elements per lane");
4087
4088  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4089  unsigned Mask = 0;
4090  for (unsigned i = 0; i != NumElts; ++i) {
4091    int Elt = N->getMaskElt(i);
4092    if (Elt < 0) continue;
4093    Elt &= NumLaneElts - 1;
4094    unsigned ShAmt = (i << Shift) % 8;
4095    Mask |= Elt << ShAmt;
4096  }
4097
4098  return Mask;
4099}
4100
4101/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4102/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4103static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4104  MVT VT = N->getValueType(0).getSimpleVT();
4105
4106  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4107         "Unsupported vector type for PSHUFHW");
4108
4109  unsigned NumElts = VT.getVectorNumElements();
4110
4111  unsigned Mask = 0;
4112  for (unsigned l = 0; l != NumElts; l += 8) {
4113    // 8 nodes per lane, but we only care about the last 4.
4114    for (unsigned i = 0; i < 4; ++i) {
4115      int Elt = N->getMaskElt(l+i+4);
4116      if (Elt < 0) continue;
4117      Elt &= 0x3; // only 2-bits.
4118      Mask |= Elt << (i * 2);
4119    }
4120  }
4121
4122  return Mask;
4123}
4124
4125/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4126/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4127static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4128  MVT VT = N->getValueType(0).getSimpleVT();
4129
4130  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4131         "Unsupported vector type for PSHUFHW");
4132
4133  unsigned NumElts = VT.getVectorNumElements();
4134
4135  unsigned Mask = 0;
4136  for (unsigned l = 0; l != NumElts; l += 8) {
4137    // 8 nodes per lane, but we only care about the first 4.
4138    for (unsigned i = 0; i < 4; ++i) {
4139      int Elt = N->getMaskElt(l+i);
4140      if (Elt < 0) continue;
4141      Elt &= 0x3; // only 2-bits
4142      Mask |= Elt << (i * 2);
4143    }
4144  }
4145
4146  return Mask;
4147}
4148
4149/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4150/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4151static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4152  MVT VT = SVOp->getValueType(0).getSimpleVT();
4153  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4154
4155  unsigned NumElts = VT.getVectorNumElements();
4156  unsigned NumLanes = VT.getSizeInBits()/128;
4157  unsigned NumLaneElts = NumElts/NumLanes;
4158
4159  int Val = 0;
4160  unsigned i;
4161  for (i = 0; i != NumElts; ++i) {
4162    Val = SVOp->getMaskElt(i);
4163    if (Val >= 0)
4164      break;
4165  }
4166  if (Val >= (int)NumElts)
4167    Val -= NumElts - NumLaneElts;
4168
4169  assert(Val - i > 0 && "PALIGNR imm should be positive");
4170  return (Val - i) * EltSize;
4171}
4172
4173/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4174/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4175/// instructions.
4176unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4177  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4178    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4179
4180  uint64_t Index =
4181    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4182
4183  MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4184  MVT ElVT = VecVT.getVectorElementType();
4185
4186  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4187  return Index / NumElemsPerChunk;
4188}
4189
4190/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4191/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4192/// instructions.
4193unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4194  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4195    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4196
4197  uint64_t Index =
4198    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4199
4200  MVT VecVT = N->getValueType(0).getSimpleVT();
4201  MVT ElVT = VecVT.getVectorElementType();
4202
4203  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4204  return Index / NumElemsPerChunk;
4205}
4206
4207/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4208/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4209/// Handles 256-bit.
4210static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4211  MVT VT = N->getValueType(0).getSimpleVT();
4212
4213  unsigned NumElts = VT.getVectorNumElements();
4214
4215  assert((VT.is256BitVector() && NumElts == 4) &&
4216         "Unsupported vector type for VPERMQ/VPERMPD");
4217
4218  unsigned Mask = 0;
4219  for (unsigned i = 0; i != NumElts; ++i) {
4220    int Elt = N->getMaskElt(i);
4221    if (Elt < 0)
4222      continue;
4223    Mask |= Elt << (i*2);
4224  }
4225
4226  return Mask;
4227}
4228/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4229/// constant +0.0.
4230bool X86::isZeroNode(SDValue Elt) {
4231  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4232    return CN->isNullValue();
4233  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4234    return CFP->getValueAPF().isPosZero();
4235  return false;
4236}
4237
4238/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4239/// their permute mask.
4240static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4241                                    SelectionDAG &DAG) {
4242  MVT VT = SVOp->getValueType(0).getSimpleVT();
4243  unsigned NumElems = VT.getVectorNumElements();
4244  SmallVector<int, 8> MaskVec;
4245
4246  for (unsigned i = 0; i != NumElems; ++i) {
4247    int Idx = SVOp->getMaskElt(i);
4248    if (Idx >= 0) {
4249      if (Idx < (int)NumElems)
4250        Idx += NumElems;
4251      else
4252        Idx -= NumElems;
4253    }
4254    MaskVec.push_back(Idx);
4255  }
4256  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4257                              SVOp->getOperand(0), &MaskVec[0]);
4258}
4259
4260/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4261/// match movhlps. The lower half elements should come from upper half of
4262/// V1 (and in order), and the upper half elements should come from the upper
4263/// half of V2 (and in order).
4264static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4265  if (!VT.is128BitVector())
4266    return false;
4267  if (VT.getVectorNumElements() != 4)
4268    return false;
4269  for (unsigned i = 0, e = 2; i != e; ++i)
4270    if (!isUndefOrEqual(Mask[i], i+2))
4271      return false;
4272  for (unsigned i = 2; i != 4; ++i)
4273    if (!isUndefOrEqual(Mask[i], i+4))
4274      return false;
4275  return true;
4276}
4277
4278/// isScalarLoadToVector - Returns true if the node is a scalar load that
4279/// is promoted to a vector. It also returns the LoadSDNode by reference if
4280/// required.
4281static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4282  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4283    return false;
4284  N = N->getOperand(0).getNode();
4285  if (!ISD::isNON_EXTLoad(N))
4286    return false;
4287  if (LD)
4288    *LD = cast<LoadSDNode>(N);
4289  return true;
4290}
4291
4292// Test whether the given value is a vector value which will be legalized
4293// into a load.
4294static bool WillBeConstantPoolLoad(SDNode *N) {
4295  if (N->getOpcode() != ISD::BUILD_VECTOR)
4296    return false;
4297
4298  // Check for any non-constant elements.
4299  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4300    switch (N->getOperand(i).getNode()->getOpcode()) {
4301    case ISD::UNDEF:
4302    case ISD::ConstantFP:
4303    case ISD::Constant:
4304      break;
4305    default:
4306      return false;
4307    }
4308
4309  // Vectors of all-zeros and all-ones are materialized with special
4310  // instructions rather than being loaded.
4311  return !ISD::isBuildVectorAllZeros(N) &&
4312         !ISD::isBuildVectorAllOnes(N);
4313}
4314
4315/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4316/// match movlp{s|d}. The lower half elements should come from lower half of
4317/// V1 (and in order), and the upper half elements should come from the upper
4318/// half of V2 (and in order). And since V1 will become the source of the
4319/// MOVLP, it must be either a vector load or a scalar load to vector.
4320static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4321                               ArrayRef<int> Mask, EVT VT) {
4322  if (!VT.is128BitVector())
4323    return false;
4324
4325  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4326    return false;
4327  // Is V2 is a vector load, don't do this transformation. We will try to use
4328  // load folding shufps op.
4329  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4330    return false;
4331
4332  unsigned NumElems = VT.getVectorNumElements();
4333
4334  if (NumElems != 2 && NumElems != 4)
4335    return false;
4336  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4337    if (!isUndefOrEqual(Mask[i], i))
4338      return false;
4339  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4340    if (!isUndefOrEqual(Mask[i], i+NumElems))
4341      return false;
4342  return true;
4343}
4344
4345/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4346/// all the same.
4347static bool isSplatVector(SDNode *N) {
4348  if (N->getOpcode() != ISD::BUILD_VECTOR)
4349    return false;
4350
4351  SDValue SplatValue = N->getOperand(0);
4352  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4353    if (N->getOperand(i) != SplatValue)
4354      return false;
4355  return true;
4356}
4357
4358/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4359/// to an zero vector.
4360/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4361static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4362  SDValue V1 = N->getOperand(0);
4363  SDValue V2 = N->getOperand(1);
4364  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4365  for (unsigned i = 0; i != NumElems; ++i) {
4366    int Idx = N->getMaskElt(i);
4367    if (Idx >= (int)NumElems) {
4368      unsigned Opc = V2.getOpcode();
4369      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4370        continue;
4371      if (Opc != ISD::BUILD_VECTOR ||
4372          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4373        return false;
4374    } else if (Idx >= 0) {
4375      unsigned Opc = V1.getOpcode();
4376      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4377        continue;
4378      if (Opc != ISD::BUILD_VECTOR ||
4379          !X86::isZeroNode(V1.getOperand(Idx)))
4380        return false;
4381    }
4382  }
4383  return true;
4384}
4385
4386/// getZeroVector - Returns a vector of specified type with all zero elements.
4387///
4388static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4389                             SelectionDAG &DAG, DebugLoc dl) {
4390  assert(VT.isVector() && "Expected a vector type");
4391
4392  // Always build SSE zero vectors as <4 x i32> bitcasted
4393  // to their dest type. This ensures they get CSE'd.
4394  SDValue Vec;
4395  if (VT.is128BitVector()) {  // SSE
4396    if (Subtarget->hasSSE2()) {  // SSE2
4397      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4398      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4399    } else { // SSE1
4400      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4401      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4402    }
4403  } else if (VT.is256BitVector()) { // AVX
4404    if (Subtarget->hasInt256()) { // AVX2
4405      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4406      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4407      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4408    } else {
4409      // 256-bit logic and arithmetic instructions in AVX are all
4410      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4411      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4412      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4413      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4414    }
4415  } else
4416    llvm_unreachable("Unexpected vector type");
4417
4418  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4419}
4420
4421/// getOnesVector - Returns a vector of specified type with all bits set.
4422/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4423/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4424/// Then bitcast to their original type, ensuring they get CSE'd.
4425static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4426                             DebugLoc dl) {
4427  assert(VT.isVector() && "Expected a vector type");
4428
4429  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4430  SDValue Vec;
4431  if (VT.is256BitVector()) {
4432    if (HasInt256) { // AVX2
4433      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4434      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4435    } else { // AVX
4436      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4437      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4438    }
4439  } else if (VT.is128BitVector()) {
4440    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4441  } else
4442    llvm_unreachable("Unexpected vector type");
4443
4444  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4445}
4446
4447/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4448/// that point to V2 points to its first element.
4449static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4450  for (unsigned i = 0; i != NumElems; ++i) {
4451    if (Mask[i] > (int)NumElems) {
4452      Mask[i] = NumElems;
4453    }
4454  }
4455}
4456
4457/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4458/// operation of specified width.
4459static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4460                       SDValue V2) {
4461  unsigned NumElems = VT.getVectorNumElements();
4462  SmallVector<int, 8> Mask;
4463  Mask.push_back(NumElems);
4464  for (unsigned i = 1; i != NumElems; ++i)
4465    Mask.push_back(i);
4466  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4467}
4468
4469/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4470static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4471                          SDValue V2) {
4472  unsigned NumElems = VT.getVectorNumElements();
4473  SmallVector<int, 8> Mask;
4474  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4475    Mask.push_back(i);
4476    Mask.push_back(i + NumElems);
4477  }
4478  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4479}
4480
4481/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4482static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4483                          SDValue V2) {
4484  unsigned NumElems = VT.getVectorNumElements();
4485  SmallVector<int, 8> Mask;
4486  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4487    Mask.push_back(i + Half);
4488    Mask.push_back(i + NumElems + Half);
4489  }
4490  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4491}
4492
4493// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4494// a generic shuffle instruction because the target has no such instructions.
4495// Generate shuffles which repeat i16 and i8 several times until they can be
4496// represented by v4f32 and then be manipulated by target suported shuffles.
4497static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4498  EVT VT = V.getValueType();
4499  int NumElems = VT.getVectorNumElements();
4500  DebugLoc dl = V.getDebugLoc();
4501
4502  while (NumElems > 4) {
4503    if (EltNo < NumElems/2) {
4504      V = getUnpackl(DAG, dl, VT, V, V);
4505    } else {
4506      V = getUnpackh(DAG, dl, VT, V, V);
4507      EltNo -= NumElems/2;
4508    }
4509    NumElems >>= 1;
4510  }
4511  return V;
4512}
4513
4514/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4515static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4516  EVT VT = V.getValueType();
4517  DebugLoc dl = V.getDebugLoc();
4518
4519  if (VT.is128BitVector()) {
4520    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4521    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4522    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4523                             &SplatMask[0]);
4524  } else if (VT.is256BitVector()) {
4525    // To use VPERMILPS to splat scalars, the second half of indicies must
4526    // refer to the higher part, which is a duplication of the lower one,
4527    // because VPERMILPS can only handle in-lane permutations.
4528    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4529                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4530
4531    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4532    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4533                             &SplatMask[0]);
4534  } else
4535    llvm_unreachable("Vector size not supported");
4536
4537  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4538}
4539
4540/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4541static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4542  EVT SrcVT = SV->getValueType(0);
4543  SDValue V1 = SV->getOperand(0);
4544  DebugLoc dl = SV->getDebugLoc();
4545
4546  int EltNo = SV->getSplatIndex();
4547  int NumElems = SrcVT.getVectorNumElements();
4548  bool Is256BitVec = SrcVT.is256BitVector();
4549
4550  assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4551         "Unknown how to promote splat for type");
4552
4553  // Extract the 128-bit part containing the splat element and update
4554  // the splat element index when it refers to the higher register.
4555  if (Is256BitVec) {
4556    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4557    if (EltNo >= NumElems/2)
4558      EltNo -= NumElems/2;
4559  }
4560
4561  // All i16 and i8 vector types can't be used directly by a generic shuffle
4562  // instruction because the target has no such instruction. Generate shuffles
4563  // which repeat i16 and i8 several times until they fit in i32, and then can
4564  // be manipulated by target suported shuffles.
4565  EVT EltVT = SrcVT.getVectorElementType();
4566  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4567    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4568
4569  // Recreate the 256-bit vector and place the same 128-bit vector
4570  // into the low and high part. This is necessary because we want
4571  // to use VPERM* to shuffle the vectors
4572  if (Is256BitVec) {
4573    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4574  }
4575
4576  return getLegalSplat(DAG, V1, EltNo);
4577}
4578
4579/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4580/// vector of zero or undef vector.  This produces a shuffle where the low
4581/// element of V2 is swizzled into the zero/undef vector, landing at element
4582/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4583static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4584                                           bool IsZero,
4585                                           const X86Subtarget *Subtarget,
4586                                           SelectionDAG &DAG) {
4587  EVT VT = V2.getValueType();
4588  SDValue V1 = IsZero
4589    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4590  unsigned NumElems = VT.getVectorNumElements();
4591  SmallVector<int, 16> MaskVec;
4592  for (unsigned i = 0; i != NumElems; ++i)
4593    // If this is the insertion idx, put the low elt of V2 here.
4594    MaskVec.push_back(i == Idx ? NumElems : i);
4595  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4596}
4597
4598/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4599/// target specific opcode. Returns true if the Mask could be calculated.
4600/// Sets IsUnary to true if only uses one source.
4601static bool getTargetShuffleMask(SDNode *N, MVT VT,
4602                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4603  unsigned NumElems = VT.getVectorNumElements();
4604  SDValue ImmN;
4605
4606  IsUnary = false;
4607  switch(N->getOpcode()) {
4608  case X86ISD::SHUFP:
4609    ImmN = N->getOperand(N->getNumOperands()-1);
4610    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611    break;
4612  case X86ISD::UNPCKH:
4613    DecodeUNPCKHMask(VT, Mask);
4614    break;
4615  case X86ISD::UNPCKL:
4616    DecodeUNPCKLMask(VT, Mask);
4617    break;
4618  case X86ISD::MOVHLPS:
4619    DecodeMOVHLPSMask(NumElems, Mask);
4620    break;
4621  case X86ISD::MOVLHPS:
4622    DecodeMOVLHPSMask(NumElems, Mask);
4623    break;
4624  case X86ISD::PALIGNR:
4625    ImmN = N->getOperand(N->getNumOperands()-1);
4626    DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4627    break;
4628  case X86ISD::PSHUFD:
4629  case X86ISD::VPERMILP:
4630    ImmN = N->getOperand(N->getNumOperands()-1);
4631    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632    IsUnary = true;
4633    break;
4634  case X86ISD::PSHUFHW:
4635    ImmN = N->getOperand(N->getNumOperands()-1);
4636    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4637    IsUnary = true;
4638    break;
4639  case X86ISD::PSHUFLW:
4640    ImmN = N->getOperand(N->getNumOperands()-1);
4641    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4642    IsUnary = true;
4643    break;
4644  case X86ISD::VPERMI:
4645    ImmN = N->getOperand(N->getNumOperands()-1);
4646    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4647    IsUnary = true;
4648    break;
4649  case X86ISD::MOVSS:
4650  case X86ISD::MOVSD: {
4651    // The index 0 always comes from the first element of the second source,
4652    // this is why MOVSS and MOVSD are used in the first place. The other
4653    // elements come from the other positions of the first source vector
4654    Mask.push_back(NumElems);
4655    for (unsigned i = 1; i != NumElems; ++i) {
4656      Mask.push_back(i);
4657    }
4658    break;
4659  }
4660  case X86ISD::VPERM2X128:
4661    ImmN = N->getOperand(N->getNumOperands()-1);
4662    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4663    if (Mask.empty()) return false;
4664    break;
4665  case X86ISD::MOVDDUP:
4666  case X86ISD::MOVLHPD:
4667  case X86ISD::MOVLPD:
4668  case X86ISD::MOVLPS:
4669  case X86ISD::MOVSHDUP:
4670  case X86ISD::MOVSLDUP:
4671    // Not yet implemented
4672    return false;
4673  default: llvm_unreachable("unknown target shuffle node");
4674  }
4675
4676  return true;
4677}
4678
4679/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4680/// element of the result of the vector shuffle.
4681static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4682                                   unsigned Depth) {
4683  if (Depth == 6)
4684    return SDValue();  // Limit search depth.
4685
4686  SDValue V = SDValue(N, 0);
4687  EVT VT = V.getValueType();
4688  unsigned Opcode = V.getOpcode();
4689
4690  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4691  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4692    int Elt = SV->getMaskElt(Index);
4693
4694    if (Elt < 0)
4695      return DAG.getUNDEF(VT.getVectorElementType());
4696
4697    unsigned NumElems = VT.getVectorNumElements();
4698    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4699                                         : SV->getOperand(1);
4700    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4701  }
4702
4703  // Recurse into target specific vector shuffles to find scalars.
4704  if (isTargetShuffle(Opcode)) {
4705    MVT ShufVT = V.getValueType().getSimpleVT();
4706    unsigned NumElems = ShufVT.getVectorNumElements();
4707    SmallVector<int, 16> ShuffleMask;
4708    bool IsUnary;
4709
4710    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4711      return SDValue();
4712
4713    int Elt = ShuffleMask[Index];
4714    if (Elt < 0)
4715      return DAG.getUNDEF(ShufVT.getVectorElementType());
4716
4717    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4718                                         : N->getOperand(1);
4719    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4720                               Depth+1);
4721  }
4722
4723  // Actual nodes that may contain scalar elements
4724  if (Opcode == ISD::BITCAST) {
4725    V = V.getOperand(0);
4726    EVT SrcVT = V.getValueType();
4727    unsigned NumElems = VT.getVectorNumElements();
4728
4729    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4730      return SDValue();
4731  }
4732
4733  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4734    return (Index == 0) ? V.getOperand(0)
4735                        : DAG.getUNDEF(VT.getVectorElementType());
4736
4737  if (V.getOpcode() == ISD::BUILD_VECTOR)
4738    return V.getOperand(Index);
4739
4740  return SDValue();
4741}
4742
4743/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4744/// shuffle operation which come from a consecutively from a zero. The
4745/// search can start in two different directions, from left or right.
4746static
4747unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4748                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4749  unsigned i;
4750  for (i = 0; i != NumElems; ++i) {
4751    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4752    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4753    if (!(Elt.getNode() &&
4754         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4755      break;
4756  }
4757
4758  return i;
4759}
4760
4761/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4762/// correspond consecutively to elements from one of the vector operands,
4763/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4764static
4765bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4766                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4767                              unsigned NumElems, unsigned &OpNum) {
4768  bool SeenV1 = false;
4769  bool SeenV2 = false;
4770
4771  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4772    int Idx = SVOp->getMaskElt(i);
4773    // Ignore undef indicies
4774    if (Idx < 0)
4775      continue;
4776
4777    if (Idx < (int)NumElems)
4778      SeenV1 = true;
4779    else
4780      SeenV2 = true;
4781
4782    // Only accept consecutive elements from the same vector
4783    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4784      return false;
4785  }
4786
4787  OpNum = SeenV1 ? 0 : 1;
4788  return true;
4789}
4790
4791/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4792/// logical left shift of a vector.
4793static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4794                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4795  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4796  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4797              false /* check zeros from right */, DAG);
4798  unsigned OpSrc;
4799
4800  if (!NumZeros)
4801    return false;
4802
4803  // Considering the elements in the mask that are not consecutive zeros,
4804  // check if they consecutively come from only one of the source vectors.
4805  //
4806  //               V1 = {X, A, B, C}     0
4807  //                         \  \  \    /
4808  //   vector_shuffle V1, V2 <1, 2, 3, X>
4809  //
4810  if (!isShuffleMaskConsecutive(SVOp,
4811            0,                   // Mask Start Index
4812            NumElems-NumZeros,   // Mask End Index(exclusive)
4813            NumZeros,            // Where to start looking in the src vector
4814            NumElems,            // Number of elements in vector
4815            OpSrc))              // Which source operand ?
4816    return false;
4817
4818  isLeft = false;
4819  ShAmt = NumZeros;
4820  ShVal = SVOp->getOperand(OpSrc);
4821  return true;
4822}
4823
4824/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4825/// logical left shift of a vector.
4826static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4827                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4828  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4829  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4830              true /* check zeros from left */, DAG);
4831  unsigned OpSrc;
4832
4833  if (!NumZeros)
4834    return false;
4835
4836  // Considering the elements in the mask that are not consecutive zeros,
4837  // check if they consecutively come from only one of the source vectors.
4838  //
4839  //                           0    { A, B, X, X } = V2
4840  //                          / \    /  /
4841  //   vector_shuffle V1, V2 <X, X, 4, 5>
4842  //
4843  if (!isShuffleMaskConsecutive(SVOp,
4844            NumZeros,     // Mask Start Index
4845            NumElems,     // Mask End Index(exclusive)
4846            0,            // Where to start looking in the src vector
4847            NumElems,     // Number of elements in vector
4848            OpSrc))       // Which source operand ?
4849    return false;
4850
4851  isLeft = true;
4852  ShAmt = NumZeros;
4853  ShVal = SVOp->getOperand(OpSrc);
4854  return true;
4855}
4856
4857/// isVectorShift - Returns true if the shuffle can be implemented as a
4858/// logical left or right shift of a vector.
4859static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4860                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4861  // Although the logic below support any bitwidth size, there are no
4862  // shift instructions which handle more than 128-bit vectors.
4863  if (!SVOp->getValueType(0).is128BitVector())
4864    return false;
4865
4866  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4867      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4868    return true;
4869
4870  return false;
4871}
4872
4873/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4874///
4875static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4876                                       unsigned NumNonZero, unsigned NumZero,
4877                                       SelectionDAG &DAG,
4878                                       const X86Subtarget* Subtarget,
4879                                       const TargetLowering &TLI) {
4880  if (NumNonZero > 8)
4881    return SDValue();
4882
4883  DebugLoc dl = Op.getDebugLoc();
4884  SDValue V(0, 0);
4885  bool First = true;
4886  for (unsigned i = 0; i < 16; ++i) {
4887    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4888    if (ThisIsNonZero && First) {
4889      if (NumZero)
4890        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4891      else
4892        V = DAG.getUNDEF(MVT::v8i16);
4893      First = false;
4894    }
4895
4896    if ((i & 1) != 0) {
4897      SDValue ThisElt(0, 0), LastElt(0, 0);
4898      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4899      if (LastIsNonZero) {
4900        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4901                              MVT::i16, Op.getOperand(i-1));
4902      }
4903      if (ThisIsNonZero) {
4904        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4905        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4906                              ThisElt, DAG.getConstant(8, MVT::i8));
4907        if (LastIsNonZero)
4908          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4909      } else
4910        ThisElt = LastElt;
4911
4912      if (ThisElt.getNode())
4913        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4914                        DAG.getIntPtrConstant(i/2));
4915    }
4916  }
4917
4918  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4919}
4920
4921/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4922///
4923static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4924                                     unsigned NumNonZero, unsigned NumZero,
4925                                     SelectionDAG &DAG,
4926                                     const X86Subtarget* Subtarget,
4927                                     const TargetLowering &TLI) {
4928  if (NumNonZero > 4)
4929    return SDValue();
4930
4931  DebugLoc dl = Op.getDebugLoc();
4932  SDValue V(0, 0);
4933  bool First = true;
4934  for (unsigned i = 0; i < 8; ++i) {
4935    bool isNonZero = (NonZeros & (1 << i)) != 0;
4936    if (isNonZero) {
4937      if (First) {
4938        if (NumZero)
4939          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4940        else
4941          V = DAG.getUNDEF(MVT::v8i16);
4942        First = false;
4943      }
4944      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4945                      MVT::v8i16, V, Op.getOperand(i),
4946                      DAG.getIntPtrConstant(i));
4947    }
4948  }
4949
4950  return V;
4951}
4952
4953/// getVShift - Return a vector logical shift node.
4954///
4955static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4956                         unsigned NumBits, SelectionDAG &DAG,
4957                         const TargetLowering &TLI, DebugLoc dl) {
4958  assert(VT.is128BitVector() && "Unknown type for VShift");
4959  EVT ShVT = MVT::v2i64;
4960  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4961  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4962  return DAG.getNode(ISD::BITCAST, dl, VT,
4963                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4964                             DAG.getConstant(NumBits,
4965                                  TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4966}
4967
4968SDValue
4969X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4970                                          SelectionDAG &DAG) const {
4971
4972  // Check if the scalar load can be widened into a vector load. And if
4973  // the address is "base + cst" see if the cst can be "absorbed" into
4974  // the shuffle mask.
4975  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4976    SDValue Ptr = LD->getBasePtr();
4977    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4978      return SDValue();
4979    EVT PVT = LD->getValueType(0);
4980    if (PVT != MVT::i32 && PVT != MVT::f32)
4981      return SDValue();
4982
4983    int FI = -1;
4984    int64_t Offset = 0;
4985    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4986      FI = FINode->getIndex();
4987      Offset = 0;
4988    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4989               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4990      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4991      Offset = Ptr.getConstantOperandVal(1);
4992      Ptr = Ptr.getOperand(0);
4993    } else {
4994      return SDValue();
4995    }
4996
4997    // FIXME: 256-bit vector instructions don't require a strict alignment,
4998    // improve this code to support it better.
4999    unsigned RequiredAlign = VT.getSizeInBits()/8;
5000    SDValue Chain = LD->getChain();
5001    // Make sure the stack object alignment is at least 16 or 32.
5002    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5003    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5004      if (MFI->isFixedObjectIndex(FI)) {
5005        // Can't change the alignment. FIXME: It's possible to compute
5006        // the exact stack offset and reference FI + adjust offset instead.
5007        // If someone *really* cares about this. That's the way to implement it.
5008        return SDValue();
5009      } else {
5010        MFI->setObjectAlignment(FI, RequiredAlign);
5011      }
5012    }
5013
5014    // (Offset % 16 or 32) must be multiple of 4. Then address is then
5015    // Ptr + (Offset & ~15).
5016    if (Offset < 0)
5017      return SDValue();
5018    if ((Offset % RequiredAlign) & 3)
5019      return SDValue();
5020    int64_t StartOffset = Offset & ~(RequiredAlign-1);
5021    if (StartOffset)
5022      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5023                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5024
5025    int EltNo = (Offset - StartOffset) >> 2;
5026    unsigned NumElems = VT.getVectorNumElements();
5027
5028    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5029    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5030                             LD->getPointerInfo().getWithOffset(StartOffset),
5031                             false, false, false, 0);
5032
5033    SmallVector<int, 8> Mask;
5034    for (unsigned i = 0; i != NumElems; ++i)
5035      Mask.push_back(EltNo);
5036
5037    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5038  }
5039
5040  return SDValue();
5041}
5042
5043/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5044/// vector of type 'VT', see if the elements can be replaced by a single large
5045/// load which has the same value as a build_vector whose operands are 'elts'.
5046///
5047/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5048///
5049/// FIXME: we'd also like to handle the case where the last elements are zero
5050/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5051/// There's even a handy isZeroNode for that purpose.
5052static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5053                                        DebugLoc &DL, SelectionDAG &DAG) {
5054  EVT EltVT = VT.getVectorElementType();
5055  unsigned NumElems = Elts.size();
5056
5057  LoadSDNode *LDBase = NULL;
5058  unsigned LastLoadedElt = -1U;
5059
5060  // For each element in the initializer, see if we've found a load or an undef.
5061  // If we don't find an initial load element, or later load elements are
5062  // non-consecutive, bail out.
5063  for (unsigned i = 0; i < NumElems; ++i) {
5064    SDValue Elt = Elts[i];
5065
5066    if (!Elt.getNode() ||
5067        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5068      return SDValue();
5069    if (!LDBase) {
5070      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5071        return SDValue();
5072      LDBase = cast<LoadSDNode>(Elt.getNode());
5073      LastLoadedElt = i;
5074      continue;
5075    }
5076    if (Elt.getOpcode() == ISD::UNDEF)
5077      continue;
5078
5079    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5080    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5081      return SDValue();
5082    LastLoadedElt = i;
5083  }
5084
5085  // If we have found an entire vector of loads and undefs, then return a large
5086  // load of the entire vector width starting at the base pointer.  If we found
5087  // consecutive loads for the low half, generate a vzext_load node.
5088  if (LastLoadedElt == NumElems - 1) {
5089    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5090      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5091                         LDBase->getPointerInfo(),
5092                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5093                         LDBase->isInvariant(), 0);
5094    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5095                       LDBase->getPointerInfo(),
5096                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5097                       LDBase->isInvariant(), LDBase->getAlignment());
5098  }
5099  if (NumElems == 4 && LastLoadedElt == 1 &&
5100      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5101    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5102    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5103    SDValue ResNode =
5104        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5105                                LDBase->getPointerInfo(),
5106                                LDBase->getAlignment(),
5107                                false/*isVolatile*/, true/*ReadMem*/,
5108                                false/*WriteMem*/);
5109
5110    // Make sure the newly-created LOAD is in the same position as LDBase in
5111    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5112    // update uses of LDBase's output chain to use the TokenFactor.
5113    if (LDBase->hasAnyUseOfValue(1)) {
5114      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5115                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5116      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5117      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5118                             SDValue(ResNode.getNode(), 1));
5119    }
5120
5121    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5122  }
5123  return SDValue();
5124}
5125
5126/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5127/// to generate a splat value for the following cases:
5128/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5129/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5130/// a scalar load, or a constant.
5131/// The VBROADCAST node is returned when a pattern is found,
5132/// or SDValue() otherwise.
5133SDValue
5134X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5135  if (!Subtarget->hasFp256())
5136    return SDValue();
5137
5138  MVT VT = Op.getValueType().getSimpleVT();
5139  DebugLoc dl = Op.getDebugLoc();
5140
5141  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5142         "Unsupported vector type for broadcast.");
5143
5144  SDValue Ld;
5145  bool ConstSplatVal;
5146
5147  switch (Op.getOpcode()) {
5148    default:
5149      // Unknown pattern found.
5150      return SDValue();
5151
5152    case ISD::BUILD_VECTOR: {
5153      // The BUILD_VECTOR node must be a splat.
5154      if (!isSplatVector(Op.getNode()))
5155        return SDValue();
5156
5157      Ld = Op.getOperand(0);
5158      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5159                     Ld.getOpcode() == ISD::ConstantFP);
5160
5161      // The suspected load node has several users. Make sure that all
5162      // of its users are from the BUILD_VECTOR node.
5163      // Constants may have multiple users.
5164      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5165        return SDValue();
5166      break;
5167    }
5168
5169    case ISD::VECTOR_SHUFFLE: {
5170      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5171
5172      // Shuffles must have a splat mask where the first element is
5173      // broadcasted.
5174      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5175        return SDValue();
5176
5177      SDValue Sc = Op.getOperand(0);
5178      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5179          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5180
5181        if (!Subtarget->hasInt256())
5182          return SDValue();
5183
5184        // Use the register form of the broadcast instruction available on AVX2.
5185        if (VT.is256BitVector())
5186          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5187        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5188      }
5189
5190      Ld = Sc.getOperand(0);
5191      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5192                       Ld.getOpcode() == ISD::ConstantFP);
5193
5194      // The scalar_to_vector node and the suspected
5195      // load node must have exactly one user.
5196      // Constants may have multiple users.
5197      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5198        return SDValue();
5199      break;
5200    }
5201  }
5202
5203  bool Is256 = VT.is256BitVector();
5204
5205  // Handle the broadcasting a single constant scalar from the constant pool
5206  // into a vector. On Sandybridge it is still better to load a constant vector
5207  // from the constant pool and not to broadcast it from a scalar.
5208  if (ConstSplatVal && Subtarget->hasInt256()) {
5209    EVT CVT = Ld.getValueType();
5210    assert(!CVT.isVector() && "Must not broadcast a vector type");
5211    unsigned ScalarSize = CVT.getSizeInBits();
5212
5213    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5214      const Constant *C = 0;
5215      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5216        C = CI->getConstantIntValue();
5217      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5218        C = CF->getConstantFPValue();
5219
5220      assert(C && "Invalid constant type");
5221
5222      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5223      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5224      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5225                       MachinePointerInfo::getConstantPool(),
5226                       false, false, false, Alignment);
5227
5228      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5229    }
5230  }
5231
5232  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5233  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5234
5235  // Handle AVX2 in-register broadcasts.
5236  if (!IsLoad && Subtarget->hasInt256() &&
5237      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5238    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5239
5240  // The scalar source must be a normal load.
5241  if (!IsLoad)
5242    return SDValue();
5243
5244  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5245    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5246
5247  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5248  // double since there is no vbroadcastsd xmm
5249  if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5250    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5251      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5252  }
5253
5254  // Unsupported broadcast.
5255  return SDValue();
5256}
5257
5258SDValue
5259X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5260  EVT VT = Op.getValueType();
5261
5262  // Skip if insert_vec_elt is not supported.
5263  if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5264    return SDValue();
5265
5266  DebugLoc DL = Op.getDebugLoc();
5267  unsigned NumElems = Op.getNumOperands();
5268
5269  SDValue VecIn1;
5270  SDValue VecIn2;
5271  SmallVector<unsigned, 4> InsertIndices;
5272  SmallVector<int, 8> Mask(NumElems, -1);
5273
5274  for (unsigned i = 0; i != NumElems; ++i) {
5275    unsigned Opc = Op.getOperand(i).getOpcode();
5276
5277    if (Opc == ISD::UNDEF)
5278      continue;
5279
5280    if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5281      // Quit if more than 1 elements need inserting.
5282      if (InsertIndices.size() > 1)
5283        return SDValue();
5284
5285      InsertIndices.push_back(i);
5286      continue;
5287    }
5288
5289    SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5290    SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5291
5292    // Quit if extracted from vector of different type.
5293    if (ExtractedFromVec.getValueType() != VT)
5294      return SDValue();
5295
5296    // Quit if non-constant index.
5297    if (!isa<ConstantSDNode>(ExtIdx))
5298      return SDValue();
5299
5300    if (VecIn1.getNode() == 0)
5301      VecIn1 = ExtractedFromVec;
5302    else if (VecIn1 != ExtractedFromVec) {
5303      if (VecIn2.getNode() == 0)
5304        VecIn2 = ExtractedFromVec;
5305      else if (VecIn2 != ExtractedFromVec)
5306        // Quit if more than 2 vectors to shuffle
5307        return SDValue();
5308    }
5309
5310    unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5311
5312    if (ExtractedFromVec == VecIn1)
5313      Mask[i] = Idx;
5314    else if (ExtractedFromVec == VecIn2)
5315      Mask[i] = Idx + NumElems;
5316  }
5317
5318  if (VecIn1.getNode() == 0)
5319    return SDValue();
5320
5321  VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5322  SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5323  for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5324    unsigned Idx = InsertIndices[i];
5325    NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5326                     DAG.getIntPtrConstant(Idx));
5327  }
5328
5329  return NV;
5330}
5331
5332SDValue
5333X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5334  DebugLoc dl = Op.getDebugLoc();
5335
5336  MVT VT = Op.getValueType().getSimpleVT();
5337  MVT ExtVT = VT.getVectorElementType();
5338  unsigned NumElems = Op.getNumOperands();
5339
5340  // Vectors containing all zeros can be matched by pxor and xorps later
5341  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5342    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5343    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5344    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5345      return Op;
5346
5347    return getZeroVector(VT, Subtarget, DAG, dl);
5348  }
5349
5350  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5351  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5352  // vpcmpeqd on 256-bit vectors.
5353  if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5354    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5355      return Op;
5356
5357    return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5358  }
5359
5360  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5361  if (Broadcast.getNode())
5362    return Broadcast;
5363
5364  unsigned EVTBits = ExtVT.getSizeInBits();
5365
5366  unsigned NumZero  = 0;
5367  unsigned NumNonZero = 0;
5368  unsigned NonZeros = 0;
5369  bool IsAllConstants = true;
5370  SmallSet<SDValue, 8> Values;
5371  for (unsigned i = 0; i < NumElems; ++i) {
5372    SDValue Elt = Op.getOperand(i);
5373    if (Elt.getOpcode() == ISD::UNDEF)
5374      continue;
5375    Values.insert(Elt);
5376    if (Elt.getOpcode() != ISD::Constant &&
5377        Elt.getOpcode() != ISD::ConstantFP)
5378      IsAllConstants = false;
5379    if (X86::isZeroNode(Elt))
5380      NumZero++;
5381    else {
5382      NonZeros |= (1 << i);
5383      NumNonZero++;
5384    }
5385  }
5386
5387  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5388  if (NumNonZero == 0)
5389    return DAG.getUNDEF(VT);
5390
5391  // Special case for single non-zero, non-undef, element.
5392  if (NumNonZero == 1) {
5393    unsigned Idx = CountTrailingZeros_32(NonZeros);
5394    SDValue Item = Op.getOperand(Idx);
5395
5396    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5397    // the value are obviously zero, truncate the value to i32 and do the
5398    // insertion that way.  Only do this if the value is non-constant or if the
5399    // value is a constant being inserted into element 0.  It is cheaper to do
5400    // a constant pool load than it is to do a movd + shuffle.
5401    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5402        (!IsAllConstants || Idx == 0)) {
5403      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5404        // Handle SSE only.
5405        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5406        EVT VecVT = MVT::v4i32;
5407        unsigned VecElts = 4;
5408
5409        // Truncate the value (which may itself be a constant) to i32, and
5410        // convert it to a vector with movd (S2V+shuffle to zero extend).
5411        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5412        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5413        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5414
5415        // Now we have our 32-bit value zero extended in the low element of
5416        // a vector.  If Idx != 0, swizzle it into place.
5417        if (Idx != 0) {
5418          SmallVector<int, 4> Mask;
5419          Mask.push_back(Idx);
5420          for (unsigned i = 1; i != VecElts; ++i)
5421            Mask.push_back(i);
5422          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5423                                      &Mask[0]);
5424        }
5425        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5426      }
5427    }
5428
5429    // If we have a constant or non-constant insertion into the low element of
5430    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5431    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5432    // depending on what the source datatype is.
5433    if (Idx == 0) {
5434      if (NumZero == 0)
5435        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5436
5437      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5438          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5439        if (VT.is256BitVector()) {
5440          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5441          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5442                             Item, DAG.getIntPtrConstant(0));
5443        }
5444        assert(VT.is128BitVector() && "Expected an SSE value type!");
5445        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5446        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5447        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5448      }
5449
5450      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5451        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5452        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5453        if (VT.is256BitVector()) {
5454          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5455          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5456        } else {
5457          assert(VT.is128BitVector() && "Expected an SSE value type!");
5458          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5459        }
5460        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5461      }
5462    }
5463
5464    // Is it a vector logical left shift?
5465    if (NumElems == 2 && Idx == 1 &&
5466        X86::isZeroNode(Op.getOperand(0)) &&
5467        !X86::isZeroNode(Op.getOperand(1))) {
5468      unsigned NumBits = VT.getSizeInBits();
5469      return getVShift(true, VT,
5470                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5471                                   VT, Op.getOperand(1)),
5472                       NumBits/2, DAG, *this, dl);
5473    }
5474
5475    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5476      return SDValue();
5477
5478    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5479    // is a non-constant being inserted into an element other than the low one,
5480    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5481    // movd/movss) to move this into the low element, then shuffle it into
5482    // place.
5483    if (EVTBits == 32) {
5484      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5485
5486      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5487      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5488      SmallVector<int, 8> MaskVec;
5489      for (unsigned i = 0; i != NumElems; ++i)
5490        MaskVec.push_back(i == Idx ? 0 : 1);
5491      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5492    }
5493  }
5494
5495  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5496  if (Values.size() == 1) {
5497    if (EVTBits == 32) {
5498      // Instead of a shuffle like this:
5499      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5500      // Check if it's possible to issue this instead.
5501      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5502      unsigned Idx = CountTrailingZeros_32(NonZeros);
5503      SDValue Item = Op.getOperand(Idx);
5504      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5505        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5506    }
5507    return SDValue();
5508  }
5509
5510  // A vector full of immediates; various special cases are already
5511  // handled, so this is best done with a single constant-pool load.
5512  if (IsAllConstants)
5513    return SDValue();
5514
5515  // For AVX-length vectors, build the individual 128-bit pieces and use
5516  // shuffles to put them in place.
5517  if (VT.is256BitVector()) {
5518    SmallVector<SDValue, 32> V;
5519    for (unsigned i = 0; i != NumElems; ++i)
5520      V.push_back(Op.getOperand(i));
5521
5522    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5523
5524    // Build both the lower and upper subvector.
5525    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5526    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5527                                NumElems/2);
5528
5529    // Recreate the wider vector with the lower and upper part.
5530    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5531  }
5532
5533  // Let legalizer expand 2-wide build_vectors.
5534  if (EVTBits == 64) {
5535    if (NumNonZero == 1) {
5536      // One half is zero or undef.
5537      unsigned Idx = CountTrailingZeros_32(NonZeros);
5538      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5539                                 Op.getOperand(Idx));
5540      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5541    }
5542    return SDValue();
5543  }
5544
5545  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5546  if (EVTBits == 8 && NumElems == 16) {
5547    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5548                                        Subtarget, *this);
5549    if (V.getNode()) return V;
5550  }
5551
5552  if (EVTBits == 16 && NumElems == 8) {
5553    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5554                                      Subtarget, *this);
5555    if (V.getNode()) return V;
5556  }
5557
5558  // If element VT is == 32 bits, turn it into a number of shuffles.
5559  SmallVector<SDValue, 8> V(NumElems);
5560  if (NumElems == 4 && NumZero > 0) {
5561    for (unsigned i = 0; i < 4; ++i) {
5562      bool isZero = !(NonZeros & (1 << i));
5563      if (isZero)
5564        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5565      else
5566        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5567    }
5568
5569    for (unsigned i = 0; i < 2; ++i) {
5570      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5571        default: break;
5572        case 0:
5573          V[i] = V[i*2];  // Must be a zero vector.
5574          break;
5575        case 1:
5576          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5577          break;
5578        case 2:
5579          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5580          break;
5581        case 3:
5582          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5583          break;
5584      }
5585    }
5586
5587    bool Reverse1 = (NonZeros & 0x3) == 2;
5588    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5589    int MaskVec[] = {
5590      Reverse1 ? 1 : 0,
5591      Reverse1 ? 0 : 1,
5592      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5593      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5594    };
5595    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5596  }
5597
5598  if (Values.size() > 1 && VT.is128BitVector()) {
5599    // Check for a build vector of consecutive loads.
5600    for (unsigned i = 0; i < NumElems; ++i)
5601      V[i] = Op.getOperand(i);
5602
5603    // Check for elements which are consecutive loads.
5604    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5605    if (LD.getNode())
5606      return LD;
5607
5608    // Check for a build vector from mostly shuffle plus few inserting.
5609    SDValue Sh = buildFromShuffleMostly(Op, DAG);
5610    if (Sh.getNode())
5611      return Sh;
5612
5613    // For SSE 4.1, use insertps to put the high elements into the low element.
5614    if (getSubtarget()->hasSSE41()) {
5615      SDValue Result;
5616      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5617        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5618      else
5619        Result = DAG.getUNDEF(VT);
5620
5621      for (unsigned i = 1; i < NumElems; ++i) {
5622        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5623        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5624                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5625      }
5626      return Result;
5627    }
5628
5629    // Otherwise, expand into a number of unpckl*, start by extending each of
5630    // our (non-undef) elements to the full vector width with the element in the
5631    // bottom slot of the vector (which generates no code for SSE).
5632    for (unsigned i = 0; i < NumElems; ++i) {
5633      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5634        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5635      else
5636        V[i] = DAG.getUNDEF(VT);
5637    }
5638
5639    // Next, we iteratively mix elements, e.g. for v4f32:
5640    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5641    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5642    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5643    unsigned EltStride = NumElems >> 1;
5644    while (EltStride != 0) {
5645      for (unsigned i = 0; i < EltStride; ++i) {
5646        // If V[i+EltStride] is undef and this is the first round of mixing,
5647        // then it is safe to just drop this shuffle: V[i] is already in the
5648        // right place, the one element (since it's the first round) being
5649        // inserted as undef can be dropped.  This isn't safe for successive
5650        // rounds because they will permute elements within both vectors.
5651        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5652            EltStride == NumElems/2)
5653          continue;
5654
5655        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5656      }
5657      EltStride >>= 1;
5658    }
5659    return V[0];
5660  }
5661  return SDValue();
5662}
5663
5664// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5665// to create 256-bit vectors from two other 128-bit ones.
5666static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5667  DebugLoc dl = Op.getDebugLoc();
5668  MVT ResVT = Op.getValueType().getSimpleVT();
5669
5670  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5671
5672  SDValue V1 = Op.getOperand(0);
5673  SDValue V2 = Op.getOperand(1);
5674  unsigned NumElems = ResVT.getVectorNumElements();
5675
5676  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5677}
5678
5679static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5680  assert(Op.getNumOperands() == 2);
5681
5682  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5683  // from two other 128-bit ones.
5684  return LowerAVXCONCAT_VECTORS(Op, DAG);
5685}
5686
5687// Try to lower a shuffle node into a simple blend instruction.
5688static SDValue
5689LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5690                           const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5691  SDValue V1 = SVOp->getOperand(0);
5692  SDValue V2 = SVOp->getOperand(1);
5693  DebugLoc dl = SVOp->getDebugLoc();
5694  MVT VT = SVOp->getValueType(0).getSimpleVT();
5695  MVT EltVT = VT.getVectorElementType();
5696  unsigned NumElems = VT.getVectorNumElements();
5697
5698  if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5699    return SDValue();
5700  if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5701    return SDValue();
5702
5703  // Check the mask for BLEND and build the value.
5704  unsigned MaskValue = 0;
5705  // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5706  unsigned NumLanes = (NumElems-1)/8 + 1;
5707  unsigned NumElemsInLane = NumElems / NumLanes;
5708
5709  // Blend for v16i16 should be symetric for the both lanes.
5710  for (unsigned i = 0; i < NumElemsInLane; ++i) {
5711
5712    int SndLaneEltIdx = (NumLanes == 2) ?
5713      SVOp->getMaskElt(i + NumElemsInLane) : -1;
5714    int EltIdx = SVOp->getMaskElt(i);
5715
5716    if ((EltIdx < 0 || EltIdx == (int)i) &&
5717        (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5718      continue;
5719
5720    if (((unsigned)EltIdx == (i + NumElems)) &&
5721        (SndLaneEltIdx < 0 ||
5722         (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5723      MaskValue |= (1<<i);
5724    else
5725      return SDValue();
5726  }
5727
5728  // Convert i32 vectors to floating point if it is not AVX2.
5729  // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5730  MVT BlendVT = VT;
5731  if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5732    BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5733                               NumElems);
5734    V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5735    V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5736  }
5737
5738  SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5739                            DAG.getConstant(MaskValue, MVT::i32));
5740  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5741}
5742
5743// v8i16 shuffles - Prefer shuffles in the following order:
5744// 1. [all]   pshuflw, pshufhw, optional move
5745// 2. [ssse3] 1 x pshufb
5746// 3. [ssse3] 2 x pshufb + 1 x por
5747// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5748static SDValue
5749LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5750                         SelectionDAG &DAG) {
5751  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5752  SDValue V1 = SVOp->getOperand(0);
5753  SDValue V2 = SVOp->getOperand(1);
5754  DebugLoc dl = SVOp->getDebugLoc();
5755  SmallVector<int, 8> MaskVals;
5756
5757  // Determine if more than 1 of the words in each of the low and high quadwords
5758  // of the result come from the same quadword of one of the two inputs.  Undef
5759  // mask values count as coming from any quadword, for better codegen.
5760  unsigned LoQuad[] = { 0, 0, 0, 0 };
5761  unsigned HiQuad[] = { 0, 0, 0, 0 };
5762  std::bitset<4> InputQuads;
5763  for (unsigned i = 0; i < 8; ++i) {
5764    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5765    int EltIdx = SVOp->getMaskElt(i);
5766    MaskVals.push_back(EltIdx);
5767    if (EltIdx < 0) {
5768      ++Quad[0];
5769      ++Quad[1];
5770      ++Quad[2];
5771      ++Quad[3];
5772      continue;
5773    }
5774    ++Quad[EltIdx / 4];
5775    InputQuads.set(EltIdx / 4);
5776  }
5777
5778  int BestLoQuad = -1;
5779  unsigned MaxQuad = 1;
5780  for (unsigned i = 0; i < 4; ++i) {
5781    if (LoQuad[i] > MaxQuad) {
5782      BestLoQuad = i;
5783      MaxQuad = LoQuad[i];
5784    }
5785  }
5786
5787  int BestHiQuad = -1;
5788  MaxQuad = 1;
5789  for (unsigned i = 0; i < 4; ++i) {
5790    if (HiQuad[i] > MaxQuad) {
5791      BestHiQuad = i;
5792      MaxQuad = HiQuad[i];
5793    }
5794  }
5795
5796  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5797  // of the two input vectors, shuffle them into one input vector so only a
5798  // single pshufb instruction is necessary. If There are more than 2 input
5799  // quads, disable the next transformation since it does not help SSSE3.
5800  bool V1Used = InputQuads[0] || InputQuads[1];
5801  bool V2Used = InputQuads[2] || InputQuads[3];
5802  if (Subtarget->hasSSSE3()) {
5803    if (InputQuads.count() == 2 && V1Used && V2Used) {
5804      BestLoQuad = InputQuads[0] ? 0 : 1;
5805      BestHiQuad = InputQuads[2] ? 2 : 3;
5806    }
5807    if (InputQuads.count() > 2) {
5808      BestLoQuad = -1;
5809      BestHiQuad = -1;
5810    }
5811  }
5812
5813  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5814  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5815  // words from all 4 input quadwords.
5816  SDValue NewV;
5817  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5818    int MaskV[] = {
5819      BestLoQuad < 0 ? 0 : BestLoQuad,
5820      BestHiQuad < 0 ? 1 : BestHiQuad
5821    };
5822    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5823                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5824                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5825    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5826
5827    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5828    // source words for the shuffle, to aid later transformations.
5829    bool AllWordsInNewV = true;
5830    bool InOrder[2] = { true, true };
5831    for (unsigned i = 0; i != 8; ++i) {
5832      int idx = MaskVals[i];
5833      if (idx != (int)i)
5834        InOrder[i/4] = false;
5835      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5836        continue;
5837      AllWordsInNewV = false;
5838      break;
5839    }
5840
5841    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5842    if (AllWordsInNewV) {
5843      for (int i = 0; i != 8; ++i) {
5844        int idx = MaskVals[i];
5845        if (idx < 0)
5846          continue;
5847        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5848        if ((idx != i) && idx < 4)
5849          pshufhw = false;
5850        if ((idx != i) && idx > 3)
5851          pshuflw = false;
5852      }
5853      V1 = NewV;
5854      V2Used = false;
5855      BestLoQuad = 0;
5856      BestHiQuad = 1;
5857    }
5858
5859    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5860    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5861    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5862      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5863      unsigned TargetMask = 0;
5864      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5865                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5866      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5867      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5868                             getShufflePSHUFLWImmediate(SVOp);
5869      V1 = NewV.getOperand(0);
5870      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5871    }
5872  }
5873
5874  // Promote splats to a larger type which usually leads to more efficient code.
5875  // FIXME: Is this true if pshufb is available?
5876  if (SVOp->isSplat())
5877    return PromoteSplat(SVOp, DAG);
5878
5879  // If we have SSSE3, and all words of the result are from 1 input vector,
5880  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5881  // is present, fall back to case 4.
5882  if (Subtarget->hasSSSE3()) {
5883    SmallVector<SDValue,16> pshufbMask;
5884
5885    // If we have elements from both input vectors, set the high bit of the
5886    // shuffle mask element to zero out elements that come from V2 in the V1
5887    // mask, and elements that come from V1 in the V2 mask, so that the two
5888    // results can be OR'd together.
5889    bool TwoInputs = V1Used && V2Used;
5890    for (unsigned i = 0; i != 8; ++i) {
5891      int EltIdx = MaskVals[i] * 2;
5892      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5893      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5894      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5895      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5896    }
5897    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5898    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5899                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5900                                 MVT::v16i8, &pshufbMask[0], 16));
5901    if (!TwoInputs)
5902      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5903
5904    // Calculate the shuffle mask for the second input, shuffle it, and
5905    // OR it with the first shuffled input.
5906    pshufbMask.clear();
5907    for (unsigned i = 0; i != 8; ++i) {
5908      int EltIdx = MaskVals[i] * 2;
5909      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5910      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5911      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5912      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5913    }
5914    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5915    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5916                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5917                                 MVT::v16i8, &pshufbMask[0], 16));
5918    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5919    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5920  }
5921
5922  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5923  // and update MaskVals with new element order.
5924  std::bitset<8> InOrder;
5925  if (BestLoQuad >= 0) {
5926    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5927    for (int i = 0; i != 4; ++i) {
5928      int idx = MaskVals[i];
5929      if (idx < 0) {
5930        InOrder.set(i);
5931      } else if ((idx / 4) == BestLoQuad) {
5932        MaskV[i] = idx & 3;
5933        InOrder.set(i);
5934      }
5935    }
5936    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5937                                &MaskV[0]);
5938
5939    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5940      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5941      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5942                                  NewV.getOperand(0),
5943                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5944    }
5945  }
5946
5947  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5948  // and update MaskVals with the new element order.
5949  if (BestHiQuad >= 0) {
5950    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5951    for (unsigned i = 4; i != 8; ++i) {
5952      int idx = MaskVals[i];
5953      if (idx < 0) {
5954        InOrder.set(i);
5955      } else if ((idx / 4) == BestHiQuad) {
5956        MaskV[i] = (idx & 3) + 4;
5957        InOrder.set(i);
5958      }
5959    }
5960    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5961                                &MaskV[0]);
5962
5963    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5964      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5965      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5966                                  NewV.getOperand(0),
5967                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5968    }
5969  }
5970
5971  // In case BestHi & BestLo were both -1, which means each quadword has a word
5972  // from each of the four input quadwords, calculate the InOrder bitvector now
5973  // before falling through to the insert/extract cleanup.
5974  if (BestLoQuad == -1 && BestHiQuad == -1) {
5975    NewV = V1;
5976    for (int i = 0; i != 8; ++i)
5977      if (MaskVals[i] < 0 || MaskVals[i] == i)
5978        InOrder.set(i);
5979  }
5980
5981  // The other elements are put in the right place using pextrw and pinsrw.
5982  for (unsigned i = 0; i != 8; ++i) {
5983    if (InOrder[i])
5984      continue;
5985    int EltIdx = MaskVals[i];
5986    if (EltIdx < 0)
5987      continue;
5988    SDValue ExtOp = (EltIdx < 8) ?
5989      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5990                  DAG.getIntPtrConstant(EltIdx)) :
5991      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5992                  DAG.getIntPtrConstant(EltIdx - 8));
5993    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5994                       DAG.getIntPtrConstant(i));
5995  }
5996  return NewV;
5997}
5998
5999// v16i8 shuffles - Prefer shuffles in the following order:
6000// 1. [ssse3] 1 x pshufb
6001// 2. [ssse3] 2 x pshufb + 1 x por
6002// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6003static
6004SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6005                                 SelectionDAG &DAG,
6006                                 const X86TargetLowering &TLI) {
6007  SDValue V1 = SVOp->getOperand(0);
6008  SDValue V2 = SVOp->getOperand(1);
6009  DebugLoc dl = SVOp->getDebugLoc();
6010  ArrayRef<int> MaskVals = SVOp->getMask();
6011
6012  // Promote splats to a larger type which usually leads to more efficient code.
6013  // FIXME: Is this true if pshufb is available?
6014  if (SVOp->isSplat())
6015    return PromoteSplat(SVOp, DAG);
6016
6017  // If we have SSSE3, case 1 is generated when all result bytes come from
6018  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6019  // present, fall back to case 3.
6020
6021  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6022  if (TLI.getSubtarget()->hasSSSE3()) {
6023    SmallVector<SDValue,16> pshufbMask;
6024
6025    // If all result elements are from one input vector, then only translate
6026    // undef mask values to 0x80 (zero out result) in the pshufb mask.
6027    //
6028    // Otherwise, we have elements from both input vectors, and must zero out
6029    // elements that come from V2 in the first mask, and V1 in the second mask
6030    // so that we can OR them together.
6031    for (unsigned i = 0; i != 16; ++i) {
6032      int EltIdx = MaskVals[i];
6033      if (EltIdx < 0 || EltIdx >= 16)
6034        EltIdx = 0x80;
6035      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6036    }
6037    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6038                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6039                                 MVT::v16i8, &pshufbMask[0], 16));
6040
6041    // As PSHUFB will zero elements with negative indices, it's safe to ignore
6042    // the 2nd operand if it's undefined or zero.
6043    if (V2.getOpcode() == ISD::UNDEF ||
6044        ISD::isBuildVectorAllZeros(V2.getNode()))
6045      return V1;
6046
6047    // Calculate the shuffle mask for the second input, shuffle it, and
6048    // OR it with the first shuffled input.
6049    pshufbMask.clear();
6050    for (unsigned i = 0; i != 16; ++i) {
6051      int EltIdx = MaskVals[i];
6052      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6053      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6054    }
6055    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6056                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6057                                 MVT::v16i8, &pshufbMask[0], 16));
6058    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6059  }
6060
6061  // No SSSE3 - Calculate in place words and then fix all out of place words
6062  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6063  // the 16 different words that comprise the two doublequadword input vectors.
6064  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6065  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6066  SDValue NewV = V1;
6067  for (int i = 0; i != 8; ++i) {
6068    int Elt0 = MaskVals[i*2];
6069    int Elt1 = MaskVals[i*2+1];
6070
6071    // This word of the result is all undef, skip it.
6072    if (Elt0 < 0 && Elt1 < 0)
6073      continue;
6074
6075    // This word of the result is already in the correct place, skip it.
6076    if ((Elt0 == i*2) && (Elt1 == i*2+1))
6077      continue;
6078
6079    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6080    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6081    SDValue InsElt;
6082
6083    // If Elt0 and Elt1 are defined, are consecutive, and can be load
6084    // using a single extract together, load it and store it.
6085    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6086      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6087                           DAG.getIntPtrConstant(Elt1 / 2));
6088      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6089                        DAG.getIntPtrConstant(i));
6090      continue;
6091    }
6092
6093    // If Elt1 is defined, extract it from the appropriate source.  If the
6094    // source byte is not also odd, shift the extracted word left 8 bits
6095    // otherwise clear the bottom 8 bits if we need to do an or.
6096    if (Elt1 >= 0) {
6097      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6098                           DAG.getIntPtrConstant(Elt1 / 2));
6099      if ((Elt1 & 1) == 0)
6100        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6101                             DAG.getConstant(8,
6102                                  TLI.getShiftAmountTy(InsElt.getValueType())));
6103      else if (Elt0 >= 0)
6104        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6105                             DAG.getConstant(0xFF00, MVT::i16));
6106    }
6107    // If Elt0 is defined, extract it from the appropriate source.  If the
6108    // source byte is not also even, shift the extracted word right 8 bits. If
6109    // Elt1 was also defined, OR the extracted values together before
6110    // inserting them in the result.
6111    if (Elt0 >= 0) {
6112      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6113                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6114      if ((Elt0 & 1) != 0)
6115        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6116                              DAG.getConstant(8,
6117                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6118      else if (Elt1 >= 0)
6119        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6120                             DAG.getConstant(0x00FF, MVT::i16));
6121      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6122                         : InsElt0;
6123    }
6124    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6125                       DAG.getIntPtrConstant(i));
6126  }
6127  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6128}
6129
6130// v32i8 shuffles - Translate to VPSHUFB if possible.
6131static
6132SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6133                                 const X86Subtarget *Subtarget,
6134                                 SelectionDAG &DAG) {
6135  MVT VT = SVOp->getValueType(0).getSimpleVT();
6136  SDValue V1 = SVOp->getOperand(0);
6137  SDValue V2 = SVOp->getOperand(1);
6138  DebugLoc dl = SVOp->getDebugLoc();
6139  SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6140
6141  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6142  bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6143  bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6144
6145  // VPSHUFB may be generated if
6146  // (1) one of input vector is undefined or zeroinitializer.
6147  // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6148  // And (2) the mask indexes don't cross the 128-bit lane.
6149  if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6150      (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6151    return SDValue();
6152
6153  if (V1IsAllZero && !V2IsAllZero) {
6154    CommuteVectorShuffleMask(MaskVals, 32);
6155    V1 = V2;
6156  }
6157  SmallVector<SDValue, 32> pshufbMask;
6158  for (unsigned i = 0; i != 32; i++) {
6159    int EltIdx = MaskVals[i];
6160    if (EltIdx < 0 || EltIdx >= 32)
6161      EltIdx = 0x80;
6162    else {
6163      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6164        // Cross lane is not allowed.
6165        return SDValue();
6166      EltIdx &= 0xf;
6167    }
6168    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6169  }
6170  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6171                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6172                                  MVT::v32i8, &pshufbMask[0], 32));
6173}
6174
6175/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6176/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6177/// done when every pair / quad of shuffle mask elements point to elements in
6178/// the right sequence. e.g.
6179/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6180static
6181SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6182                                 SelectionDAG &DAG) {
6183  MVT VT = SVOp->getValueType(0).getSimpleVT();
6184  DebugLoc dl = SVOp->getDebugLoc();
6185  unsigned NumElems = VT.getVectorNumElements();
6186  MVT NewVT;
6187  unsigned Scale;
6188  switch (VT.SimpleTy) {
6189  default: llvm_unreachable("Unexpected!");
6190  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6191  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6192  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6193  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6194  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6195  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6196  }
6197
6198  SmallVector<int, 8> MaskVec;
6199  for (unsigned i = 0; i != NumElems; i += Scale) {
6200    int StartIdx = -1;
6201    for (unsigned j = 0; j != Scale; ++j) {
6202      int EltIdx = SVOp->getMaskElt(i+j);
6203      if (EltIdx < 0)
6204        continue;
6205      if (StartIdx < 0)
6206        StartIdx = (EltIdx / Scale);
6207      if (EltIdx != (int)(StartIdx*Scale + j))
6208        return SDValue();
6209    }
6210    MaskVec.push_back(StartIdx);
6211  }
6212
6213  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6214  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6215  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6216}
6217
6218/// getVZextMovL - Return a zero-extending vector move low node.
6219///
6220static SDValue getVZextMovL(MVT VT, EVT OpVT,
6221                            SDValue SrcOp, SelectionDAG &DAG,
6222                            const X86Subtarget *Subtarget, DebugLoc dl) {
6223  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6224    LoadSDNode *LD = NULL;
6225    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6226      LD = dyn_cast<LoadSDNode>(SrcOp);
6227    if (!LD) {
6228      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6229      // instead.
6230      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6231      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6232          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6233          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6234          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6235        // PR2108
6236        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6237        return DAG.getNode(ISD::BITCAST, dl, VT,
6238                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6239                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6240                                                   OpVT,
6241                                                   SrcOp.getOperand(0)
6242                                                          .getOperand(0))));
6243      }
6244    }
6245  }
6246
6247  return DAG.getNode(ISD::BITCAST, dl, VT,
6248                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6249                                 DAG.getNode(ISD::BITCAST, dl,
6250                                             OpVT, SrcOp)));
6251}
6252
6253/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6254/// which could not be matched by any known target speficic shuffle
6255static SDValue
6256LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6257
6258  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6259  if (NewOp.getNode())
6260    return NewOp;
6261
6262  MVT VT = SVOp->getValueType(0).getSimpleVT();
6263
6264  unsigned NumElems = VT.getVectorNumElements();
6265  unsigned NumLaneElems = NumElems / 2;
6266
6267  DebugLoc dl = SVOp->getDebugLoc();
6268  MVT EltVT = VT.getVectorElementType();
6269  MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6270  SDValue Output[2];
6271
6272  SmallVector<int, 16> Mask;
6273  for (unsigned l = 0; l < 2; ++l) {
6274    // Build a shuffle mask for the output, discovering on the fly which
6275    // input vectors to use as shuffle operands (recorded in InputUsed).
6276    // If building a suitable shuffle vector proves too hard, then bail
6277    // out with UseBuildVector set.
6278    bool UseBuildVector = false;
6279    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6280    unsigned LaneStart = l * NumLaneElems;
6281    for (unsigned i = 0; i != NumLaneElems; ++i) {
6282      // The mask element.  This indexes into the input.
6283      int Idx = SVOp->getMaskElt(i+LaneStart);
6284      if (Idx < 0) {
6285        // the mask element does not index into any input vector.
6286        Mask.push_back(-1);
6287        continue;
6288      }
6289
6290      // The input vector this mask element indexes into.
6291      int Input = Idx / NumLaneElems;
6292
6293      // Turn the index into an offset from the start of the input vector.
6294      Idx -= Input * NumLaneElems;
6295
6296      // Find or create a shuffle vector operand to hold this input.
6297      unsigned OpNo;
6298      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6299        if (InputUsed[OpNo] == Input)
6300          // This input vector is already an operand.
6301          break;
6302        if (InputUsed[OpNo] < 0) {
6303          // Create a new operand for this input vector.
6304          InputUsed[OpNo] = Input;
6305          break;
6306        }
6307      }
6308
6309      if (OpNo >= array_lengthof(InputUsed)) {
6310        // More than two input vectors used!  Give up on trying to create a
6311        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6312        UseBuildVector = true;
6313        break;
6314      }
6315
6316      // Add the mask index for the new shuffle vector.
6317      Mask.push_back(Idx + OpNo * NumLaneElems);
6318    }
6319
6320    if (UseBuildVector) {
6321      SmallVector<SDValue, 16> SVOps;
6322      for (unsigned i = 0; i != NumLaneElems; ++i) {
6323        // The mask element.  This indexes into the input.
6324        int Idx = SVOp->getMaskElt(i+LaneStart);
6325        if (Idx < 0) {
6326          SVOps.push_back(DAG.getUNDEF(EltVT));
6327          continue;
6328        }
6329
6330        // The input vector this mask element indexes into.
6331        int Input = Idx / NumElems;
6332
6333        // Turn the index into an offset from the start of the input vector.
6334        Idx -= Input * NumElems;
6335
6336        // Extract the vector element by hand.
6337        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6338                                    SVOp->getOperand(Input),
6339                                    DAG.getIntPtrConstant(Idx)));
6340      }
6341
6342      // Construct the output using a BUILD_VECTOR.
6343      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6344                              SVOps.size());
6345    } else if (InputUsed[0] < 0) {
6346      // No input vectors were used! The result is undefined.
6347      Output[l] = DAG.getUNDEF(NVT);
6348    } else {
6349      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6350                                        (InputUsed[0] % 2) * NumLaneElems,
6351                                        DAG, dl);
6352      // If only one input was used, use an undefined vector for the other.
6353      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6354        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6355                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6356      // At least one input vector was used. Create a new shuffle vector.
6357      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6358    }
6359
6360    Mask.clear();
6361  }
6362
6363  // Concatenate the result back
6364  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6365}
6366
6367/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6368/// 4 elements, and match them with several different shuffle types.
6369static SDValue
6370LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6371  SDValue V1 = SVOp->getOperand(0);
6372  SDValue V2 = SVOp->getOperand(1);
6373  DebugLoc dl = SVOp->getDebugLoc();
6374  MVT VT = SVOp->getValueType(0).getSimpleVT();
6375
6376  assert(VT.is128BitVector() && "Unsupported vector size");
6377
6378  std::pair<int, int> Locs[4];
6379  int Mask1[] = { -1, -1, -1, -1 };
6380  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6381
6382  unsigned NumHi = 0;
6383  unsigned NumLo = 0;
6384  for (unsigned i = 0; i != 4; ++i) {
6385    int Idx = PermMask[i];
6386    if (Idx < 0) {
6387      Locs[i] = std::make_pair(-1, -1);
6388    } else {
6389      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6390      if (Idx < 4) {
6391        Locs[i] = std::make_pair(0, NumLo);
6392        Mask1[NumLo] = Idx;
6393        NumLo++;
6394      } else {
6395        Locs[i] = std::make_pair(1, NumHi);
6396        if (2+NumHi < 4)
6397          Mask1[2+NumHi] = Idx;
6398        NumHi++;
6399      }
6400    }
6401  }
6402
6403  if (NumLo <= 2 && NumHi <= 2) {
6404    // If no more than two elements come from either vector. This can be
6405    // implemented with two shuffles. First shuffle gather the elements.
6406    // The second shuffle, which takes the first shuffle as both of its
6407    // vector operands, put the elements into the right order.
6408    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6409
6410    int Mask2[] = { -1, -1, -1, -1 };
6411
6412    for (unsigned i = 0; i != 4; ++i)
6413      if (Locs[i].first != -1) {
6414        unsigned Idx = (i < 2) ? 0 : 4;
6415        Idx += Locs[i].first * 2 + Locs[i].second;
6416        Mask2[i] = Idx;
6417      }
6418
6419    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6420  }
6421
6422  if (NumLo == 3 || NumHi == 3) {
6423    // Otherwise, we must have three elements from one vector, call it X, and
6424    // one element from the other, call it Y.  First, use a shufps to build an
6425    // intermediate vector with the one element from Y and the element from X
6426    // that will be in the same half in the final destination (the indexes don't
6427    // matter). Then, use a shufps to build the final vector, taking the half
6428    // containing the element from Y from the intermediate, and the other half
6429    // from X.
6430    if (NumHi == 3) {
6431      // Normalize it so the 3 elements come from V1.
6432      CommuteVectorShuffleMask(PermMask, 4);
6433      std::swap(V1, V2);
6434    }
6435
6436    // Find the element from V2.
6437    unsigned HiIndex;
6438    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6439      int Val = PermMask[HiIndex];
6440      if (Val < 0)
6441        continue;
6442      if (Val >= 4)
6443        break;
6444    }
6445
6446    Mask1[0] = PermMask[HiIndex];
6447    Mask1[1] = -1;
6448    Mask1[2] = PermMask[HiIndex^1];
6449    Mask1[3] = -1;
6450    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6451
6452    if (HiIndex >= 2) {
6453      Mask1[0] = PermMask[0];
6454      Mask1[1] = PermMask[1];
6455      Mask1[2] = HiIndex & 1 ? 6 : 4;
6456      Mask1[3] = HiIndex & 1 ? 4 : 6;
6457      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6458    }
6459
6460    Mask1[0] = HiIndex & 1 ? 2 : 0;
6461    Mask1[1] = HiIndex & 1 ? 0 : 2;
6462    Mask1[2] = PermMask[2];
6463    Mask1[3] = PermMask[3];
6464    if (Mask1[2] >= 0)
6465      Mask1[2] += 4;
6466    if (Mask1[3] >= 0)
6467      Mask1[3] += 4;
6468    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6469  }
6470
6471  // Break it into (shuffle shuffle_hi, shuffle_lo).
6472  int LoMask[] = { -1, -1, -1, -1 };
6473  int HiMask[] = { -1, -1, -1, -1 };
6474
6475  int *MaskPtr = LoMask;
6476  unsigned MaskIdx = 0;
6477  unsigned LoIdx = 0;
6478  unsigned HiIdx = 2;
6479  for (unsigned i = 0; i != 4; ++i) {
6480    if (i == 2) {
6481      MaskPtr = HiMask;
6482      MaskIdx = 1;
6483      LoIdx = 0;
6484      HiIdx = 2;
6485    }
6486    int Idx = PermMask[i];
6487    if (Idx < 0) {
6488      Locs[i] = std::make_pair(-1, -1);
6489    } else if (Idx < 4) {
6490      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6491      MaskPtr[LoIdx] = Idx;
6492      LoIdx++;
6493    } else {
6494      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6495      MaskPtr[HiIdx] = Idx;
6496      HiIdx++;
6497    }
6498  }
6499
6500  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6501  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6502  int MaskOps[] = { -1, -1, -1, -1 };
6503  for (unsigned i = 0; i != 4; ++i)
6504    if (Locs[i].first != -1)
6505      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6506  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6507}
6508
6509static bool MayFoldVectorLoad(SDValue V) {
6510  while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6511    V = V.getOperand(0);
6512
6513  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6514    V = V.getOperand(0);
6515  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6516      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6517    // BUILD_VECTOR (load), undef
6518    V = V.getOperand(0);
6519
6520  return MayFoldLoad(V);
6521}
6522
6523static
6524SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6525  EVT VT = Op.getValueType();
6526
6527  // Canonizalize to v2f64.
6528  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6529  return DAG.getNode(ISD::BITCAST, dl, VT,
6530                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6531                                          V1, DAG));
6532}
6533
6534static
6535SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6536                        bool HasSSE2) {
6537  SDValue V1 = Op.getOperand(0);
6538  SDValue V2 = Op.getOperand(1);
6539  EVT VT = Op.getValueType();
6540
6541  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6542
6543  if (HasSSE2 && VT == MVT::v2f64)
6544    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6545
6546  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6547  return DAG.getNode(ISD::BITCAST, dl, VT,
6548                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6549                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6550                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6551}
6552
6553static
6554SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6555  SDValue V1 = Op.getOperand(0);
6556  SDValue V2 = Op.getOperand(1);
6557  EVT VT = Op.getValueType();
6558
6559  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6560         "unsupported shuffle type");
6561
6562  if (V2.getOpcode() == ISD::UNDEF)
6563    V2 = V1;
6564
6565  // v4i32 or v4f32
6566  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6567}
6568
6569static
6570SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6571  SDValue V1 = Op.getOperand(0);
6572  SDValue V2 = Op.getOperand(1);
6573  EVT VT = Op.getValueType();
6574  unsigned NumElems = VT.getVectorNumElements();
6575
6576  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6577  // operand of these instructions is only memory, so check if there's a
6578  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6579  // same masks.
6580  bool CanFoldLoad = false;
6581
6582  // Trivial case, when V2 comes from a load.
6583  if (MayFoldVectorLoad(V2))
6584    CanFoldLoad = true;
6585
6586  // When V1 is a load, it can be folded later into a store in isel, example:
6587  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6588  //    turns into:
6589  //  (MOVLPSmr addr:$src1, VR128:$src2)
6590  // So, recognize this potential and also use MOVLPS or MOVLPD
6591  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6592    CanFoldLoad = true;
6593
6594  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6595  if (CanFoldLoad) {
6596    if (HasSSE2 && NumElems == 2)
6597      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6598
6599    if (NumElems == 4)
6600      // If we don't care about the second element, proceed to use movss.
6601      if (SVOp->getMaskElt(1) != -1)
6602        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6603  }
6604
6605  // movl and movlp will both match v2i64, but v2i64 is never matched by
6606  // movl earlier because we make it strict to avoid messing with the movlp load
6607  // folding logic (see the code above getMOVLP call). Match it here then,
6608  // this is horrible, but will stay like this until we move all shuffle
6609  // matching to x86 specific nodes. Note that for the 1st condition all
6610  // types are matched with movsd.
6611  if (HasSSE2) {
6612    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6613    // as to remove this logic from here, as much as possible
6614    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6615      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6616    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6617  }
6618
6619  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6620
6621  // Invert the operand order and use SHUFPS to match it.
6622  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6623                              getShuffleSHUFImmediate(SVOp), DAG);
6624}
6625
6626// Reduce a vector shuffle to zext.
6627SDValue
6628X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6629  // PMOVZX is only available from SSE41.
6630  if (!Subtarget->hasSSE41())
6631    return SDValue();
6632
6633  EVT VT = Op.getValueType();
6634
6635  // Only AVX2 support 256-bit vector integer extending.
6636  if (!Subtarget->hasInt256() && VT.is256BitVector())
6637    return SDValue();
6638
6639  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6640  DebugLoc DL = Op.getDebugLoc();
6641  SDValue V1 = Op.getOperand(0);
6642  SDValue V2 = Op.getOperand(1);
6643  unsigned NumElems = VT.getVectorNumElements();
6644
6645  // Extending is an unary operation and the element type of the source vector
6646  // won't be equal to or larger than i64.
6647  if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6648      VT.getVectorElementType() == MVT::i64)
6649    return SDValue();
6650
6651  // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6652  unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6653  while ((1U << Shift) < NumElems) {
6654    if (SVOp->getMaskElt(1U << Shift) == 1)
6655      break;
6656    Shift += 1;
6657    // The maximal ratio is 8, i.e. from i8 to i64.
6658    if (Shift > 3)
6659      return SDValue();
6660  }
6661
6662  // Check the shuffle mask.
6663  unsigned Mask = (1U << Shift) - 1;
6664  for (unsigned i = 0; i != NumElems; ++i) {
6665    int EltIdx = SVOp->getMaskElt(i);
6666    if ((i & Mask) != 0 && EltIdx != -1)
6667      return SDValue();
6668    if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6669      return SDValue();
6670  }
6671
6672  LLVMContext *Context = DAG.getContext();
6673  unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6674  EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6675  EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6676
6677  if (!isTypeLegal(NVT))
6678    return SDValue();
6679
6680  // Simplify the operand as it's prepared to be fed into shuffle.
6681  unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6682  if (V1.getOpcode() == ISD::BITCAST &&
6683      V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6684      V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6685      V1.getOperand(0)
6686        .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6687    // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6688    SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6689    ConstantSDNode *CIdx =
6690      dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6691    // If it's foldable, i.e. normal load with single use, we will let code
6692    // selection to fold it. Otherwise, we will short the conversion sequence.
6693    if (CIdx && CIdx->getZExtValue() == 0 &&
6694        (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6695      if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6696        // The "ext_vec_elt" node is wider than the result node.
6697        // In this case we should extract subvector from V.
6698        // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6699        unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6700        EVT FullVT = V.getValueType();
6701        EVT SubVecVT = EVT::getVectorVT(*Context,
6702                                        FullVT.getVectorElementType(),
6703                                        FullVT.getVectorNumElements()/Ratio);
6704        V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6705                        DAG.getIntPtrConstant(0));
6706      }
6707      V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6708    }
6709  }
6710
6711  return DAG.getNode(ISD::BITCAST, DL, VT,
6712                     DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6713}
6714
6715SDValue
6716X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6717  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6718  MVT VT = Op.getValueType().getSimpleVT();
6719  DebugLoc dl = Op.getDebugLoc();
6720  SDValue V1 = Op.getOperand(0);
6721  SDValue V2 = Op.getOperand(1);
6722
6723  if (isZeroShuffle(SVOp))
6724    return getZeroVector(VT, Subtarget, DAG, dl);
6725
6726  // Handle splat operations
6727  if (SVOp->isSplat()) {
6728    // Use vbroadcast whenever the splat comes from a foldable load
6729    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6730    if (Broadcast.getNode())
6731      return Broadcast;
6732  }
6733
6734  // Check integer expanding shuffles.
6735  SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6736  if (NewOp.getNode())
6737    return NewOp;
6738
6739  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6740  // do it!
6741  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6742      VT == MVT::v16i16 || VT == MVT::v32i8) {
6743    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6744    if (NewOp.getNode())
6745      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6746  } else if ((VT == MVT::v4i32 ||
6747             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6748    // FIXME: Figure out a cleaner way to do this.
6749    // Try to make use of movq to zero out the top part.
6750    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6751      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6752      if (NewOp.getNode()) {
6753        MVT NewVT = NewOp.getValueType().getSimpleVT();
6754        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6755                               NewVT, true, false))
6756          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6757                              DAG, Subtarget, dl);
6758      }
6759    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6760      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6761      if (NewOp.getNode()) {
6762        MVT NewVT = NewOp.getValueType().getSimpleVT();
6763        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6764          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6765                              DAG, Subtarget, dl);
6766      }
6767    }
6768  }
6769  return SDValue();
6770}
6771
6772SDValue
6773X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6774  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6775  SDValue V1 = Op.getOperand(0);
6776  SDValue V2 = Op.getOperand(1);
6777  MVT VT = Op.getValueType().getSimpleVT();
6778  DebugLoc dl = Op.getDebugLoc();
6779  unsigned NumElems = VT.getVectorNumElements();
6780  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6781  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6782  bool V1IsSplat = false;
6783  bool V2IsSplat = false;
6784  bool HasSSE2 = Subtarget->hasSSE2();
6785  bool HasFp256    = Subtarget->hasFp256();
6786  bool HasInt256   = Subtarget->hasInt256();
6787  MachineFunction &MF = DAG.getMachineFunction();
6788  bool OptForSize = MF.getFunction()->getAttributes().
6789    hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6790
6791  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6792
6793  if (V1IsUndef && V2IsUndef)
6794    return DAG.getUNDEF(VT);
6795
6796  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6797
6798  // Vector shuffle lowering takes 3 steps:
6799  //
6800  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6801  //    narrowing and commutation of operands should be handled.
6802  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6803  //    shuffle nodes.
6804  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6805  //    so the shuffle can be broken into other shuffles and the legalizer can
6806  //    try the lowering again.
6807  //
6808  // The general idea is that no vector_shuffle operation should be left to
6809  // be matched during isel, all of them must be converted to a target specific
6810  // node here.
6811
6812  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6813  // narrowing and commutation of operands should be handled. The actual code
6814  // doesn't include all of those, work in progress...
6815  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6816  if (NewOp.getNode())
6817    return NewOp;
6818
6819  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6820
6821  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6822  // unpckh_undef). Only use pshufd if speed is more important than size.
6823  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6824    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6825  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6826    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6827
6828  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6829      V2IsUndef && MayFoldVectorLoad(V1))
6830    return getMOVDDup(Op, dl, V1, DAG);
6831
6832  if (isMOVHLPS_v_undef_Mask(M, VT))
6833    return getMOVHighToLow(Op, dl, DAG);
6834
6835  // Use to match splats
6836  if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6837      (VT == MVT::v2f64 || VT == MVT::v2i64))
6838    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6839
6840  if (isPSHUFDMask(M, VT)) {
6841    // The actual implementation will match the mask in the if above and then
6842    // during isel it can match several different instructions, not only pshufd
6843    // as its name says, sad but true, emulate the behavior for now...
6844    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6845      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6846
6847    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6848
6849    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6850      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6851
6852    if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6853      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6854                                  DAG);
6855
6856    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6857                                TargetMask, DAG);
6858  }
6859
6860  // Check if this can be converted into a logical shift.
6861  bool isLeft = false;
6862  unsigned ShAmt = 0;
6863  SDValue ShVal;
6864  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6865  if (isShift && ShVal.hasOneUse()) {
6866    // If the shifted value has multiple uses, it may be cheaper to use
6867    // v_set0 + movlhps or movhlps, etc.
6868    MVT EltVT = VT.getVectorElementType();
6869    ShAmt *= EltVT.getSizeInBits();
6870    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6871  }
6872
6873  if (isMOVLMask(M, VT)) {
6874    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6875      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6876    if (!isMOVLPMask(M, VT)) {
6877      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6878        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6879
6880      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6881        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6882    }
6883  }
6884
6885  // FIXME: fold these into legal mask.
6886  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6887    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6888
6889  if (isMOVHLPSMask(M, VT))
6890    return getMOVHighToLow(Op, dl, DAG);
6891
6892  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6893    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6894
6895  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6896    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6897
6898  if (isMOVLPMask(M, VT))
6899    return getMOVLP(Op, dl, DAG, HasSSE2);
6900
6901  if (ShouldXformToMOVHLPS(M, VT) ||
6902      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6903    return CommuteVectorShuffle(SVOp, DAG);
6904
6905  if (isShift) {
6906    // No better options. Use a vshldq / vsrldq.
6907    MVT EltVT = VT.getVectorElementType();
6908    ShAmt *= EltVT.getSizeInBits();
6909    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6910  }
6911
6912  bool Commuted = false;
6913  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6914  // 1,1,1,1 -> v8i16 though.
6915  V1IsSplat = isSplatVector(V1.getNode());
6916  V2IsSplat = isSplatVector(V2.getNode());
6917
6918  // Canonicalize the splat or undef, if present, to be on the RHS.
6919  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6920    CommuteVectorShuffleMask(M, NumElems);
6921    std::swap(V1, V2);
6922    std::swap(V1IsSplat, V2IsSplat);
6923    Commuted = true;
6924  }
6925
6926  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6927    // Shuffling low element of v1 into undef, just return v1.
6928    if (V2IsUndef)
6929      return V1;
6930    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6931    // the instruction selector will not match, so get a canonical MOVL with
6932    // swapped operands to undo the commute.
6933    return getMOVL(DAG, dl, VT, V2, V1);
6934  }
6935
6936  if (isUNPCKLMask(M, VT, HasInt256))
6937    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6938
6939  if (isUNPCKHMask(M, VT, HasInt256))
6940    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6941
6942  if (V2IsSplat) {
6943    // Normalize mask so all entries that point to V2 points to its first
6944    // element then try to match unpck{h|l} again. If match, return a
6945    // new vector_shuffle with the corrected mask.p
6946    SmallVector<int, 8> NewMask(M.begin(), M.end());
6947    NormalizeMask(NewMask, NumElems);
6948    if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6949      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6950    if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6951      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6952  }
6953
6954  if (Commuted) {
6955    // Commute is back and try unpck* again.
6956    // FIXME: this seems wrong.
6957    CommuteVectorShuffleMask(M, NumElems);
6958    std::swap(V1, V2);
6959    std::swap(V1IsSplat, V2IsSplat);
6960    Commuted = false;
6961
6962    if (isUNPCKLMask(M, VT, HasInt256))
6963      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6964
6965    if (isUNPCKHMask(M, VT, HasInt256))
6966      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6967  }
6968
6969  // Normalize the node to match x86 shuffle ops if needed
6970  if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6971    return CommuteVectorShuffle(SVOp, DAG);
6972
6973  // The checks below are all present in isShuffleMaskLegal, but they are
6974  // inlined here right now to enable us to directly emit target specific
6975  // nodes, and remove one by one until they don't return Op anymore.
6976
6977  if (isPALIGNRMask(M, VT, Subtarget))
6978    return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6979                                getShufflePALIGNRImmediate(SVOp),
6980                                DAG);
6981
6982  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6983      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6984    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6985      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6986  }
6987
6988  if (isPSHUFHWMask(M, VT, HasInt256))
6989    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6990                                getShufflePSHUFHWImmediate(SVOp),
6991                                DAG);
6992
6993  if (isPSHUFLWMask(M, VT, HasInt256))
6994    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6995                                getShufflePSHUFLWImmediate(SVOp),
6996                                DAG);
6997
6998  if (isSHUFPMask(M, VT, HasFp256))
6999    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7000                                getShuffleSHUFImmediate(SVOp), DAG);
7001
7002  if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7003    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7004  if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7005    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7006
7007  //===--------------------------------------------------------------------===//
7008  // Generate target specific nodes for 128 or 256-bit shuffles only
7009  // supported in the AVX instruction set.
7010  //
7011
7012  // Handle VMOVDDUPY permutations
7013  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7014    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7015
7016  // Handle VPERMILPS/D* permutations
7017  if (isVPERMILPMask(M, VT, HasFp256)) {
7018    if (HasInt256 && VT == MVT::v8i32)
7019      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7020                                  getShuffleSHUFImmediate(SVOp), DAG);
7021    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7022                                getShuffleSHUFImmediate(SVOp), DAG);
7023  }
7024
7025  // Handle VPERM2F128/VPERM2I128 permutations
7026  if (isVPERM2X128Mask(M, VT, HasFp256))
7027    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7028                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7029
7030  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7031  if (BlendOp.getNode())
7032    return BlendOp;
7033
7034  if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7035    SmallVector<SDValue, 8> permclMask;
7036    for (unsigned i = 0; i != 8; ++i) {
7037      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7038    }
7039    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7040                               &permclMask[0], 8);
7041    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7042    return DAG.getNode(X86ISD::VPERMV, dl, VT,
7043                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7044  }
7045
7046  if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7047    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7048                                getShuffleCLImmediate(SVOp), DAG);
7049
7050  //===--------------------------------------------------------------------===//
7051  // Since no target specific shuffle was selected for this generic one,
7052  // lower it into other known shuffles. FIXME: this isn't true yet, but
7053  // this is the plan.
7054  //
7055
7056  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7057  if (VT == MVT::v8i16) {
7058    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7059    if (NewOp.getNode())
7060      return NewOp;
7061  }
7062
7063  if (VT == MVT::v16i8) {
7064    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7065    if (NewOp.getNode())
7066      return NewOp;
7067  }
7068
7069  if (VT == MVT::v32i8) {
7070    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7071    if (NewOp.getNode())
7072      return NewOp;
7073  }
7074
7075  // Handle all 128-bit wide vectors with 4 elements, and match them with
7076  // several different shuffle types.
7077  if (NumElems == 4 && VT.is128BitVector())
7078    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7079
7080  // Handle general 256-bit shuffles
7081  if (VT.is256BitVector())
7082    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7083
7084  return SDValue();
7085}
7086
7087static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7088  MVT VT = Op.getValueType().getSimpleVT();
7089  DebugLoc dl = Op.getDebugLoc();
7090
7091  if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7092    return SDValue();
7093
7094  if (VT.getSizeInBits() == 8) {
7095    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7096                                  Op.getOperand(0), Op.getOperand(1));
7097    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7098                                  DAG.getValueType(VT));
7099    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7100  }
7101
7102  if (VT.getSizeInBits() == 16) {
7103    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7104    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7105    if (Idx == 0)
7106      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7107                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7108                                     DAG.getNode(ISD::BITCAST, dl,
7109                                                 MVT::v4i32,
7110                                                 Op.getOperand(0)),
7111                                     Op.getOperand(1)));
7112    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7113                                  Op.getOperand(0), Op.getOperand(1));
7114    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7115                                  DAG.getValueType(VT));
7116    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7117  }
7118
7119  if (VT == MVT::f32) {
7120    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7121    // the result back to FR32 register. It's only worth matching if the
7122    // result has a single use which is a store or a bitcast to i32.  And in
7123    // the case of a store, it's not worth it if the index is a constant 0,
7124    // because a MOVSSmr can be used instead, which is smaller and faster.
7125    if (!Op.hasOneUse())
7126      return SDValue();
7127    SDNode *User = *Op.getNode()->use_begin();
7128    if ((User->getOpcode() != ISD::STORE ||
7129         (isa<ConstantSDNode>(Op.getOperand(1)) &&
7130          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7131        (User->getOpcode() != ISD::BITCAST ||
7132         User->getValueType(0) != MVT::i32))
7133      return SDValue();
7134    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7135                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7136                                              Op.getOperand(0)),
7137                                              Op.getOperand(1));
7138    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7139  }
7140
7141  if (VT == MVT::i32 || VT == MVT::i64) {
7142    // ExtractPS/pextrq works with constant index.
7143    if (isa<ConstantSDNode>(Op.getOperand(1)))
7144      return Op;
7145  }
7146  return SDValue();
7147}
7148
7149SDValue
7150X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7151                                           SelectionDAG &DAG) const {
7152  if (!isa<ConstantSDNode>(Op.getOperand(1)))
7153    return SDValue();
7154
7155  SDValue Vec = Op.getOperand(0);
7156  MVT VecVT = Vec.getValueType().getSimpleVT();
7157
7158  // If this is a 256-bit vector result, first extract the 128-bit vector and
7159  // then extract the element from the 128-bit vector.
7160  if (VecVT.is256BitVector()) {
7161    DebugLoc dl = Op.getNode()->getDebugLoc();
7162    unsigned NumElems = VecVT.getVectorNumElements();
7163    SDValue Idx = Op.getOperand(1);
7164    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7165
7166    // Get the 128-bit vector.
7167    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7168
7169    if (IdxVal >= NumElems/2)
7170      IdxVal -= NumElems/2;
7171    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7172                       DAG.getConstant(IdxVal, MVT::i32));
7173  }
7174
7175  assert(VecVT.is128BitVector() && "Unexpected vector length");
7176
7177  if (Subtarget->hasSSE41()) {
7178    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7179    if (Res.getNode())
7180      return Res;
7181  }
7182
7183  MVT VT = Op.getValueType().getSimpleVT();
7184  DebugLoc dl = Op.getDebugLoc();
7185  // TODO: handle v16i8.
7186  if (VT.getSizeInBits() == 16) {
7187    SDValue Vec = Op.getOperand(0);
7188    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7189    if (Idx == 0)
7190      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7191                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7192                                     DAG.getNode(ISD::BITCAST, dl,
7193                                                 MVT::v4i32, Vec),
7194                                     Op.getOperand(1)));
7195    // Transform it so it match pextrw which produces a 32-bit result.
7196    MVT EltVT = MVT::i32;
7197    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7198                                  Op.getOperand(0), Op.getOperand(1));
7199    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7200                                  DAG.getValueType(VT));
7201    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7202  }
7203
7204  if (VT.getSizeInBits() == 32) {
7205    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7206    if (Idx == 0)
7207      return Op;
7208
7209    // SHUFPS the element to the lowest double word, then movss.
7210    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7211    MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7212    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7213                                       DAG.getUNDEF(VVT), Mask);
7214    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7215                       DAG.getIntPtrConstant(0));
7216  }
7217
7218  if (VT.getSizeInBits() == 64) {
7219    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7220    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7221    //        to match extract_elt for f64.
7222    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7223    if (Idx == 0)
7224      return Op;
7225
7226    // UNPCKHPD the element to the lowest double word, then movsd.
7227    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7228    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7229    int Mask[2] = { 1, -1 };
7230    MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7231    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7232                                       DAG.getUNDEF(VVT), Mask);
7233    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7234                       DAG.getIntPtrConstant(0));
7235  }
7236
7237  return SDValue();
7238}
7239
7240static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7241  MVT VT = Op.getValueType().getSimpleVT();
7242  MVT EltVT = VT.getVectorElementType();
7243  DebugLoc dl = Op.getDebugLoc();
7244
7245  SDValue N0 = Op.getOperand(0);
7246  SDValue N1 = Op.getOperand(1);
7247  SDValue N2 = Op.getOperand(2);
7248
7249  if (!VT.is128BitVector())
7250    return SDValue();
7251
7252  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7253      isa<ConstantSDNode>(N2)) {
7254    unsigned Opc;
7255    if (VT == MVT::v8i16)
7256      Opc = X86ISD::PINSRW;
7257    else if (VT == MVT::v16i8)
7258      Opc = X86ISD::PINSRB;
7259    else
7260      Opc = X86ISD::PINSRB;
7261
7262    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7263    // argument.
7264    if (N1.getValueType() != MVT::i32)
7265      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7266    if (N2.getValueType() != MVT::i32)
7267      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7268    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7269  }
7270
7271  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7272    // Bits [7:6] of the constant are the source select.  This will always be
7273    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7274    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7275    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7276    // Bits [5:4] of the constant are the destination select.  This is the
7277    //  value of the incoming immediate.
7278    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7279    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7280    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7281    // Create this as a scalar to vector..
7282    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7283    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7284  }
7285
7286  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7287    // PINSR* works with constant index.
7288    return Op;
7289  }
7290  return SDValue();
7291}
7292
7293SDValue
7294X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7295  MVT VT = Op.getValueType().getSimpleVT();
7296  MVT EltVT = VT.getVectorElementType();
7297
7298  DebugLoc dl = Op.getDebugLoc();
7299  SDValue N0 = Op.getOperand(0);
7300  SDValue N1 = Op.getOperand(1);
7301  SDValue N2 = Op.getOperand(2);
7302
7303  // If this is a 256-bit vector result, first extract the 128-bit vector,
7304  // insert the element into the extracted half and then place it back.
7305  if (VT.is256BitVector()) {
7306    if (!isa<ConstantSDNode>(N2))
7307      return SDValue();
7308
7309    // Get the desired 128-bit vector half.
7310    unsigned NumElems = VT.getVectorNumElements();
7311    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7312    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7313
7314    // Insert the element into the desired half.
7315    bool Upper = IdxVal >= NumElems/2;
7316    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7317                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7318
7319    // Insert the changed part back to the 256-bit vector
7320    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7321  }
7322
7323  if (Subtarget->hasSSE41())
7324    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7325
7326  if (EltVT == MVT::i8)
7327    return SDValue();
7328
7329  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7330    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7331    // as its second argument.
7332    if (N1.getValueType() != MVT::i32)
7333      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7334    if (N2.getValueType() != MVT::i32)
7335      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7336    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7337  }
7338  return SDValue();
7339}
7340
7341static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7342  LLVMContext *Context = DAG.getContext();
7343  DebugLoc dl = Op.getDebugLoc();
7344  MVT OpVT = Op.getValueType().getSimpleVT();
7345
7346  // If this is a 256-bit vector result, first insert into a 128-bit
7347  // vector and then insert into the 256-bit vector.
7348  if (!OpVT.is128BitVector()) {
7349    // Insert into a 128-bit vector.
7350    EVT VT128 = EVT::getVectorVT(*Context,
7351                                 OpVT.getVectorElementType(),
7352                                 OpVT.getVectorNumElements() / 2);
7353
7354    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7355
7356    // Insert the 128-bit vector.
7357    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7358  }
7359
7360  if (OpVT == MVT::v1i64 &&
7361      Op.getOperand(0).getValueType() == MVT::i64)
7362    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7363
7364  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7365  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7366  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7367                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7368}
7369
7370// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7371// a simple subregister reference or explicit instructions to grab
7372// upper bits of a vector.
7373static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7374                                      SelectionDAG &DAG) {
7375  if (Subtarget->hasFp256()) {
7376    DebugLoc dl = Op.getNode()->getDebugLoc();
7377    SDValue Vec = Op.getNode()->getOperand(0);
7378    SDValue Idx = Op.getNode()->getOperand(1);
7379
7380    if (Op.getNode()->getValueType(0).is128BitVector() &&
7381        Vec.getNode()->getValueType(0).is256BitVector() &&
7382        isa<ConstantSDNode>(Idx)) {
7383      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7384      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7385    }
7386  }
7387  return SDValue();
7388}
7389
7390// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7391// simple superregister reference or explicit instructions to insert
7392// the upper bits of a vector.
7393static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7394                                     SelectionDAG &DAG) {
7395  if (Subtarget->hasFp256()) {
7396    DebugLoc dl = Op.getNode()->getDebugLoc();
7397    SDValue Vec = Op.getNode()->getOperand(0);
7398    SDValue SubVec = Op.getNode()->getOperand(1);
7399    SDValue Idx = Op.getNode()->getOperand(2);
7400
7401    if (Op.getNode()->getValueType(0).is256BitVector() &&
7402        SubVec.getNode()->getValueType(0).is128BitVector() &&
7403        isa<ConstantSDNode>(Idx)) {
7404      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7405      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7406    }
7407  }
7408  return SDValue();
7409}
7410
7411// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7412// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7413// one of the above mentioned nodes. It has to be wrapped because otherwise
7414// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7415// be used to form addressing mode. These wrapped nodes will be selected
7416// into MOV32ri.
7417SDValue
7418X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7419  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7420
7421  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7422  // global base reg.
7423  unsigned char OpFlag = 0;
7424  unsigned WrapperKind = X86ISD::Wrapper;
7425  CodeModel::Model M = getTargetMachine().getCodeModel();
7426
7427  if (Subtarget->isPICStyleRIPRel() &&
7428      (M == CodeModel::Small || M == CodeModel::Kernel))
7429    WrapperKind = X86ISD::WrapperRIP;
7430  else if (Subtarget->isPICStyleGOT())
7431    OpFlag = X86II::MO_GOTOFF;
7432  else if (Subtarget->isPICStyleStubPIC())
7433    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7434
7435  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7436                                             CP->getAlignment(),
7437                                             CP->getOffset(), OpFlag);
7438  DebugLoc DL = CP->getDebugLoc();
7439  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7440  // With PIC, the address is actually $g + Offset.
7441  if (OpFlag) {
7442    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7443                         DAG.getNode(X86ISD::GlobalBaseReg,
7444                                     DebugLoc(), getPointerTy()),
7445                         Result);
7446  }
7447
7448  return Result;
7449}
7450
7451SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7452  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7453
7454  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7455  // global base reg.
7456  unsigned char OpFlag = 0;
7457  unsigned WrapperKind = X86ISD::Wrapper;
7458  CodeModel::Model M = getTargetMachine().getCodeModel();
7459
7460  if (Subtarget->isPICStyleRIPRel() &&
7461      (M == CodeModel::Small || M == CodeModel::Kernel))
7462    WrapperKind = X86ISD::WrapperRIP;
7463  else if (Subtarget->isPICStyleGOT())
7464    OpFlag = X86II::MO_GOTOFF;
7465  else if (Subtarget->isPICStyleStubPIC())
7466    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7467
7468  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7469                                          OpFlag);
7470  DebugLoc DL = JT->getDebugLoc();
7471  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7472
7473  // With PIC, the address is actually $g + Offset.
7474  if (OpFlag)
7475    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7476                         DAG.getNode(X86ISD::GlobalBaseReg,
7477                                     DebugLoc(), getPointerTy()),
7478                         Result);
7479
7480  return Result;
7481}
7482
7483SDValue
7484X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7485  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7486
7487  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7488  // global base reg.
7489  unsigned char OpFlag = 0;
7490  unsigned WrapperKind = X86ISD::Wrapper;
7491  CodeModel::Model M = getTargetMachine().getCodeModel();
7492
7493  if (Subtarget->isPICStyleRIPRel() &&
7494      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7495    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7496      OpFlag = X86II::MO_GOTPCREL;
7497    WrapperKind = X86ISD::WrapperRIP;
7498  } else if (Subtarget->isPICStyleGOT()) {
7499    OpFlag = X86II::MO_GOT;
7500  } else if (Subtarget->isPICStyleStubPIC()) {
7501    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7502  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7503    OpFlag = X86II::MO_DARWIN_NONLAZY;
7504  }
7505
7506  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7507
7508  DebugLoc DL = Op.getDebugLoc();
7509  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7510
7511  // With PIC, the address is actually $g + Offset.
7512  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7513      !Subtarget->is64Bit()) {
7514    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7515                         DAG.getNode(X86ISD::GlobalBaseReg,
7516                                     DebugLoc(), getPointerTy()),
7517                         Result);
7518  }
7519
7520  // For symbols that require a load from a stub to get the address, emit the
7521  // load.
7522  if (isGlobalStubReference(OpFlag))
7523    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7524                         MachinePointerInfo::getGOT(), false, false, false, 0);
7525
7526  return Result;
7527}
7528
7529SDValue
7530X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7531  // Create the TargetBlockAddressAddress node.
7532  unsigned char OpFlags =
7533    Subtarget->ClassifyBlockAddressReference();
7534  CodeModel::Model M = getTargetMachine().getCodeModel();
7535  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7536  int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7537  DebugLoc dl = Op.getDebugLoc();
7538  SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7539                                             OpFlags);
7540
7541  if (Subtarget->isPICStyleRIPRel() &&
7542      (M == CodeModel::Small || M == CodeModel::Kernel))
7543    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7544  else
7545    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7546
7547  // With PIC, the address is actually $g + Offset.
7548  if (isGlobalRelativeToPICBase(OpFlags)) {
7549    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7550                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7551                         Result);
7552  }
7553
7554  return Result;
7555}
7556
7557SDValue
7558X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7559                                      int64_t Offset, SelectionDAG &DAG) const {
7560  // Create the TargetGlobalAddress node, folding in the constant
7561  // offset if it is legal.
7562  unsigned char OpFlags =
7563    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7564  CodeModel::Model M = getTargetMachine().getCodeModel();
7565  SDValue Result;
7566  if (OpFlags == X86II::MO_NO_FLAG &&
7567      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7568    // A direct static reference to a global.
7569    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7570    Offset = 0;
7571  } else {
7572    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7573  }
7574
7575  if (Subtarget->isPICStyleRIPRel() &&
7576      (M == CodeModel::Small || M == CodeModel::Kernel))
7577    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7578  else
7579    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7580
7581  // With PIC, the address is actually $g + Offset.
7582  if (isGlobalRelativeToPICBase(OpFlags)) {
7583    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7584                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7585                         Result);
7586  }
7587
7588  // For globals that require a load from a stub to get the address, emit the
7589  // load.
7590  if (isGlobalStubReference(OpFlags))
7591    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7592                         MachinePointerInfo::getGOT(), false, false, false, 0);
7593
7594  // If there was a non-zero offset that we didn't fold, create an explicit
7595  // addition for it.
7596  if (Offset != 0)
7597    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7598                         DAG.getConstant(Offset, getPointerTy()));
7599
7600  return Result;
7601}
7602
7603SDValue
7604X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7605  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7606  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7607  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7608}
7609
7610static SDValue
7611GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7612           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7613           unsigned char OperandFlags, bool LocalDynamic = false) {
7614  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7615  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7616  DebugLoc dl = GA->getDebugLoc();
7617  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7618                                           GA->getValueType(0),
7619                                           GA->getOffset(),
7620                                           OperandFlags);
7621
7622  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7623                                           : X86ISD::TLSADDR;
7624
7625  if (InFlag) {
7626    SDValue Ops[] = { Chain,  TGA, *InFlag };
7627    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7628  } else {
7629    SDValue Ops[]  = { Chain, TGA };
7630    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7631  }
7632
7633  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7634  MFI->setAdjustsStack(true);
7635
7636  SDValue Flag = Chain.getValue(1);
7637  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7638}
7639
7640// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7641static SDValue
7642LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7643                                const EVT PtrVT) {
7644  SDValue InFlag;
7645  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7646  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7647                                   DAG.getNode(X86ISD::GlobalBaseReg,
7648                                               DebugLoc(), PtrVT), InFlag);
7649  InFlag = Chain.getValue(1);
7650
7651  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7652}
7653
7654// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7655static SDValue
7656LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7657                                const EVT PtrVT) {
7658  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7659                    X86::RAX, X86II::MO_TLSGD);
7660}
7661
7662static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7663                                           SelectionDAG &DAG,
7664                                           const EVT PtrVT,
7665                                           bool is64Bit) {
7666  DebugLoc dl = GA->getDebugLoc();
7667
7668  // Get the start address of the TLS block for this module.
7669  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7670      .getInfo<X86MachineFunctionInfo>();
7671  MFI->incNumLocalDynamicTLSAccesses();
7672
7673  SDValue Base;
7674  if (is64Bit) {
7675    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7676                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7677  } else {
7678    SDValue InFlag;
7679    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7680        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7681    InFlag = Chain.getValue(1);
7682    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7683                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7684  }
7685
7686  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7687  // of Base.
7688
7689  // Build x@dtpoff.
7690  unsigned char OperandFlags = X86II::MO_DTPOFF;
7691  unsigned WrapperKind = X86ISD::Wrapper;
7692  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7693                                           GA->getValueType(0),
7694                                           GA->getOffset(), OperandFlags);
7695  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7696
7697  // Add x@dtpoff with the base.
7698  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7699}
7700
7701// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7702static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7703                                   const EVT PtrVT, TLSModel::Model model,
7704                                   bool is64Bit, bool isPIC) {
7705  DebugLoc dl = GA->getDebugLoc();
7706
7707  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7708  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7709                                                         is64Bit ? 257 : 256));
7710
7711  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7712                                      DAG.getIntPtrConstant(0),
7713                                      MachinePointerInfo(Ptr),
7714                                      false, false, false, 0);
7715
7716  unsigned char OperandFlags = 0;
7717  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7718  // initialexec.
7719  unsigned WrapperKind = X86ISD::Wrapper;
7720  if (model == TLSModel::LocalExec) {
7721    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7722  } else if (model == TLSModel::InitialExec) {
7723    if (is64Bit) {
7724      OperandFlags = X86II::MO_GOTTPOFF;
7725      WrapperKind = X86ISD::WrapperRIP;
7726    } else {
7727      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7728    }
7729  } else {
7730    llvm_unreachable("Unexpected model");
7731  }
7732
7733  // emit "addl x@ntpoff,%eax" (local exec)
7734  // or "addl x@indntpoff,%eax" (initial exec)
7735  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7736  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7737                                           GA->getValueType(0),
7738                                           GA->getOffset(), OperandFlags);
7739  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7740
7741  if (model == TLSModel::InitialExec) {
7742    if (isPIC && !is64Bit) {
7743      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7744                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7745                           Offset);
7746    }
7747
7748    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7749                         MachinePointerInfo::getGOT(), false, false, false,
7750                         0);
7751  }
7752
7753  // The address of the thread local variable is the add of the thread
7754  // pointer with the offset of the variable.
7755  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7756}
7757
7758SDValue
7759X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7760
7761  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7762  const GlobalValue *GV = GA->getGlobal();
7763
7764  if (Subtarget->isTargetELF()) {
7765    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7766
7767    switch (model) {
7768      case TLSModel::GeneralDynamic:
7769        if (Subtarget->is64Bit())
7770          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7771        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7772      case TLSModel::LocalDynamic:
7773        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7774                                           Subtarget->is64Bit());
7775      case TLSModel::InitialExec:
7776      case TLSModel::LocalExec:
7777        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7778                                   Subtarget->is64Bit(),
7779                        getTargetMachine().getRelocationModel() == Reloc::PIC_);
7780    }
7781    llvm_unreachable("Unknown TLS model.");
7782  }
7783
7784  if (Subtarget->isTargetDarwin()) {
7785    // Darwin only has one model of TLS.  Lower to that.
7786    unsigned char OpFlag = 0;
7787    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7788                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7789
7790    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7791    // global base reg.
7792    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7793                  !Subtarget->is64Bit();
7794    if (PIC32)
7795      OpFlag = X86II::MO_TLVP_PIC_BASE;
7796    else
7797      OpFlag = X86II::MO_TLVP;
7798    DebugLoc DL = Op.getDebugLoc();
7799    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7800                                                GA->getValueType(0),
7801                                                GA->getOffset(), OpFlag);
7802    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7803
7804    // With PIC32, the address is actually $g + Offset.
7805    if (PIC32)
7806      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7807                           DAG.getNode(X86ISD::GlobalBaseReg,
7808                                       DebugLoc(), getPointerTy()),
7809                           Offset);
7810
7811    // Lowering the machine isd will make sure everything is in the right
7812    // location.
7813    SDValue Chain = DAG.getEntryNode();
7814    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7815    SDValue Args[] = { Chain, Offset };
7816    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7817
7818    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7819    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7820    MFI->setAdjustsStack(true);
7821
7822    // And our return value (tls address) is in the standard call return value
7823    // location.
7824    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7825    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7826                              Chain.getValue(1));
7827  }
7828
7829  if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7830    // Just use the implicit TLS architecture
7831    // Need to generate someting similar to:
7832    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7833    //                                  ; from TEB
7834    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7835    //   mov     rcx, qword [rdx+rcx*8]
7836    //   mov     eax, .tls$:tlsvar
7837    //   [rax+rcx] contains the address
7838    // Windows 64bit: gs:0x58
7839    // Windows 32bit: fs:__tls_array
7840
7841    // If GV is an alias then use the aliasee for determining
7842    // thread-localness.
7843    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7844      GV = GA->resolveAliasedGlobal(false);
7845    DebugLoc dl = GA->getDebugLoc();
7846    SDValue Chain = DAG.getEntryNode();
7847
7848    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7849    // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7850    // use its literal value of 0x2C.
7851    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7852                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7853                                                             256)
7854                                        : Type::getInt32PtrTy(*DAG.getContext(),
7855                                                              257));
7856
7857    SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7858      (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7859        DAG.getExternalSymbol("_tls_array", getPointerTy()));
7860
7861    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7862                                        MachinePointerInfo(Ptr),
7863                                        false, false, false, 0);
7864
7865    // Load the _tls_index variable
7866    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7867    if (Subtarget->is64Bit())
7868      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7869                           IDX, MachinePointerInfo(), MVT::i32,
7870                           false, false, 0);
7871    else
7872      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7873                        false, false, false, 0);
7874
7875    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7876                                    getPointerTy());
7877    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7878
7879    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7880    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7881                      false, false, false, 0);
7882
7883    // Get the offset of start of .tls section
7884    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7885                                             GA->getValueType(0),
7886                                             GA->getOffset(), X86II::MO_SECREL);
7887    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7888
7889    // The address of the thread local variable is the add of the thread
7890    // pointer with the offset of the variable.
7891    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7892  }
7893
7894  llvm_unreachable("TLS not implemented for this target.");
7895}
7896
7897/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7898/// and take a 2 x i32 value to shift plus a shift amount.
7899SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7900  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7901  EVT VT = Op.getValueType();
7902  unsigned VTBits = VT.getSizeInBits();
7903  DebugLoc dl = Op.getDebugLoc();
7904  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7905  SDValue ShOpLo = Op.getOperand(0);
7906  SDValue ShOpHi = Op.getOperand(1);
7907  SDValue ShAmt  = Op.getOperand(2);
7908  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7909                                     DAG.getConstant(VTBits - 1, MVT::i8))
7910                       : DAG.getConstant(0, VT);
7911
7912  SDValue Tmp2, Tmp3;
7913  if (Op.getOpcode() == ISD::SHL_PARTS) {
7914    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7915    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7916  } else {
7917    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7918    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7919  }
7920
7921  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7922                                DAG.getConstant(VTBits, MVT::i8));
7923  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7924                             AndNode, DAG.getConstant(0, MVT::i8));
7925
7926  SDValue Hi, Lo;
7927  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7928  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7929  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7930
7931  if (Op.getOpcode() == ISD::SHL_PARTS) {
7932    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7933    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7934  } else {
7935    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7936    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7937  }
7938
7939  SDValue Ops[2] = { Lo, Hi };
7940  return DAG.getMergeValues(Ops, 2, dl);
7941}
7942
7943SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7944                                           SelectionDAG &DAG) const {
7945  EVT SrcVT = Op.getOperand(0).getValueType();
7946
7947  if (SrcVT.isVector())
7948    return SDValue();
7949
7950  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7951         "Unknown SINT_TO_FP to lower!");
7952
7953  // These are really Legal; return the operand so the caller accepts it as
7954  // Legal.
7955  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7956    return Op;
7957  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7958      Subtarget->is64Bit()) {
7959    return Op;
7960  }
7961
7962  DebugLoc dl = Op.getDebugLoc();
7963  unsigned Size = SrcVT.getSizeInBits()/8;
7964  MachineFunction &MF = DAG.getMachineFunction();
7965  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7966  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7967  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7968                               StackSlot,
7969                               MachinePointerInfo::getFixedStack(SSFI),
7970                               false, false, 0);
7971  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7972}
7973
7974SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7975                                     SDValue StackSlot,
7976                                     SelectionDAG &DAG) const {
7977  // Build the FILD
7978  DebugLoc DL = Op.getDebugLoc();
7979  SDVTList Tys;
7980  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7981  if (useSSE)
7982    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7983  else
7984    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7985
7986  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7987
7988  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7989  MachineMemOperand *MMO;
7990  if (FI) {
7991    int SSFI = FI->getIndex();
7992    MMO =
7993      DAG.getMachineFunction()
7994      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7995                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7996  } else {
7997    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7998    StackSlot = StackSlot.getOperand(1);
7999  }
8000  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8001  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8002                                           X86ISD::FILD, DL,
8003                                           Tys, Ops, array_lengthof(Ops),
8004                                           SrcVT, MMO);
8005
8006  if (useSSE) {
8007    Chain = Result.getValue(1);
8008    SDValue InFlag = Result.getValue(2);
8009
8010    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8011    // shouldn't be necessary except that RFP cannot be live across
8012    // multiple blocks. When stackifier is fixed, they can be uncoupled.
8013    MachineFunction &MF = DAG.getMachineFunction();
8014    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8015    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8016    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8017    Tys = DAG.getVTList(MVT::Other);
8018    SDValue Ops[] = {
8019      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8020    };
8021    MachineMemOperand *MMO =
8022      DAG.getMachineFunction()
8023      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8024                            MachineMemOperand::MOStore, SSFISize, SSFISize);
8025
8026    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8027                                    Ops, array_lengthof(Ops),
8028                                    Op.getValueType(), MMO);
8029    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8030                         MachinePointerInfo::getFixedStack(SSFI),
8031                         false, false, false, 0);
8032  }
8033
8034  return Result;
8035}
8036
8037// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8038SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8039                                               SelectionDAG &DAG) const {
8040  // This algorithm is not obvious. Here it is what we're trying to output:
8041  /*
8042     movq       %rax,  %xmm0
8043     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8044     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8045     #ifdef __SSE3__
8046       haddpd   %xmm0, %xmm0
8047     #else
8048       pshufd   $0x4e, %xmm0, %xmm1
8049       addpd    %xmm1, %xmm0
8050     #endif
8051  */
8052
8053  DebugLoc dl = Op.getDebugLoc();
8054  LLVMContext *Context = DAG.getContext();
8055
8056  // Build some magic constants.
8057  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8058  Constant *C0 = ConstantDataVector::get(*Context, CV0);
8059  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8060
8061  SmallVector<Constant*,2> CV1;
8062  CV1.push_back(
8063    ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8064                                      APInt(64, 0x4330000000000000ULL))));
8065  CV1.push_back(
8066    ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8067                                      APInt(64, 0x4530000000000000ULL))));
8068  Constant *C1 = ConstantVector::get(CV1);
8069  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8070
8071  // Load the 64-bit value into an XMM register.
8072  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8073                            Op.getOperand(0));
8074  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8075                              MachinePointerInfo::getConstantPool(),
8076                              false, false, false, 16);
8077  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8078                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8079                              CLod0);
8080
8081  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8082                              MachinePointerInfo::getConstantPool(),
8083                              false, false, false, 16);
8084  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8085  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8086  SDValue Result;
8087
8088  if (Subtarget->hasSSE3()) {
8089    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8090    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8091  } else {
8092    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8093    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8094                                           S2F, 0x4E, DAG);
8095    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8096                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8097                         Sub);
8098  }
8099
8100  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8101                     DAG.getIntPtrConstant(0));
8102}
8103
8104// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8105SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8106                                               SelectionDAG &DAG) const {
8107  DebugLoc dl = Op.getDebugLoc();
8108  // FP constant to bias correct the final result.
8109  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8110                                   MVT::f64);
8111
8112  // Load the 32-bit value into an XMM register.
8113  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8114                             Op.getOperand(0));
8115
8116  // Zero out the upper parts of the register.
8117  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8118
8119  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8120                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8121                     DAG.getIntPtrConstant(0));
8122
8123  // Or the load with the bias.
8124  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8125                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8126                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8127                                                   MVT::v2f64, Load)),
8128                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8129                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8130                                                   MVT::v2f64, Bias)));
8131  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8132                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8133                   DAG.getIntPtrConstant(0));
8134
8135  // Subtract the bias.
8136  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8137
8138  // Handle final rounding.
8139  EVT DestVT = Op.getValueType();
8140
8141  if (DestVT.bitsLT(MVT::f64))
8142    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8143                       DAG.getIntPtrConstant(0));
8144  if (DestVT.bitsGT(MVT::f64))
8145    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8146
8147  // Handle final rounding.
8148  return Sub;
8149}
8150
8151SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8152                                               SelectionDAG &DAG) const {
8153  SDValue N0 = Op.getOperand(0);
8154  EVT SVT = N0.getValueType();
8155  DebugLoc dl = Op.getDebugLoc();
8156
8157  assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8158          SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8159         "Custom UINT_TO_FP is not supported!");
8160
8161  EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8162                             SVT.getVectorNumElements());
8163  return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8164                     DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8165}
8166
8167SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8168                                           SelectionDAG &DAG) const {
8169  SDValue N0 = Op.getOperand(0);
8170  DebugLoc dl = Op.getDebugLoc();
8171
8172  if (Op.getValueType().isVector())
8173    return lowerUINT_TO_FP_vec(Op, DAG);
8174
8175  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8176  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8177  // the optimization here.
8178  if (DAG.SignBitIsZero(N0))
8179    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8180
8181  EVT SrcVT = N0.getValueType();
8182  EVT DstVT = Op.getValueType();
8183  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8184    return LowerUINT_TO_FP_i64(Op, DAG);
8185  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8186    return LowerUINT_TO_FP_i32(Op, DAG);
8187  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8188    return SDValue();
8189
8190  // Make a 64-bit buffer, and use it to build an FILD.
8191  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8192  if (SrcVT == MVT::i32) {
8193    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8194    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8195                                     getPointerTy(), StackSlot, WordOff);
8196    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8197                                  StackSlot, MachinePointerInfo(),
8198                                  false, false, 0);
8199    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8200                                  OffsetSlot, MachinePointerInfo(),
8201                                  false, false, 0);
8202    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8203    return Fild;
8204  }
8205
8206  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8207  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8208                               StackSlot, MachinePointerInfo(),
8209                               false, false, 0);
8210  // For i64 source, we need to add the appropriate power of 2 if the input
8211  // was negative.  This is the same as the optimization in
8212  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8213  // we must be careful to do the computation in x87 extended precision, not
8214  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8215  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8216  MachineMemOperand *MMO =
8217    DAG.getMachineFunction()
8218    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8219                          MachineMemOperand::MOLoad, 8, 8);
8220
8221  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8222  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8223  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8224                                         MVT::i64, MMO);
8225
8226  APInt FF(32, 0x5F800000ULL);
8227
8228  // Check whether the sign bit is set.
8229  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8230                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8231                                 ISD::SETLT);
8232
8233  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8234  SDValue FudgePtr = DAG.getConstantPool(
8235                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8236                                         getPointerTy());
8237
8238  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8239  SDValue Zero = DAG.getIntPtrConstant(0);
8240  SDValue Four = DAG.getIntPtrConstant(4);
8241  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8242                               Zero, Four);
8243  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8244
8245  // Load the value out, extending it from f32 to f80.
8246  // FIXME: Avoid the extend by constructing the right constant pool?
8247  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8248                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8249                                 MVT::f32, false, false, 4);
8250  // Extend everything to 80 bits to force it to be done on x87.
8251  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8252  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8253}
8254
8255std::pair<SDValue,SDValue>
8256X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8257                                    bool IsSigned, bool IsReplace) const {
8258  DebugLoc DL = Op.getDebugLoc();
8259
8260  EVT DstTy = Op.getValueType();
8261
8262  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8263    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8264    DstTy = MVT::i64;
8265  }
8266
8267  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8268         DstTy.getSimpleVT() >= MVT::i16 &&
8269         "Unknown FP_TO_INT to lower!");
8270
8271  // These are really Legal.
8272  if (DstTy == MVT::i32 &&
8273      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8274    return std::make_pair(SDValue(), SDValue());
8275  if (Subtarget->is64Bit() &&
8276      DstTy == MVT::i64 &&
8277      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8278    return std::make_pair(SDValue(), SDValue());
8279
8280  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8281  // stack slot, or into the FTOL runtime function.
8282  MachineFunction &MF = DAG.getMachineFunction();
8283  unsigned MemSize = DstTy.getSizeInBits()/8;
8284  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8285  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8286
8287  unsigned Opc;
8288  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8289    Opc = X86ISD::WIN_FTOL;
8290  else
8291    switch (DstTy.getSimpleVT().SimpleTy) {
8292    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8293    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8294    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8295    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8296    }
8297
8298  SDValue Chain = DAG.getEntryNode();
8299  SDValue Value = Op.getOperand(0);
8300  EVT TheVT = Op.getOperand(0).getValueType();
8301  // FIXME This causes a redundant load/store if the SSE-class value is already
8302  // in memory, such as if it is on the callstack.
8303  if (isScalarFPTypeInSSEReg(TheVT)) {
8304    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8305    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8306                         MachinePointerInfo::getFixedStack(SSFI),
8307                         false, false, 0);
8308    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8309    SDValue Ops[] = {
8310      Chain, StackSlot, DAG.getValueType(TheVT)
8311    };
8312
8313    MachineMemOperand *MMO =
8314      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8315                              MachineMemOperand::MOLoad, MemSize, MemSize);
8316    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8317                                    DstTy, MMO);
8318    Chain = Value.getValue(1);
8319    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8320    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8321  }
8322
8323  MachineMemOperand *MMO =
8324    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8325                            MachineMemOperand::MOStore, MemSize, MemSize);
8326
8327  if (Opc != X86ISD::WIN_FTOL) {
8328    // Build the FP_TO_INT*_IN_MEM
8329    SDValue Ops[] = { Chain, Value, StackSlot };
8330    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8331                                           Ops, 3, DstTy, MMO);
8332    return std::make_pair(FIST, StackSlot);
8333  } else {
8334    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8335      DAG.getVTList(MVT::Other, MVT::Glue),
8336      Chain, Value);
8337    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8338      MVT::i32, ftol.getValue(1));
8339    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8340      MVT::i32, eax.getValue(2));
8341    SDValue Ops[] = { eax, edx };
8342    SDValue pair = IsReplace
8343      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8344      : DAG.getMergeValues(Ops, 2, DL);
8345    return std::make_pair(pair, SDValue());
8346  }
8347}
8348
8349static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8350                              const X86Subtarget *Subtarget) {
8351  MVT VT = Op->getValueType(0).getSimpleVT();
8352  SDValue In = Op->getOperand(0);
8353  MVT InVT = In.getValueType().getSimpleVT();
8354  DebugLoc dl = Op->getDebugLoc();
8355
8356  // Optimize vectors in AVX mode:
8357  //
8358  //   v8i16 -> v8i32
8359  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8360  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8361  //   Concat upper and lower parts.
8362  //
8363  //   v4i32 -> v4i64
8364  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8365  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8366  //   Concat upper and lower parts.
8367  //
8368
8369  if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8370      ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8371    return SDValue();
8372
8373  if (Subtarget->hasInt256())
8374    return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8375
8376  SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8377  SDValue Undef = DAG.getUNDEF(InVT);
8378  bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8379  SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8380  SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8381
8382  MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8383                             VT.getVectorNumElements()/2);
8384
8385  OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8386  OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8387
8388  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8389}
8390
8391SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8392                                           SelectionDAG &DAG) const {
8393  if (Subtarget->hasFp256()) {
8394    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8395    if (Res.getNode())
8396      return Res;
8397  }
8398
8399  return SDValue();
8400}
8401SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8402                                            SelectionDAG &DAG) const {
8403  DebugLoc DL = Op.getDebugLoc();
8404  MVT VT = Op.getValueType().getSimpleVT();
8405  SDValue In = Op.getOperand(0);
8406  MVT SVT = In.getValueType().getSimpleVT();
8407
8408  if (Subtarget->hasFp256()) {
8409    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8410    if (Res.getNode())
8411      return Res;
8412  }
8413
8414  if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8415      VT.getVectorNumElements() != SVT.getVectorNumElements())
8416    return SDValue();
8417
8418  assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8419
8420  // AVX2 has better support of integer extending.
8421  if (Subtarget->hasInt256())
8422    return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8423
8424  SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8425  static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8426  SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8427                           DAG.getVectorShuffle(MVT::v8i16, DL, In,
8428                                                DAG.getUNDEF(MVT::v8i16),
8429                                                &Mask[0]));
8430
8431  return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8432}
8433
8434SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8435  DebugLoc DL = Op.getDebugLoc();
8436  MVT VT = Op.getValueType().getSimpleVT();
8437  SDValue In = Op.getOperand(0);
8438  MVT SVT = In.getValueType().getSimpleVT();
8439
8440  if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8441    // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8442    if (Subtarget->hasInt256()) {
8443      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8444      In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8445      In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8446                                ShufMask);
8447      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8448                         DAG.getIntPtrConstant(0));
8449    }
8450
8451    // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8452    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8453                               DAG.getIntPtrConstant(0));
8454    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8455                               DAG.getIntPtrConstant(2));
8456
8457    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8458    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8459
8460    // The PSHUFD mask:
8461    static const int ShufMask1[] = {0, 2, 0, 0};
8462    SDValue Undef = DAG.getUNDEF(VT);
8463    OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8464    OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8465
8466    // The MOVLHPS mask:
8467    static const int ShufMask2[] = {0, 1, 4, 5};
8468    return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8469  }
8470
8471  if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8472    // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8473    if (Subtarget->hasInt256()) {
8474      In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8475
8476      SmallVector<SDValue,32> pshufbMask;
8477      for (unsigned i = 0; i < 2; ++i) {
8478        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8479        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8480        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8481        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8482        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8483        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8484        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8485        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8486        for (unsigned j = 0; j < 8; ++j)
8487          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8488      }
8489      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8490                               &pshufbMask[0], 32);
8491      In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8492      In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8493
8494      static const int ShufMask[] = {0,  2,  -1,  -1};
8495      In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8496                                &ShufMask[0]);
8497      In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8498                       DAG.getIntPtrConstant(0));
8499      return DAG.getNode(ISD::BITCAST, DL, VT, In);
8500    }
8501
8502    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8503                               DAG.getIntPtrConstant(0));
8504
8505    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8506                               DAG.getIntPtrConstant(4));
8507
8508    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8509    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8510
8511    // The PSHUFB mask:
8512    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8513                                   -1, -1, -1, -1, -1, -1, -1, -1};
8514
8515    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8516    OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8517    OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8518
8519    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8520    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8521
8522    // The MOVLHPS Mask:
8523    static const int ShufMask2[] = {0, 1, 4, 5};
8524    SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8525    return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8526  }
8527
8528  // Handle truncation of V256 to V128 using shuffles.
8529  if (!VT.is128BitVector() || !SVT.is256BitVector())
8530    return SDValue();
8531
8532  assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8533         "Invalid op");
8534  assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8535
8536  unsigned NumElems = VT.getVectorNumElements();
8537  EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8538                             NumElems * 2);
8539
8540  SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8541  // Prepare truncation shuffle mask
8542  for (unsigned i = 0; i != NumElems; ++i)
8543    MaskVec[i] = i * 2;
8544  SDValue V = DAG.getVectorShuffle(NVT, DL,
8545                                   DAG.getNode(ISD::BITCAST, DL, NVT, In),
8546                                   DAG.getUNDEF(NVT), &MaskVec[0]);
8547  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8548                     DAG.getIntPtrConstant(0));
8549}
8550
8551SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8552                                           SelectionDAG &DAG) const {
8553  MVT VT = Op.getValueType().getSimpleVT();
8554  if (VT.isVector()) {
8555    if (VT == MVT::v8i16)
8556      return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8557                         DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8558                                     MVT::v8i32, Op.getOperand(0)));
8559    return SDValue();
8560  }
8561
8562  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8563    /*IsSigned=*/ true, /*IsReplace=*/ false);
8564  SDValue FIST = Vals.first, StackSlot = Vals.second;
8565  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8566  if (FIST.getNode() == 0) return Op;
8567
8568  if (StackSlot.getNode())
8569    // Load the result.
8570    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8571                       FIST, StackSlot, MachinePointerInfo(),
8572                       false, false, false, 0);
8573
8574  // The node is the result.
8575  return FIST;
8576}
8577
8578SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8579                                           SelectionDAG &DAG) const {
8580  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8581    /*IsSigned=*/ false, /*IsReplace=*/ false);
8582  SDValue FIST = Vals.first, StackSlot = Vals.second;
8583  assert(FIST.getNode() && "Unexpected failure");
8584
8585  if (StackSlot.getNode())
8586    // Load the result.
8587    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8588                       FIST, StackSlot, MachinePointerInfo(),
8589                       false, false, false, 0);
8590
8591  // The node is the result.
8592  return FIST;
8593}
8594
8595static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8596  DebugLoc DL = Op.getDebugLoc();
8597  MVT VT = Op.getValueType().getSimpleVT();
8598  SDValue In = Op.getOperand(0);
8599  MVT SVT = In.getValueType().getSimpleVT();
8600
8601  assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8602
8603  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8604                     DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8605                                 In, DAG.getUNDEF(SVT)));
8606}
8607
8608SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8609  LLVMContext *Context = DAG.getContext();
8610  DebugLoc dl = Op.getDebugLoc();
8611  MVT VT = Op.getValueType().getSimpleVT();
8612  MVT EltVT = VT;
8613  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8614  if (VT.isVector()) {
8615    EltVT = VT.getVectorElementType();
8616    NumElts = VT.getVectorNumElements();
8617  }
8618  Constant *C;
8619  if (EltVT == MVT::f64)
8620    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8621                                          APInt(64, ~(1ULL << 63))));
8622  else
8623    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8624                                          APInt(32, ~(1U << 31))));
8625  C = ConstantVector::getSplat(NumElts, C);
8626  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8627  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8628  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8629                             MachinePointerInfo::getConstantPool(),
8630                             false, false, false, Alignment);
8631  if (VT.isVector()) {
8632    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8633    return DAG.getNode(ISD::BITCAST, dl, VT,
8634                       DAG.getNode(ISD::AND, dl, ANDVT,
8635                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8636                                               Op.getOperand(0)),
8637                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8638  }
8639  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8640}
8641
8642SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8643  LLVMContext *Context = DAG.getContext();
8644  DebugLoc dl = Op.getDebugLoc();
8645  MVT VT = Op.getValueType().getSimpleVT();
8646  MVT EltVT = VT;
8647  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8648  if (VT.isVector()) {
8649    EltVT = VT.getVectorElementType();
8650    NumElts = VT.getVectorNumElements();
8651  }
8652  Constant *C;
8653  if (EltVT == MVT::f64)
8654    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8655                                          APInt(64, 1ULL << 63)));
8656  else
8657    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8658                                          APInt(32, 1U << 31)));
8659  C = ConstantVector::getSplat(NumElts, C);
8660  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8661  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8662  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8663                             MachinePointerInfo::getConstantPool(),
8664                             false, false, false, Alignment);
8665  if (VT.isVector()) {
8666    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8667    return DAG.getNode(ISD::BITCAST, dl, VT,
8668                       DAG.getNode(ISD::XOR, dl, XORVT,
8669                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8670                                               Op.getOperand(0)),
8671                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8672  }
8673
8674  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8675}
8676
8677SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8678  LLVMContext *Context = DAG.getContext();
8679  SDValue Op0 = Op.getOperand(0);
8680  SDValue Op1 = Op.getOperand(1);
8681  DebugLoc dl = Op.getDebugLoc();
8682  MVT VT = Op.getValueType().getSimpleVT();
8683  MVT SrcVT = Op1.getValueType().getSimpleVT();
8684
8685  // If second operand is smaller, extend it first.
8686  if (SrcVT.bitsLT(VT)) {
8687    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8688    SrcVT = VT;
8689  }
8690  // And if it is bigger, shrink it first.
8691  if (SrcVT.bitsGT(VT)) {
8692    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8693    SrcVT = VT;
8694  }
8695
8696  // At this point the operands and the result should have the same
8697  // type, and that won't be f80 since that is not custom lowered.
8698
8699  // First get the sign bit of second operand.
8700  SmallVector<Constant*,4> CV;
8701  if (SrcVT == MVT::f64) {
8702    const fltSemantics &Sem = APFloat::IEEEdouble;
8703    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8704    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8705  } else {
8706    const fltSemantics &Sem = APFloat::IEEEsingle;
8707    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8708    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8709    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8710    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8711  }
8712  Constant *C = ConstantVector::get(CV);
8713  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8714  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8715                              MachinePointerInfo::getConstantPool(),
8716                              false, false, false, 16);
8717  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8718
8719  // Shift sign bit right or left if the two operands have different types.
8720  if (SrcVT.bitsGT(VT)) {
8721    // Op0 is MVT::f32, Op1 is MVT::f64.
8722    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8723    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8724                          DAG.getConstant(32, MVT::i32));
8725    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8726    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8727                          DAG.getIntPtrConstant(0));
8728  }
8729
8730  // Clear first operand sign bit.
8731  CV.clear();
8732  if (VT == MVT::f64) {
8733    const fltSemantics &Sem = APFloat::IEEEdouble;
8734    CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8735                                                   APInt(64, ~(1ULL << 63)))));
8736    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8737  } else {
8738    const fltSemantics &Sem = APFloat::IEEEsingle;
8739    CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8740                                                   APInt(32, ~(1U << 31)))));
8741    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8742    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8743    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8744  }
8745  C = ConstantVector::get(CV);
8746  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8747  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8748                              MachinePointerInfo::getConstantPool(),
8749                              false, false, false, 16);
8750  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8751
8752  // Or the value with the sign bit.
8753  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8754}
8755
8756static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8757  SDValue N0 = Op.getOperand(0);
8758  DebugLoc dl = Op.getDebugLoc();
8759  MVT VT = Op.getValueType().getSimpleVT();
8760
8761  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8762  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8763                                  DAG.getConstant(1, VT));
8764  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8765}
8766
8767// LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8768//
8769SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8770                                                  SelectionDAG &DAG) const {
8771  assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8772
8773  if (!Subtarget->hasSSE41())
8774    return SDValue();
8775
8776  if (!Op->hasOneUse())
8777    return SDValue();
8778
8779  SDNode *N = Op.getNode();
8780  DebugLoc DL = N->getDebugLoc();
8781
8782  SmallVector<SDValue, 8> Opnds;
8783  DenseMap<SDValue, unsigned> VecInMap;
8784  EVT VT = MVT::Other;
8785
8786  // Recognize a special case where a vector is casted into wide integer to
8787  // test all 0s.
8788  Opnds.push_back(N->getOperand(0));
8789  Opnds.push_back(N->getOperand(1));
8790
8791  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8792    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8793    // BFS traverse all OR'd operands.
8794    if (I->getOpcode() == ISD::OR) {
8795      Opnds.push_back(I->getOperand(0));
8796      Opnds.push_back(I->getOperand(1));
8797      // Re-evaluate the number of nodes to be traversed.
8798      e += 2; // 2 more nodes (LHS and RHS) are pushed.
8799      continue;
8800    }
8801
8802    // Quit if a non-EXTRACT_VECTOR_ELT
8803    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8804      return SDValue();
8805
8806    // Quit if without a constant index.
8807    SDValue Idx = I->getOperand(1);
8808    if (!isa<ConstantSDNode>(Idx))
8809      return SDValue();
8810
8811    SDValue ExtractedFromVec = I->getOperand(0);
8812    DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8813    if (M == VecInMap.end()) {
8814      VT = ExtractedFromVec.getValueType();
8815      // Quit if not 128/256-bit vector.
8816      if (!VT.is128BitVector() && !VT.is256BitVector())
8817        return SDValue();
8818      // Quit if not the same type.
8819      if (VecInMap.begin() != VecInMap.end() &&
8820          VT != VecInMap.begin()->first.getValueType())
8821        return SDValue();
8822      M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8823    }
8824    M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8825  }
8826
8827  assert((VT.is128BitVector() || VT.is256BitVector()) &&
8828         "Not extracted from 128-/256-bit vector.");
8829
8830  unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8831  SmallVector<SDValue, 8> VecIns;
8832
8833  for (DenseMap<SDValue, unsigned>::const_iterator
8834        I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8835    // Quit if not all elements are used.
8836    if (I->second != FullMask)
8837      return SDValue();
8838    VecIns.push_back(I->first);
8839  }
8840
8841  EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8842
8843  // Cast all vectors into TestVT for PTEST.
8844  for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8845    VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8846
8847  // If more than one full vectors are evaluated, OR them first before PTEST.
8848  for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8849    // Each iteration will OR 2 nodes and append the result until there is only
8850    // 1 node left, i.e. the final OR'd value of all vectors.
8851    SDValue LHS = VecIns[Slot];
8852    SDValue RHS = VecIns[Slot + 1];
8853    VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8854  }
8855
8856  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8857                     VecIns.back(), VecIns.back());
8858}
8859
8860/// Emit nodes that will be selected as "test Op0,Op0", or something
8861/// equivalent.
8862SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8863                                    SelectionDAG &DAG) const {
8864  DebugLoc dl = Op.getDebugLoc();
8865
8866  // CF and OF aren't always set the way we want. Determine which
8867  // of these we need.
8868  bool NeedCF = false;
8869  bool NeedOF = false;
8870  switch (X86CC) {
8871  default: break;
8872  case X86::COND_A: case X86::COND_AE:
8873  case X86::COND_B: case X86::COND_BE:
8874    NeedCF = true;
8875    break;
8876  case X86::COND_G: case X86::COND_GE:
8877  case X86::COND_L: case X86::COND_LE:
8878  case X86::COND_O: case X86::COND_NO:
8879    NeedOF = true;
8880    break;
8881  }
8882
8883  // See if we can use the EFLAGS value from the operand instead of
8884  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8885  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8886  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8887    // Emit a CMP with 0, which is the TEST pattern.
8888    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8889                       DAG.getConstant(0, Op.getValueType()));
8890
8891  unsigned Opcode = 0;
8892  unsigned NumOperands = 0;
8893
8894  // Truncate operations may prevent the merge of the SETCC instruction
8895  // and the arithmetic intruction before it. Attempt to truncate the operands
8896  // of the arithmetic instruction and use a reduced bit-width instruction.
8897  bool NeedTruncation = false;
8898  SDValue ArithOp = Op;
8899  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8900    SDValue Arith = Op->getOperand(0);
8901    // Both the trunc and the arithmetic op need to have one user each.
8902    if (Arith->hasOneUse())
8903      switch (Arith.getOpcode()) {
8904        default: break;
8905        case ISD::ADD:
8906        case ISD::SUB:
8907        case ISD::AND:
8908        case ISD::OR:
8909        case ISD::XOR: {
8910          NeedTruncation = true;
8911          ArithOp = Arith;
8912        }
8913      }
8914  }
8915
8916  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8917  // which may be the result of a CAST.  We use the variable 'Op', which is the
8918  // non-casted variable when we check for possible users.
8919  switch (ArithOp.getOpcode()) {
8920  case ISD::ADD:
8921    // Due to an isel shortcoming, be conservative if this add is likely to be
8922    // selected as part of a load-modify-store instruction. When the root node
8923    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8924    // uses of other nodes in the match, such as the ADD in this case. This
8925    // leads to the ADD being left around and reselected, with the result being
8926    // two adds in the output.  Alas, even if none our users are stores, that
8927    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8928    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8929    // climbing the DAG back to the root, and it doesn't seem to be worth the
8930    // effort.
8931    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8932         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8933      if (UI->getOpcode() != ISD::CopyToReg &&
8934          UI->getOpcode() != ISD::SETCC &&
8935          UI->getOpcode() != ISD::STORE)
8936        goto default_case;
8937
8938    if (ConstantSDNode *C =
8939        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8940      // An add of one will be selected as an INC.
8941      if (C->getAPIntValue() == 1) {
8942        Opcode = X86ISD::INC;
8943        NumOperands = 1;
8944        break;
8945      }
8946
8947      // An add of negative one (subtract of one) will be selected as a DEC.
8948      if (C->getAPIntValue().isAllOnesValue()) {
8949        Opcode = X86ISD::DEC;
8950        NumOperands = 1;
8951        break;
8952      }
8953    }
8954
8955    // Otherwise use a regular EFLAGS-setting add.
8956    Opcode = X86ISD::ADD;
8957    NumOperands = 2;
8958    break;
8959  case ISD::AND: {
8960    // If the primary and result isn't used, don't bother using X86ISD::AND,
8961    // because a TEST instruction will be better.
8962    bool NonFlagUse = false;
8963    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8964           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8965      SDNode *User = *UI;
8966      unsigned UOpNo = UI.getOperandNo();
8967      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8968        // Look pass truncate.
8969        UOpNo = User->use_begin().getOperandNo();
8970        User = *User->use_begin();
8971      }
8972
8973      if (User->getOpcode() != ISD::BRCOND &&
8974          User->getOpcode() != ISD::SETCC &&
8975          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8976        NonFlagUse = true;
8977        break;
8978      }
8979    }
8980
8981    if (!NonFlagUse)
8982      break;
8983  }
8984    // FALL THROUGH
8985  case ISD::SUB:
8986  case ISD::OR:
8987  case ISD::XOR:
8988    // Due to the ISEL shortcoming noted above, be conservative if this op is
8989    // likely to be selected as part of a load-modify-store instruction.
8990    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8991           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8992      if (UI->getOpcode() == ISD::STORE)
8993        goto default_case;
8994
8995    // Otherwise use a regular EFLAGS-setting instruction.
8996    switch (ArithOp.getOpcode()) {
8997    default: llvm_unreachable("unexpected operator!");
8998    case ISD::SUB: Opcode = X86ISD::SUB; break;
8999    case ISD::XOR: Opcode = X86ISD::XOR; break;
9000    case ISD::AND: Opcode = X86ISD::AND; break;
9001    case ISD::OR: {
9002      if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9003        SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9004        if (EFLAGS.getNode())
9005          return EFLAGS;
9006      }
9007      Opcode = X86ISD::OR;
9008      break;
9009    }
9010    }
9011
9012    NumOperands = 2;
9013    break;
9014  case X86ISD::ADD:
9015  case X86ISD::SUB:
9016  case X86ISD::INC:
9017  case X86ISD::DEC:
9018  case X86ISD::OR:
9019  case X86ISD::XOR:
9020  case X86ISD::AND:
9021    return SDValue(Op.getNode(), 1);
9022  default:
9023  default_case:
9024    break;
9025  }
9026
9027  // If we found that truncation is beneficial, perform the truncation and
9028  // update 'Op'.
9029  if (NeedTruncation) {
9030    EVT VT = Op.getValueType();
9031    SDValue WideVal = Op->getOperand(0);
9032    EVT WideVT = WideVal.getValueType();
9033    unsigned ConvertedOp = 0;
9034    // Use a target machine opcode to prevent further DAGCombine
9035    // optimizations that may separate the arithmetic operations
9036    // from the setcc node.
9037    switch (WideVal.getOpcode()) {
9038      default: break;
9039      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9040      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9041      case ISD::AND: ConvertedOp = X86ISD::AND; break;
9042      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9043      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9044    }
9045
9046    if (ConvertedOp) {
9047      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9048      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9049        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9050        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9051        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9052      }
9053    }
9054  }
9055
9056  if (Opcode == 0)
9057    // Emit a CMP with 0, which is the TEST pattern.
9058    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9059                       DAG.getConstant(0, Op.getValueType()));
9060
9061  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9062  SmallVector<SDValue, 4> Ops;
9063  for (unsigned i = 0; i != NumOperands; ++i)
9064    Ops.push_back(Op.getOperand(i));
9065
9066  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9067  DAG.ReplaceAllUsesWith(Op, New);
9068  return SDValue(New.getNode(), 1);
9069}
9070
9071/// Emit nodes that will be selected as "cmp Op0,Op1", or something
9072/// equivalent.
9073SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9074                                   SelectionDAG &DAG) const {
9075  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9076    if (C->getAPIntValue() == 0)
9077      return EmitTest(Op0, X86CC, DAG);
9078
9079  DebugLoc dl = Op0.getDebugLoc();
9080  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9081       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9082    // Use SUB instead of CMP to enable CSE between SUB and CMP.
9083    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9084    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9085                              Op0, Op1);
9086    return SDValue(Sub.getNode(), 1);
9087  }
9088  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9089}
9090
9091/// Convert a comparison if required by the subtarget.
9092SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9093                                                 SelectionDAG &DAG) const {
9094  // If the subtarget does not support the FUCOMI instruction, floating-point
9095  // comparisons have to be converted.
9096  if (Subtarget->hasCMov() ||
9097      Cmp.getOpcode() != X86ISD::CMP ||
9098      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9099      !Cmp.getOperand(1).getValueType().isFloatingPoint())
9100    return Cmp;
9101
9102  // The instruction selector will select an FUCOM instruction instead of
9103  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9104  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9105  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9106  DebugLoc dl = Cmp.getDebugLoc();
9107  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9108  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9109  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9110                            DAG.getConstant(8, MVT::i8));
9111  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9112  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9113}
9114
9115static bool isAllOnes(SDValue V) {
9116  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9117  return C && C->isAllOnesValue();
9118}
9119
9120/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9121/// if it's possible.
9122SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9123                                     DebugLoc dl, SelectionDAG &DAG) const {
9124  SDValue Op0 = And.getOperand(0);
9125  SDValue Op1 = And.getOperand(1);
9126  if (Op0.getOpcode() == ISD::TRUNCATE)
9127    Op0 = Op0.getOperand(0);
9128  if (Op1.getOpcode() == ISD::TRUNCATE)
9129    Op1 = Op1.getOperand(0);
9130
9131  SDValue LHS, RHS;
9132  if (Op1.getOpcode() == ISD::SHL)
9133    std::swap(Op0, Op1);
9134  if (Op0.getOpcode() == ISD::SHL) {
9135    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9136      if (And00C->getZExtValue() == 1) {
9137        // If we looked past a truncate, check that it's only truncating away
9138        // known zeros.
9139        unsigned BitWidth = Op0.getValueSizeInBits();
9140        unsigned AndBitWidth = And.getValueSizeInBits();
9141        if (BitWidth > AndBitWidth) {
9142          APInt Zeros, Ones;
9143          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9144          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9145            return SDValue();
9146        }
9147        LHS = Op1;
9148        RHS = Op0.getOperand(1);
9149      }
9150  } else if (Op1.getOpcode() == ISD::Constant) {
9151    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9152    uint64_t AndRHSVal = AndRHS->getZExtValue();
9153    SDValue AndLHS = Op0;
9154
9155    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9156      LHS = AndLHS.getOperand(0);
9157      RHS = AndLHS.getOperand(1);
9158    }
9159
9160    // Use BT if the immediate can't be encoded in a TEST instruction.
9161    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9162      LHS = AndLHS;
9163      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9164    }
9165  }
9166
9167  if (LHS.getNode()) {
9168    // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9169    // the condition code later.
9170    bool Invert = false;
9171    if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9172      Invert = true;
9173      LHS = LHS.getOperand(0);
9174    }
9175
9176    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9177    // instruction.  Since the shift amount is in-range-or-undefined, we know
9178    // that doing a bittest on the i32 value is ok.  We extend to i32 because
9179    // the encoding for the i16 version is larger than the i32 version.
9180    // Also promote i16 to i32 for performance / code size reason.
9181    if (LHS.getValueType() == MVT::i8 ||
9182        LHS.getValueType() == MVT::i16)
9183      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9184
9185    // If the operand types disagree, extend the shift amount to match.  Since
9186    // BT ignores high bits (like shifts) we can use anyextend.
9187    if (LHS.getValueType() != RHS.getValueType())
9188      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9189
9190    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9191    X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9192    // Flip the condition if the LHS was a not instruction
9193    if (Invert)
9194      Cond = X86::GetOppositeBranchCondition(Cond);
9195    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9196                       DAG.getConstant(Cond, MVT::i8), BT);
9197  }
9198
9199  return SDValue();
9200}
9201
9202// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9203// ones, and then concatenate the result back.
9204static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9205  MVT VT = Op.getValueType().getSimpleVT();
9206
9207  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9208         "Unsupported value type for operation");
9209
9210  unsigned NumElems = VT.getVectorNumElements();
9211  DebugLoc dl = Op.getDebugLoc();
9212  SDValue CC = Op.getOperand(2);
9213
9214  // Extract the LHS vectors
9215  SDValue LHS = Op.getOperand(0);
9216  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9217  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9218
9219  // Extract the RHS vectors
9220  SDValue RHS = Op.getOperand(1);
9221  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9222  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9223
9224  // Issue the operation on the smaller types and concatenate the result back
9225  MVT EltVT = VT.getVectorElementType();
9226  MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9227  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9228                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9229                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9230}
9231
9232static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9233                           SelectionDAG &DAG) {
9234  SDValue Cond;
9235  SDValue Op0 = Op.getOperand(0);
9236  SDValue Op1 = Op.getOperand(1);
9237  SDValue CC = Op.getOperand(2);
9238  MVT VT = Op.getValueType().getSimpleVT();
9239  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9240  bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9241  DebugLoc dl = Op.getDebugLoc();
9242
9243  if (isFP) {
9244#ifndef NDEBUG
9245    MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9246    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9247#endif
9248
9249    unsigned SSECC;
9250    bool Swap = false;
9251
9252    // SSE Condition code mapping:
9253    //  0 - EQ
9254    //  1 - LT
9255    //  2 - LE
9256    //  3 - UNORD
9257    //  4 - NEQ
9258    //  5 - NLT
9259    //  6 - NLE
9260    //  7 - ORD
9261    switch (SetCCOpcode) {
9262    default: llvm_unreachable("Unexpected SETCC condition");
9263    case ISD::SETOEQ:
9264    case ISD::SETEQ:  SSECC = 0; break;
9265    case ISD::SETOGT:
9266    case ISD::SETGT: Swap = true; // Fallthrough
9267    case ISD::SETLT:
9268    case ISD::SETOLT: SSECC = 1; break;
9269    case ISD::SETOGE:
9270    case ISD::SETGE: Swap = true; // Fallthrough
9271    case ISD::SETLE:
9272    case ISD::SETOLE: SSECC = 2; break;
9273    case ISD::SETUO:  SSECC = 3; break;
9274    case ISD::SETUNE:
9275    case ISD::SETNE:  SSECC = 4; break;
9276    case ISD::SETULE: Swap = true; // Fallthrough
9277    case ISD::SETUGE: SSECC = 5; break;
9278    case ISD::SETULT: Swap = true; // Fallthrough
9279    case ISD::SETUGT: SSECC = 6; break;
9280    case ISD::SETO:   SSECC = 7; break;
9281    case ISD::SETUEQ:
9282    case ISD::SETONE: SSECC = 8; break;
9283    }
9284    if (Swap)
9285      std::swap(Op0, Op1);
9286
9287    // In the two special cases we can't handle, emit two comparisons.
9288    if (SSECC == 8) {
9289      unsigned CC0, CC1;
9290      unsigned CombineOpc;
9291      if (SetCCOpcode == ISD::SETUEQ) {
9292        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9293      } else {
9294        assert(SetCCOpcode == ISD::SETONE);
9295        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9296      }
9297
9298      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9299                                 DAG.getConstant(CC0, MVT::i8));
9300      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9301                                 DAG.getConstant(CC1, MVT::i8));
9302      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9303    }
9304    // Handle all other FP comparisons here.
9305    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9306                       DAG.getConstant(SSECC, MVT::i8));
9307  }
9308
9309  // Break 256-bit integer vector compare into smaller ones.
9310  if (VT.is256BitVector() && !Subtarget->hasInt256())
9311    return Lower256IntVSETCC(Op, DAG);
9312
9313  // We are handling one of the integer comparisons here.  Since SSE only has
9314  // GT and EQ comparisons for integer, swapping operands and multiple
9315  // operations may be required for some comparisons.
9316  unsigned Opc;
9317  bool Swap = false, Invert = false, FlipSigns = false;
9318
9319  switch (SetCCOpcode) {
9320  default: llvm_unreachable("Unexpected SETCC condition");
9321  case ISD::SETNE:  Invert = true;
9322  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9323  case ISD::SETLT:  Swap = true;
9324  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9325  case ISD::SETGE:  Swap = true;
9326  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9327  case ISD::SETULT: Swap = true;
9328  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9329  case ISD::SETUGE: Swap = true;
9330  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9331  }
9332  if (Swap)
9333    std::swap(Op0, Op1);
9334
9335  // Check that the operation in question is available (most are plain SSE2,
9336  // but PCMPGTQ and PCMPEQQ have different requirements).
9337  if (VT == MVT::v2i64) {
9338    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9339      return SDValue();
9340    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9341      // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9342      // pcmpeqd + pshufd + pand.
9343      assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9344
9345      // First cast everything to the right type,
9346      Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9347      Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9348
9349      // Do the compare.
9350      SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9351
9352      // Make sure the lower and upper halves are both all-ones.
9353      const int Mask[] = { 1, 0, 3, 2 };
9354      SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9355      Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9356
9357      if (Invert)
9358        Result = DAG.getNOT(dl, Result, MVT::v4i32);
9359
9360      return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9361    }
9362  }
9363
9364  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9365  // bits of the inputs before performing those operations.
9366  if (FlipSigns) {
9367    EVT EltVT = VT.getVectorElementType();
9368    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9369                                      EltVT);
9370    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9371    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9372                                    SignBits.size());
9373    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9374    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9375  }
9376
9377  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9378
9379  // If the logical-not of the result is required, perform that now.
9380  if (Invert)
9381    Result = DAG.getNOT(dl, Result, VT);
9382
9383  return Result;
9384}
9385
9386SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9387
9388  MVT VT = Op.getValueType().getSimpleVT();
9389
9390  if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9391
9392  assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9393  SDValue Op0 = Op.getOperand(0);
9394  SDValue Op1 = Op.getOperand(1);
9395  DebugLoc dl = Op.getDebugLoc();
9396  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9397
9398  // Optimize to BT if possible.
9399  // Lower (X & (1 << N)) == 0 to BT(X, N).
9400  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9401  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9402  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9403      Op1.getOpcode() == ISD::Constant &&
9404      cast<ConstantSDNode>(Op1)->isNullValue() &&
9405      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9406    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9407    if (NewSetCC.getNode())
9408      return NewSetCC;
9409  }
9410
9411  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9412  // these.
9413  if (Op1.getOpcode() == ISD::Constant &&
9414      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9415       cast<ConstantSDNode>(Op1)->isNullValue()) &&
9416      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9417
9418    // If the input is a setcc, then reuse the input setcc or use a new one with
9419    // the inverted condition.
9420    if (Op0.getOpcode() == X86ISD::SETCC) {
9421      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9422      bool Invert = (CC == ISD::SETNE) ^
9423        cast<ConstantSDNode>(Op1)->isNullValue();
9424      if (!Invert) return Op0;
9425
9426      CCode = X86::GetOppositeBranchCondition(CCode);
9427      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9428                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9429    }
9430  }
9431
9432  bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9433  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9434  if (X86CC == X86::COND_INVALID)
9435    return SDValue();
9436
9437  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9438  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9439  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9440                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9441}
9442
9443// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9444static bool isX86LogicalCmp(SDValue Op) {
9445  unsigned Opc = Op.getNode()->getOpcode();
9446  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9447      Opc == X86ISD::SAHF)
9448    return true;
9449  if (Op.getResNo() == 1 &&
9450      (Opc == X86ISD::ADD ||
9451       Opc == X86ISD::SUB ||
9452       Opc == X86ISD::ADC ||
9453       Opc == X86ISD::SBB ||
9454       Opc == X86ISD::SMUL ||
9455       Opc == X86ISD::UMUL ||
9456       Opc == X86ISD::INC ||
9457       Opc == X86ISD::DEC ||
9458       Opc == X86ISD::OR ||
9459       Opc == X86ISD::XOR ||
9460       Opc == X86ISD::AND))
9461    return true;
9462
9463  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9464    return true;
9465
9466  return false;
9467}
9468
9469static bool isZero(SDValue V) {
9470  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9471  return C && C->isNullValue();
9472}
9473
9474static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9475  if (V.getOpcode() != ISD::TRUNCATE)
9476    return false;
9477
9478  SDValue VOp0 = V.getOperand(0);
9479  unsigned InBits = VOp0.getValueSizeInBits();
9480  unsigned Bits = V.getValueSizeInBits();
9481  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9482}
9483
9484SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9485  bool addTest = true;
9486  SDValue Cond  = Op.getOperand(0);
9487  SDValue Op1 = Op.getOperand(1);
9488  SDValue Op2 = Op.getOperand(2);
9489  DebugLoc DL = Op.getDebugLoc();
9490  SDValue CC;
9491
9492  if (Cond.getOpcode() == ISD::SETCC) {
9493    SDValue NewCond = LowerSETCC(Cond, DAG);
9494    if (NewCond.getNode())
9495      Cond = NewCond;
9496  }
9497
9498  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9499  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9500  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9501  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9502  if (Cond.getOpcode() == X86ISD::SETCC &&
9503      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9504      isZero(Cond.getOperand(1).getOperand(1))) {
9505    SDValue Cmp = Cond.getOperand(1);
9506
9507    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9508
9509    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9510        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9511      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9512
9513      SDValue CmpOp0 = Cmp.getOperand(0);
9514      // Apply further optimizations for special cases
9515      // (select (x != 0), -1, 0) -> neg & sbb
9516      // (select (x == 0), 0, -1) -> neg & sbb
9517      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9518        if (YC->isNullValue() &&
9519            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9520          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9521          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9522                                    DAG.getConstant(0, CmpOp0.getValueType()),
9523                                    CmpOp0);
9524          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9525                                    DAG.getConstant(X86::COND_B, MVT::i8),
9526                                    SDValue(Neg.getNode(), 1));
9527          return Res;
9528        }
9529
9530      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9531                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9532      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9533
9534      SDValue Res =   // Res = 0 or -1.
9535        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9536                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9537
9538      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9539        Res = DAG.getNOT(DL, Res, Res.getValueType());
9540
9541      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9542      if (N2C == 0 || !N2C->isNullValue())
9543        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9544      return Res;
9545    }
9546  }
9547
9548  // Look past (and (setcc_carry (cmp ...)), 1).
9549  if (Cond.getOpcode() == ISD::AND &&
9550      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9551    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9552    if (C && C->getAPIntValue() == 1)
9553      Cond = Cond.getOperand(0);
9554  }
9555
9556  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9557  // setting operand in place of the X86ISD::SETCC.
9558  unsigned CondOpcode = Cond.getOpcode();
9559  if (CondOpcode == X86ISD::SETCC ||
9560      CondOpcode == X86ISD::SETCC_CARRY) {
9561    CC = Cond.getOperand(0);
9562
9563    SDValue Cmp = Cond.getOperand(1);
9564    unsigned Opc = Cmp.getOpcode();
9565    MVT VT = Op.getValueType().getSimpleVT();
9566
9567    bool IllegalFPCMov = false;
9568    if (VT.isFloatingPoint() && !VT.isVector() &&
9569        !isScalarFPTypeInSSEReg(VT))  // FPStack?
9570      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9571
9572    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9573        Opc == X86ISD::BT) { // FIXME
9574      Cond = Cmp;
9575      addTest = false;
9576    }
9577  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9578             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9579             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9580              Cond.getOperand(0).getValueType() != MVT::i8)) {
9581    SDValue LHS = Cond.getOperand(0);
9582    SDValue RHS = Cond.getOperand(1);
9583    unsigned X86Opcode;
9584    unsigned X86Cond;
9585    SDVTList VTs;
9586    switch (CondOpcode) {
9587    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9588    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9589    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9590    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9591    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9592    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9593    default: llvm_unreachable("unexpected overflowing operator");
9594    }
9595    if (CondOpcode == ISD::UMULO)
9596      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9597                          MVT::i32);
9598    else
9599      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9600
9601    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9602
9603    if (CondOpcode == ISD::UMULO)
9604      Cond = X86Op.getValue(2);
9605    else
9606      Cond = X86Op.getValue(1);
9607
9608    CC = DAG.getConstant(X86Cond, MVT::i8);
9609    addTest = false;
9610  }
9611
9612  if (addTest) {
9613    // Look pass the truncate if the high bits are known zero.
9614    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9615        Cond = Cond.getOperand(0);
9616
9617    // We know the result of AND is compared against zero. Try to match
9618    // it to BT.
9619    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9620      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9621      if (NewSetCC.getNode()) {
9622        CC = NewSetCC.getOperand(0);
9623        Cond = NewSetCC.getOperand(1);
9624        addTest = false;
9625      }
9626    }
9627  }
9628
9629  if (addTest) {
9630    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9631    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9632  }
9633
9634  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9635  // a <  b ?  0 : -1 -> RES = setcc_carry
9636  // a >= b ? -1 :  0 -> RES = setcc_carry
9637  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9638  if (Cond.getOpcode() == X86ISD::SUB) {
9639    Cond = ConvertCmpIfNecessary(Cond, DAG);
9640    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9641
9642    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9643        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9644      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9645                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9646      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9647        return DAG.getNOT(DL, Res, Res.getValueType());
9648      return Res;
9649    }
9650  }
9651
9652  // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9653  // widen the cmov and push the truncate through. This avoids introducing a new
9654  // branch during isel and doesn't add any extensions.
9655  if (Op.getValueType() == MVT::i8 &&
9656      Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9657    SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9658    if (T1.getValueType() == T2.getValueType() &&
9659        // Blacklist CopyFromReg to avoid partial register stalls.
9660        T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9661      SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9662      SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9663      return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9664    }
9665  }
9666
9667  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9668  // condition is true.
9669  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9670  SDValue Ops[] = { Op2, Op1, CC, Cond };
9671  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9672}
9673
9674SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9675                                            SelectionDAG &DAG) const {
9676  MVT VT = Op->getValueType(0).getSimpleVT();
9677  SDValue In = Op->getOperand(0);
9678  MVT InVT = In.getValueType().getSimpleVT();
9679  DebugLoc dl = Op->getDebugLoc();
9680
9681  if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9682      (VT != MVT::v8i32 || InVT != MVT::v8i16))
9683    return SDValue();
9684
9685  if (Subtarget->hasInt256())
9686    return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9687
9688  // Optimize vectors in AVX mode
9689  // Sign extend  v8i16 to v8i32 and
9690  //              v4i32 to v4i64
9691  //
9692  // Divide input vector into two parts
9693  // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9694  // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9695  // concat the vectors to original VT
9696
9697  unsigned NumElems = InVT.getVectorNumElements();
9698  SDValue Undef = DAG.getUNDEF(InVT);
9699
9700  SmallVector<int,8> ShufMask1(NumElems, -1);
9701  for (unsigned i = 0; i != NumElems/2; ++i)
9702    ShufMask1[i] = i;
9703
9704  SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9705
9706  SmallVector<int,8> ShufMask2(NumElems, -1);
9707  for (unsigned i = 0; i != NumElems/2; ++i)
9708    ShufMask2[i] = i + NumElems/2;
9709
9710  SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9711
9712  MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9713                                VT.getVectorNumElements()/2);
9714
9715  OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9716  OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9717
9718  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9719}
9720
9721// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9722// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9723// from the AND / OR.
9724static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9725  Opc = Op.getOpcode();
9726  if (Opc != ISD::OR && Opc != ISD::AND)
9727    return false;
9728  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9729          Op.getOperand(0).hasOneUse() &&
9730          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9731          Op.getOperand(1).hasOneUse());
9732}
9733
9734// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9735// 1 and that the SETCC node has a single use.
9736static bool isXor1OfSetCC(SDValue Op) {
9737  if (Op.getOpcode() != ISD::XOR)
9738    return false;
9739  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9740  if (N1C && N1C->getAPIntValue() == 1) {
9741    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9742      Op.getOperand(0).hasOneUse();
9743  }
9744  return false;
9745}
9746
9747SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9748  bool addTest = true;
9749  SDValue Chain = Op.getOperand(0);
9750  SDValue Cond  = Op.getOperand(1);
9751  SDValue Dest  = Op.getOperand(2);
9752  DebugLoc dl = Op.getDebugLoc();
9753  SDValue CC;
9754  bool Inverted = false;
9755
9756  if (Cond.getOpcode() == ISD::SETCC) {
9757    // Check for setcc([su]{add,sub,mul}o == 0).
9758    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9759        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9760        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9761        Cond.getOperand(0).getResNo() == 1 &&
9762        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9763         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9764         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9765         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9766         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9767         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9768      Inverted = true;
9769      Cond = Cond.getOperand(0);
9770    } else {
9771      SDValue NewCond = LowerSETCC(Cond, DAG);
9772      if (NewCond.getNode())
9773        Cond = NewCond;
9774    }
9775  }
9776#if 0
9777  // FIXME: LowerXALUO doesn't handle these!!
9778  else if (Cond.getOpcode() == X86ISD::ADD  ||
9779           Cond.getOpcode() == X86ISD::SUB  ||
9780           Cond.getOpcode() == X86ISD::SMUL ||
9781           Cond.getOpcode() == X86ISD::UMUL)
9782    Cond = LowerXALUO(Cond, DAG);
9783#endif
9784
9785  // Look pass (and (setcc_carry (cmp ...)), 1).
9786  if (Cond.getOpcode() == ISD::AND &&
9787      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9788    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9789    if (C && C->getAPIntValue() == 1)
9790      Cond = Cond.getOperand(0);
9791  }
9792
9793  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9794  // setting operand in place of the X86ISD::SETCC.
9795  unsigned CondOpcode = Cond.getOpcode();
9796  if (CondOpcode == X86ISD::SETCC ||
9797      CondOpcode == X86ISD::SETCC_CARRY) {
9798    CC = Cond.getOperand(0);
9799
9800    SDValue Cmp = Cond.getOperand(1);
9801    unsigned Opc = Cmp.getOpcode();
9802    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9803    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9804      Cond = Cmp;
9805      addTest = false;
9806    } else {
9807      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9808      default: break;
9809      case X86::COND_O:
9810      case X86::COND_B:
9811        // These can only come from an arithmetic instruction with overflow,
9812        // e.g. SADDO, UADDO.
9813        Cond = Cond.getNode()->getOperand(1);
9814        addTest = false;
9815        break;
9816      }
9817    }
9818  }
9819  CondOpcode = Cond.getOpcode();
9820  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9821      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9822      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9823       Cond.getOperand(0).getValueType() != MVT::i8)) {
9824    SDValue LHS = Cond.getOperand(0);
9825    SDValue RHS = Cond.getOperand(1);
9826    unsigned X86Opcode;
9827    unsigned X86Cond;
9828    SDVTList VTs;
9829    switch (CondOpcode) {
9830    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9831    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9832    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9833    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9834    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9835    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9836    default: llvm_unreachable("unexpected overflowing operator");
9837    }
9838    if (Inverted)
9839      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9840    if (CondOpcode == ISD::UMULO)
9841      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9842                          MVT::i32);
9843    else
9844      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9845
9846    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9847
9848    if (CondOpcode == ISD::UMULO)
9849      Cond = X86Op.getValue(2);
9850    else
9851      Cond = X86Op.getValue(1);
9852
9853    CC = DAG.getConstant(X86Cond, MVT::i8);
9854    addTest = false;
9855  } else {
9856    unsigned CondOpc;
9857    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9858      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9859      if (CondOpc == ISD::OR) {
9860        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9861        // two branches instead of an explicit OR instruction with a
9862        // separate test.
9863        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9864            isX86LogicalCmp(Cmp)) {
9865          CC = Cond.getOperand(0).getOperand(0);
9866          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9867                              Chain, Dest, CC, Cmp);
9868          CC = Cond.getOperand(1).getOperand(0);
9869          Cond = Cmp;
9870          addTest = false;
9871        }
9872      } else { // ISD::AND
9873        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9874        // two branches instead of an explicit AND instruction with a
9875        // separate test. However, we only do this if this block doesn't
9876        // have a fall-through edge, because this requires an explicit
9877        // jmp when the condition is false.
9878        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9879            isX86LogicalCmp(Cmp) &&
9880            Op.getNode()->hasOneUse()) {
9881          X86::CondCode CCode =
9882            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9883          CCode = X86::GetOppositeBranchCondition(CCode);
9884          CC = DAG.getConstant(CCode, MVT::i8);
9885          SDNode *User = *Op.getNode()->use_begin();
9886          // Look for an unconditional branch following this conditional branch.
9887          // We need this because we need to reverse the successors in order
9888          // to implement FCMP_OEQ.
9889          if (User->getOpcode() == ISD::BR) {
9890            SDValue FalseBB = User->getOperand(1);
9891            SDNode *NewBR =
9892              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9893            assert(NewBR == User);
9894            (void)NewBR;
9895            Dest = FalseBB;
9896
9897            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9898                                Chain, Dest, CC, Cmp);
9899            X86::CondCode CCode =
9900              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9901            CCode = X86::GetOppositeBranchCondition(CCode);
9902            CC = DAG.getConstant(CCode, MVT::i8);
9903            Cond = Cmp;
9904            addTest = false;
9905          }
9906        }
9907      }
9908    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9909      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9910      // It should be transformed during dag combiner except when the condition
9911      // is set by a arithmetics with overflow node.
9912      X86::CondCode CCode =
9913        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9914      CCode = X86::GetOppositeBranchCondition(CCode);
9915      CC = DAG.getConstant(CCode, MVT::i8);
9916      Cond = Cond.getOperand(0).getOperand(1);
9917      addTest = false;
9918    } else if (Cond.getOpcode() == ISD::SETCC &&
9919               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9920      // For FCMP_OEQ, we can emit
9921      // two branches instead of an explicit AND instruction with a
9922      // separate test. However, we only do this if this block doesn't
9923      // have a fall-through edge, because this requires an explicit
9924      // jmp when the condition is false.
9925      if (Op.getNode()->hasOneUse()) {
9926        SDNode *User = *Op.getNode()->use_begin();
9927        // Look for an unconditional branch following this conditional branch.
9928        // We need this because we need to reverse the successors in order
9929        // to implement FCMP_OEQ.
9930        if (User->getOpcode() == ISD::BR) {
9931          SDValue FalseBB = User->getOperand(1);
9932          SDNode *NewBR =
9933            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9934          assert(NewBR == User);
9935          (void)NewBR;
9936          Dest = FalseBB;
9937
9938          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9939                                    Cond.getOperand(0), Cond.getOperand(1));
9940          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9941          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9942          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9943                              Chain, Dest, CC, Cmp);
9944          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9945          Cond = Cmp;
9946          addTest = false;
9947        }
9948      }
9949    } else if (Cond.getOpcode() == ISD::SETCC &&
9950               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9951      // For FCMP_UNE, we can emit
9952      // two branches instead of an explicit AND instruction with a
9953      // separate test. However, we only do this if this block doesn't
9954      // have a fall-through edge, because this requires an explicit
9955      // jmp when the condition is false.
9956      if (Op.getNode()->hasOneUse()) {
9957        SDNode *User = *Op.getNode()->use_begin();
9958        // Look for an unconditional branch following this conditional branch.
9959        // We need this because we need to reverse the successors in order
9960        // to implement FCMP_UNE.
9961        if (User->getOpcode() == ISD::BR) {
9962          SDValue FalseBB = User->getOperand(1);
9963          SDNode *NewBR =
9964            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9965          assert(NewBR == User);
9966          (void)NewBR;
9967
9968          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9969                                    Cond.getOperand(0), Cond.getOperand(1));
9970          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9971          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9972          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9973                              Chain, Dest, CC, Cmp);
9974          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9975          Cond = Cmp;
9976          addTest = false;
9977          Dest = FalseBB;
9978        }
9979      }
9980    }
9981  }
9982
9983  if (addTest) {
9984    // Look pass the truncate if the high bits are known zero.
9985    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9986        Cond = Cond.getOperand(0);
9987
9988    // We know the result of AND is compared against zero. Try to match
9989    // it to BT.
9990    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9991      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9992      if (NewSetCC.getNode()) {
9993        CC = NewSetCC.getOperand(0);
9994        Cond = NewSetCC.getOperand(1);
9995        addTest = false;
9996      }
9997    }
9998  }
9999
10000  if (addTest) {
10001    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10002    Cond = EmitTest(Cond, X86::COND_NE, DAG);
10003  }
10004  Cond = ConvertCmpIfNecessary(Cond, DAG);
10005  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10006                     Chain, Dest, CC, Cond);
10007}
10008
10009// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10010// Calls to _alloca is needed to probe the stack when allocating more than 4k
10011// bytes in one go. Touching the stack at 4K increments is necessary to ensure
10012// that the guard pages used by the OS virtual memory manager are allocated in
10013// correct sequence.
10014SDValue
10015X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10016                                           SelectionDAG &DAG) const {
10017  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10018          getTargetMachine().Options.EnableSegmentedStacks) &&
10019         "This should be used only on Windows targets or when segmented stacks "
10020         "are being used");
10021  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10022  DebugLoc dl = Op.getDebugLoc();
10023
10024  // Get the inputs.
10025  SDValue Chain = Op.getOperand(0);
10026  SDValue Size  = Op.getOperand(1);
10027  // FIXME: Ensure alignment here
10028
10029  bool Is64Bit = Subtarget->is64Bit();
10030  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10031
10032  if (getTargetMachine().Options.EnableSegmentedStacks) {
10033    MachineFunction &MF = DAG.getMachineFunction();
10034    MachineRegisterInfo &MRI = MF.getRegInfo();
10035
10036    if (Is64Bit) {
10037      // The 64 bit implementation of segmented stacks needs to clobber both r10
10038      // r11. This makes it impossible to use it along with nested parameters.
10039      const Function *F = MF.getFunction();
10040
10041      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10042           I != E; ++I)
10043        if (I->hasNestAttr())
10044          report_fatal_error("Cannot use segmented stacks with functions that "
10045                             "have nested arguments.");
10046    }
10047
10048    const TargetRegisterClass *AddrRegClass =
10049      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10050    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10051    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10052    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10053                                DAG.getRegister(Vreg, SPTy));
10054    SDValue Ops1[2] = { Value, Chain };
10055    return DAG.getMergeValues(Ops1, 2, dl);
10056  } else {
10057    SDValue Flag;
10058    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10059
10060    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10061    Flag = Chain.getValue(1);
10062    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10063
10064    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10065    Flag = Chain.getValue(1);
10066
10067    Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10068                               SPTy).getValue(1);
10069
10070    SDValue Ops1[2] = { Chain.getValue(0), Chain };
10071    return DAG.getMergeValues(Ops1, 2, dl);
10072  }
10073}
10074
10075SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10076  MachineFunction &MF = DAG.getMachineFunction();
10077  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10078
10079  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10080  DebugLoc DL = Op.getDebugLoc();
10081
10082  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10083    // vastart just stores the address of the VarArgsFrameIndex slot into the
10084    // memory location argument.
10085    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10086                                   getPointerTy());
10087    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10088                        MachinePointerInfo(SV), false, false, 0);
10089  }
10090
10091  // __va_list_tag:
10092  //   gp_offset         (0 - 6 * 8)
10093  //   fp_offset         (48 - 48 + 8 * 16)
10094  //   overflow_arg_area (point to parameters coming in memory).
10095  //   reg_save_area
10096  SmallVector<SDValue, 8> MemOps;
10097  SDValue FIN = Op.getOperand(1);
10098  // Store gp_offset
10099  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10100                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10101                                               MVT::i32),
10102                               FIN, MachinePointerInfo(SV), false, false, 0);
10103  MemOps.push_back(Store);
10104
10105  // Store fp_offset
10106  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10107                    FIN, DAG.getIntPtrConstant(4));
10108  Store = DAG.getStore(Op.getOperand(0), DL,
10109                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10110                                       MVT::i32),
10111                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
10112  MemOps.push_back(Store);
10113
10114  // Store ptr to overflow_arg_area
10115  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10116                    FIN, DAG.getIntPtrConstant(4));
10117  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10118                                    getPointerTy());
10119  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10120                       MachinePointerInfo(SV, 8),
10121                       false, false, 0);
10122  MemOps.push_back(Store);
10123
10124  // Store ptr to reg_save_area.
10125  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10126                    FIN, DAG.getIntPtrConstant(8));
10127  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10128                                    getPointerTy());
10129  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10130                       MachinePointerInfo(SV, 16), false, false, 0);
10131  MemOps.push_back(Store);
10132  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10133                     &MemOps[0], MemOps.size());
10134}
10135
10136SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10137  assert(Subtarget->is64Bit() &&
10138         "LowerVAARG only handles 64-bit va_arg!");
10139  assert((Subtarget->isTargetLinux() ||
10140          Subtarget->isTargetDarwin()) &&
10141          "Unhandled target in LowerVAARG");
10142  assert(Op.getNode()->getNumOperands() == 4);
10143  SDValue Chain = Op.getOperand(0);
10144  SDValue SrcPtr = Op.getOperand(1);
10145  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10146  unsigned Align = Op.getConstantOperandVal(3);
10147  DebugLoc dl = Op.getDebugLoc();
10148
10149  EVT ArgVT = Op.getNode()->getValueType(0);
10150  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10151  uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10152  uint8_t ArgMode;
10153
10154  // Decide which area this value should be read from.
10155  // TODO: Implement the AMD64 ABI in its entirety. This simple
10156  // selection mechanism works only for the basic types.
10157  if (ArgVT == MVT::f80) {
10158    llvm_unreachable("va_arg for f80 not yet implemented");
10159  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10160    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10161  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10162    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10163  } else {
10164    llvm_unreachable("Unhandled argument type in LowerVAARG");
10165  }
10166
10167  if (ArgMode == 2) {
10168    // Sanity Check: Make sure using fp_offset makes sense.
10169    assert(!getTargetMachine().Options.UseSoftFloat &&
10170           !(DAG.getMachineFunction()
10171                .getFunction()->getAttributes()
10172                .hasAttribute(AttributeSet::FunctionIndex,
10173                              Attribute::NoImplicitFloat)) &&
10174           Subtarget->hasSSE1());
10175  }
10176
10177  // Insert VAARG_64 node into the DAG
10178  // VAARG_64 returns two values: Variable Argument Address, Chain
10179  SmallVector<SDValue, 11> InstOps;
10180  InstOps.push_back(Chain);
10181  InstOps.push_back(SrcPtr);
10182  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10183  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10184  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10185  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10186  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10187                                          VTs, &InstOps[0], InstOps.size(),
10188                                          MVT::i64,
10189                                          MachinePointerInfo(SV),
10190                                          /*Align=*/0,
10191                                          /*Volatile=*/false,
10192                                          /*ReadMem=*/true,
10193                                          /*WriteMem=*/true);
10194  Chain = VAARG.getValue(1);
10195
10196  // Load the next argument and return it
10197  return DAG.getLoad(ArgVT, dl,
10198                     Chain,
10199                     VAARG,
10200                     MachinePointerInfo(),
10201                     false, false, false, 0);
10202}
10203
10204static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10205                           SelectionDAG &DAG) {
10206  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10207  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10208  SDValue Chain = Op.getOperand(0);
10209  SDValue DstPtr = Op.getOperand(1);
10210  SDValue SrcPtr = Op.getOperand(2);
10211  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10212  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10213  DebugLoc DL = Op.getDebugLoc();
10214
10215  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10216                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10217                       false,
10218                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10219}
10220
10221// getTargetVShiftNode - Handle vector element shifts where the shift amount
10222// may or may not be a constant. Takes immediate version of shift as input.
10223static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10224                                   SDValue SrcOp, SDValue ShAmt,
10225                                   SelectionDAG &DAG) {
10226  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10227
10228  if (isa<ConstantSDNode>(ShAmt)) {
10229    // Constant may be a TargetConstant. Use a regular constant.
10230    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10231    switch (Opc) {
10232      default: llvm_unreachable("Unknown target vector shift node");
10233      case X86ISD::VSHLI:
10234      case X86ISD::VSRLI:
10235      case X86ISD::VSRAI:
10236        return DAG.getNode(Opc, dl, VT, SrcOp,
10237                           DAG.getConstant(ShiftAmt, MVT::i32));
10238    }
10239  }
10240
10241  // Change opcode to non-immediate version
10242  switch (Opc) {
10243    default: llvm_unreachable("Unknown target vector shift node");
10244    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10245    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10246    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10247  }
10248
10249  // Need to build a vector containing shift amount
10250  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10251  SDValue ShOps[4];
10252  ShOps[0] = ShAmt;
10253  ShOps[1] = DAG.getConstant(0, MVT::i32);
10254  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10255  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10256
10257  // The return type has to be a 128-bit type with the same element
10258  // type as the input type.
10259  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10260  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10261
10262  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10263  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10264}
10265
10266static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10267  DebugLoc dl = Op.getDebugLoc();
10268  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10269  switch (IntNo) {
10270  default: return SDValue();    // Don't custom lower most intrinsics.
10271  // Comparison intrinsics.
10272  case Intrinsic::x86_sse_comieq_ss:
10273  case Intrinsic::x86_sse_comilt_ss:
10274  case Intrinsic::x86_sse_comile_ss:
10275  case Intrinsic::x86_sse_comigt_ss:
10276  case Intrinsic::x86_sse_comige_ss:
10277  case Intrinsic::x86_sse_comineq_ss:
10278  case Intrinsic::x86_sse_ucomieq_ss:
10279  case Intrinsic::x86_sse_ucomilt_ss:
10280  case Intrinsic::x86_sse_ucomile_ss:
10281  case Intrinsic::x86_sse_ucomigt_ss:
10282  case Intrinsic::x86_sse_ucomige_ss:
10283  case Intrinsic::x86_sse_ucomineq_ss:
10284  case Intrinsic::x86_sse2_comieq_sd:
10285  case Intrinsic::x86_sse2_comilt_sd:
10286  case Intrinsic::x86_sse2_comile_sd:
10287  case Intrinsic::x86_sse2_comigt_sd:
10288  case Intrinsic::x86_sse2_comige_sd:
10289  case Intrinsic::x86_sse2_comineq_sd:
10290  case Intrinsic::x86_sse2_ucomieq_sd:
10291  case Intrinsic::x86_sse2_ucomilt_sd:
10292  case Intrinsic::x86_sse2_ucomile_sd:
10293  case Intrinsic::x86_sse2_ucomigt_sd:
10294  case Intrinsic::x86_sse2_ucomige_sd:
10295  case Intrinsic::x86_sse2_ucomineq_sd: {
10296    unsigned Opc;
10297    ISD::CondCode CC;
10298    switch (IntNo) {
10299    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10300    case Intrinsic::x86_sse_comieq_ss:
10301    case Intrinsic::x86_sse2_comieq_sd:
10302      Opc = X86ISD::COMI;
10303      CC = ISD::SETEQ;
10304      break;
10305    case Intrinsic::x86_sse_comilt_ss:
10306    case Intrinsic::x86_sse2_comilt_sd:
10307      Opc = X86ISD::COMI;
10308      CC = ISD::SETLT;
10309      break;
10310    case Intrinsic::x86_sse_comile_ss:
10311    case Intrinsic::x86_sse2_comile_sd:
10312      Opc = X86ISD::COMI;
10313      CC = ISD::SETLE;
10314      break;
10315    case Intrinsic::x86_sse_comigt_ss:
10316    case Intrinsic::x86_sse2_comigt_sd:
10317      Opc = X86ISD::COMI;
10318      CC = ISD::SETGT;
10319      break;
10320    case Intrinsic::x86_sse_comige_ss:
10321    case Intrinsic::x86_sse2_comige_sd:
10322      Opc = X86ISD::COMI;
10323      CC = ISD::SETGE;
10324      break;
10325    case Intrinsic::x86_sse_comineq_ss:
10326    case Intrinsic::x86_sse2_comineq_sd:
10327      Opc = X86ISD::COMI;
10328      CC = ISD::SETNE;
10329      break;
10330    case Intrinsic::x86_sse_ucomieq_ss:
10331    case Intrinsic::x86_sse2_ucomieq_sd:
10332      Opc = X86ISD::UCOMI;
10333      CC = ISD::SETEQ;
10334      break;
10335    case Intrinsic::x86_sse_ucomilt_ss:
10336    case Intrinsic::x86_sse2_ucomilt_sd:
10337      Opc = X86ISD::UCOMI;
10338      CC = ISD::SETLT;
10339      break;
10340    case Intrinsic::x86_sse_ucomile_ss:
10341    case Intrinsic::x86_sse2_ucomile_sd:
10342      Opc = X86ISD::UCOMI;
10343      CC = ISD::SETLE;
10344      break;
10345    case Intrinsic::x86_sse_ucomigt_ss:
10346    case Intrinsic::x86_sse2_ucomigt_sd:
10347      Opc = X86ISD::UCOMI;
10348      CC = ISD::SETGT;
10349      break;
10350    case Intrinsic::x86_sse_ucomige_ss:
10351    case Intrinsic::x86_sse2_ucomige_sd:
10352      Opc = X86ISD::UCOMI;
10353      CC = ISD::SETGE;
10354      break;
10355    case Intrinsic::x86_sse_ucomineq_ss:
10356    case Intrinsic::x86_sse2_ucomineq_sd:
10357      Opc = X86ISD::UCOMI;
10358      CC = ISD::SETNE;
10359      break;
10360    }
10361
10362    SDValue LHS = Op.getOperand(1);
10363    SDValue RHS = Op.getOperand(2);
10364    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10365    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10366    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10367    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10368                                DAG.getConstant(X86CC, MVT::i8), Cond);
10369    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10370  }
10371
10372  // Arithmetic intrinsics.
10373  case Intrinsic::x86_sse2_pmulu_dq:
10374  case Intrinsic::x86_avx2_pmulu_dq:
10375    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10376                       Op.getOperand(1), Op.getOperand(2));
10377
10378  // SSE2/AVX2 sub with unsigned saturation intrinsics
10379  case Intrinsic::x86_sse2_psubus_b:
10380  case Intrinsic::x86_sse2_psubus_w:
10381  case Intrinsic::x86_avx2_psubus_b:
10382  case Intrinsic::x86_avx2_psubus_w:
10383    return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10384                       Op.getOperand(1), Op.getOperand(2));
10385
10386  // SSE3/AVX horizontal add/sub intrinsics
10387  case Intrinsic::x86_sse3_hadd_ps:
10388  case Intrinsic::x86_sse3_hadd_pd:
10389  case Intrinsic::x86_avx_hadd_ps_256:
10390  case Intrinsic::x86_avx_hadd_pd_256:
10391  case Intrinsic::x86_sse3_hsub_ps:
10392  case Intrinsic::x86_sse3_hsub_pd:
10393  case Intrinsic::x86_avx_hsub_ps_256:
10394  case Intrinsic::x86_avx_hsub_pd_256:
10395  case Intrinsic::x86_ssse3_phadd_w_128:
10396  case Intrinsic::x86_ssse3_phadd_d_128:
10397  case Intrinsic::x86_avx2_phadd_w:
10398  case Intrinsic::x86_avx2_phadd_d:
10399  case Intrinsic::x86_ssse3_phsub_w_128:
10400  case Intrinsic::x86_ssse3_phsub_d_128:
10401  case Intrinsic::x86_avx2_phsub_w:
10402  case Intrinsic::x86_avx2_phsub_d: {
10403    unsigned Opcode;
10404    switch (IntNo) {
10405    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10406    case Intrinsic::x86_sse3_hadd_ps:
10407    case Intrinsic::x86_sse3_hadd_pd:
10408    case Intrinsic::x86_avx_hadd_ps_256:
10409    case Intrinsic::x86_avx_hadd_pd_256:
10410      Opcode = X86ISD::FHADD;
10411      break;
10412    case Intrinsic::x86_sse3_hsub_ps:
10413    case Intrinsic::x86_sse3_hsub_pd:
10414    case Intrinsic::x86_avx_hsub_ps_256:
10415    case Intrinsic::x86_avx_hsub_pd_256:
10416      Opcode = X86ISD::FHSUB;
10417      break;
10418    case Intrinsic::x86_ssse3_phadd_w_128:
10419    case Intrinsic::x86_ssse3_phadd_d_128:
10420    case Intrinsic::x86_avx2_phadd_w:
10421    case Intrinsic::x86_avx2_phadd_d:
10422      Opcode = X86ISD::HADD;
10423      break;
10424    case Intrinsic::x86_ssse3_phsub_w_128:
10425    case Intrinsic::x86_ssse3_phsub_d_128:
10426    case Intrinsic::x86_avx2_phsub_w:
10427    case Intrinsic::x86_avx2_phsub_d:
10428      Opcode = X86ISD::HSUB;
10429      break;
10430    }
10431    return DAG.getNode(Opcode, dl, Op.getValueType(),
10432                       Op.getOperand(1), Op.getOperand(2));
10433  }
10434
10435  // SSE2/SSE41/AVX2 integer max/min intrinsics.
10436  case Intrinsic::x86_sse2_pmaxu_b:
10437  case Intrinsic::x86_sse41_pmaxuw:
10438  case Intrinsic::x86_sse41_pmaxud:
10439  case Intrinsic::x86_avx2_pmaxu_b:
10440  case Intrinsic::x86_avx2_pmaxu_w:
10441  case Intrinsic::x86_avx2_pmaxu_d:
10442  case Intrinsic::x86_sse2_pminu_b:
10443  case Intrinsic::x86_sse41_pminuw:
10444  case Intrinsic::x86_sse41_pminud:
10445  case Intrinsic::x86_avx2_pminu_b:
10446  case Intrinsic::x86_avx2_pminu_w:
10447  case Intrinsic::x86_avx2_pminu_d:
10448  case Intrinsic::x86_sse41_pmaxsb:
10449  case Intrinsic::x86_sse2_pmaxs_w:
10450  case Intrinsic::x86_sse41_pmaxsd:
10451  case Intrinsic::x86_avx2_pmaxs_b:
10452  case Intrinsic::x86_avx2_pmaxs_w:
10453  case Intrinsic::x86_avx2_pmaxs_d:
10454  case Intrinsic::x86_sse41_pminsb:
10455  case Intrinsic::x86_sse2_pmins_w:
10456  case Intrinsic::x86_sse41_pminsd:
10457  case Intrinsic::x86_avx2_pmins_b:
10458  case Intrinsic::x86_avx2_pmins_w:
10459  case Intrinsic::x86_avx2_pmins_d: {
10460    unsigned Opcode;
10461    switch (IntNo) {
10462    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10463    case Intrinsic::x86_sse2_pmaxu_b:
10464    case Intrinsic::x86_sse41_pmaxuw:
10465    case Intrinsic::x86_sse41_pmaxud:
10466    case Intrinsic::x86_avx2_pmaxu_b:
10467    case Intrinsic::x86_avx2_pmaxu_w:
10468    case Intrinsic::x86_avx2_pmaxu_d:
10469      Opcode = X86ISD::UMAX;
10470      break;
10471    case Intrinsic::x86_sse2_pminu_b:
10472    case Intrinsic::x86_sse41_pminuw:
10473    case Intrinsic::x86_sse41_pminud:
10474    case Intrinsic::x86_avx2_pminu_b:
10475    case Intrinsic::x86_avx2_pminu_w:
10476    case Intrinsic::x86_avx2_pminu_d:
10477      Opcode = X86ISD::UMIN;
10478      break;
10479    case Intrinsic::x86_sse41_pmaxsb:
10480    case Intrinsic::x86_sse2_pmaxs_w:
10481    case Intrinsic::x86_sse41_pmaxsd:
10482    case Intrinsic::x86_avx2_pmaxs_b:
10483    case Intrinsic::x86_avx2_pmaxs_w:
10484    case Intrinsic::x86_avx2_pmaxs_d:
10485      Opcode = X86ISD::SMAX;
10486      break;
10487    case Intrinsic::x86_sse41_pminsb:
10488    case Intrinsic::x86_sse2_pmins_w:
10489    case Intrinsic::x86_sse41_pminsd:
10490    case Intrinsic::x86_avx2_pmins_b:
10491    case Intrinsic::x86_avx2_pmins_w:
10492    case Intrinsic::x86_avx2_pmins_d:
10493      Opcode = X86ISD::SMIN;
10494      break;
10495    }
10496    return DAG.getNode(Opcode, dl, Op.getValueType(),
10497                       Op.getOperand(1), Op.getOperand(2));
10498  }
10499
10500  // SSE/SSE2/AVX floating point max/min intrinsics.
10501  case Intrinsic::x86_sse_max_ps:
10502  case Intrinsic::x86_sse2_max_pd:
10503  case Intrinsic::x86_avx_max_ps_256:
10504  case Intrinsic::x86_avx_max_pd_256:
10505  case Intrinsic::x86_sse_min_ps:
10506  case Intrinsic::x86_sse2_min_pd:
10507  case Intrinsic::x86_avx_min_ps_256:
10508  case Intrinsic::x86_avx_min_pd_256: {
10509    unsigned Opcode;
10510    switch (IntNo) {
10511    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10512    case Intrinsic::x86_sse_max_ps:
10513    case Intrinsic::x86_sse2_max_pd:
10514    case Intrinsic::x86_avx_max_ps_256:
10515    case Intrinsic::x86_avx_max_pd_256:
10516      Opcode = X86ISD::FMAX;
10517      break;
10518    case Intrinsic::x86_sse_min_ps:
10519    case Intrinsic::x86_sse2_min_pd:
10520    case Intrinsic::x86_avx_min_ps_256:
10521    case Intrinsic::x86_avx_min_pd_256:
10522      Opcode = X86ISD::FMIN;
10523      break;
10524    }
10525    return DAG.getNode(Opcode, dl, Op.getValueType(),
10526                       Op.getOperand(1), Op.getOperand(2));
10527  }
10528
10529  // AVX2 variable shift intrinsics
10530  case Intrinsic::x86_avx2_psllv_d:
10531  case Intrinsic::x86_avx2_psllv_q:
10532  case Intrinsic::x86_avx2_psllv_d_256:
10533  case Intrinsic::x86_avx2_psllv_q_256:
10534  case Intrinsic::x86_avx2_psrlv_d:
10535  case Intrinsic::x86_avx2_psrlv_q:
10536  case Intrinsic::x86_avx2_psrlv_d_256:
10537  case Intrinsic::x86_avx2_psrlv_q_256:
10538  case Intrinsic::x86_avx2_psrav_d:
10539  case Intrinsic::x86_avx2_psrav_d_256: {
10540    unsigned Opcode;
10541    switch (IntNo) {
10542    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10543    case Intrinsic::x86_avx2_psllv_d:
10544    case Intrinsic::x86_avx2_psllv_q:
10545    case Intrinsic::x86_avx2_psllv_d_256:
10546    case Intrinsic::x86_avx2_psllv_q_256:
10547      Opcode = ISD::SHL;
10548      break;
10549    case Intrinsic::x86_avx2_psrlv_d:
10550    case Intrinsic::x86_avx2_psrlv_q:
10551    case Intrinsic::x86_avx2_psrlv_d_256:
10552    case Intrinsic::x86_avx2_psrlv_q_256:
10553      Opcode = ISD::SRL;
10554      break;
10555    case Intrinsic::x86_avx2_psrav_d:
10556    case Intrinsic::x86_avx2_psrav_d_256:
10557      Opcode = ISD::SRA;
10558      break;
10559    }
10560    return DAG.getNode(Opcode, dl, Op.getValueType(),
10561                       Op.getOperand(1), Op.getOperand(2));
10562  }
10563
10564  case Intrinsic::x86_ssse3_pshuf_b_128:
10565  case Intrinsic::x86_avx2_pshuf_b:
10566    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10567                       Op.getOperand(1), Op.getOperand(2));
10568
10569  case Intrinsic::x86_ssse3_psign_b_128:
10570  case Intrinsic::x86_ssse3_psign_w_128:
10571  case Intrinsic::x86_ssse3_psign_d_128:
10572  case Intrinsic::x86_avx2_psign_b:
10573  case Intrinsic::x86_avx2_psign_w:
10574  case Intrinsic::x86_avx2_psign_d:
10575    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10576                       Op.getOperand(1), Op.getOperand(2));
10577
10578  case Intrinsic::x86_sse41_insertps:
10579    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10580                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10581
10582  case Intrinsic::x86_avx_vperm2f128_ps_256:
10583  case Intrinsic::x86_avx_vperm2f128_pd_256:
10584  case Intrinsic::x86_avx_vperm2f128_si_256:
10585  case Intrinsic::x86_avx2_vperm2i128:
10586    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10587                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10588
10589  case Intrinsic::x86_avx2_permd:
10590  case Intrinsic::x86_avx2_permps:
10591    // Operands intentionally swapped. Mask is last operand to intrinsic,
10592    // but second operand for node/intruction.
10593    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10594                       Op.getOperand(2), Op.getOperand(1));
10595
10596  case Intrinsic::x86_sse_sqrt_ps:
10597  case Intrinsic::x86_sse2_sqrt_pd:
10598  case Intrinsic::x86_avx_sqrt_ps_256:
10599  case Intrinsic::x86_avx_sqrt_pd_256:
10600    return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10601
10602  // ptest and testp intrinsics. The intrinsic these come from are designed to
10603  // return an integer value, not just an instruction so lower it to the ptest
10604  // or testp pattern and a setcc for the result.
10605  case Intrinsic::x86_sse41_ptestz:
10606  case Intrinsic::x86_sse41_ptestc:
10607  case Intrinsic::x86_sse41_ptestnzc:
10608  case Intrinsic::x86_avx_ptestz_256:
10609  case Intrinsic::x86_avx_ptestc_256:
10610  case Intrinsic::x86_avx_ptestnzc_256:
10611  case Intrinsic::x86_avx_vtestz_ps:
10612  case Intrinsic::x86_avx_vtestc_ps:
10613  case Intrinsic::x86_avx_vtestnzc_ps:
10614  case Intrinsic::x86_avx_vtestz_pd:
10615  case Intrinsic::x86_avx_vtestc_pd:
10616  case Intrinsic::x86_avx_vtestnzc_pd:
10617  case Intrinsic::x86_avx_vtestz_ps_256:
10618  case Intrinsic::x86_avx_vtestc_ps_256:
10619  case Intrinsic::x86_avx_vtestnzc_ps_256:
10620  case Intrinsic::x86_avx_vtestz_pd_256:
10621  case Intrinsic::x86_avx_vtestc_pd_256:
10622  case Intrinsic::x86_avx_vtestnzc_pd_256: {
10623    bool IsTestPacked = false;
10624    unsigned X86CC;
10625    switch (IntNo) {
10626    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10627    case Intrinsic::x86_avx_vtestz_ps:
10628    case Intrinsic::x86_avx_vtestz_pd:
10629    case Intrinsic::x86_avx_vtestz_ps_256:
10630    case Intrinsic::x86_avx_vtestz_pd_256:
10631      IsTestPacked = true; // Fallthrough
10632    case Intrinsic::x86_sse41_ptestz:
10633    case Intrinsic::x86_avx_ptestz_256:
10634      // ZF = 1
10635      X86CC = X86::COND_E;
10636      break;
10637    case Intrinsic::x86_avx_vtestc_ps:
10638    case Intrinsic::x86_avx_vtestc_pd:
10639    case Intrinsic::x86_avx_vtestc_ps_256:
10640    case Intrinsic::x86_avx_vtestc_pd_256:
10641      IsTestPacked = true; // Fallthrough
10642    case Intrinsic::x86_sse41_ptestc:
10643    case Intrinsic::x86_avx_ptestc_256:
10644      // CF = 1
10645      X86CC = X86::COND_B;
10646      break;
10647    case Intrinsic::x86_avx_vtestnzc_ps:
10648    case Intrinsic::x86_avx_vtestnzc_pd:
10649    case Intrinsic::x86_avx_vtestnzc_ps_256:
10650    case Intrinsic::x86_avx_vtestnzc_pd_256:
10651      IsTestPacked = true; // Fallthrough
10652    case Intrinsic::x86_sse41_ptestnzc:
10653    case Intrinsic::x86_avx_ptestnzc_256:
10654      // ZF and CF = 0
10655      X86CC = X86::COND_A;
10656      break;
10657    }
10658
10659    SDValue LHS = Op.getOperand(1);
10660    SDValue RHS = Op.getOperand(2);
10661    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10662    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10663    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10664    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10665    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10666  }
10667
10668  // SSE/AVX shift intrinsics
10669  case Intrinsic::x86_sse2_psll_w:
10670  case Intrinsic::x86_sse2_psll_d:
10671  case Intrinsic::x86_sse2_psll_q:
10672  case Intrinsic::x86_avx2_psll_w:
10673  case Intrinsic::x86_avx2_psll_d:
10674  case Intrinsic::x86_avx2_psll_q:
10675  case Intrinsic::x86_sse2_psrl_w:
10676  case Intrinsic::x86_sse2_psrl_d:
10677  case Intrinsic::x86_sse2_psrl_q:
10678  case Intrinsic::x86_avx2_psrl_w:
10679  case Intrinsic::x86_avx2_psrl_d:
10680  case Intrinsic::x86_avx2_psrl_q:
10681  case Intrinsic::x86_sse2_psra_w:
10682  case Intrinsic::x86_sse2_psra_d:
10683  case Intrinsic::x86_avx2_psra_w:
10684  case Intrinsic::x86_avx2_psra_d: {
10685    unsigned Opcode;
10686    switch (IntNo) {
10687    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10688    case Intrinsic::x86_sse2_psll_w:
10689    case Intrinsic::x86_sse2_psll_d:
10690    case Intrinsic::x86_sse2_psll_q:
10691    case Intrinsic::x86_avx2_psll_w:
10692    case Intrinsic::x86_avx2_psll_d:
10693    case Intrinsic::x86_avx2_psll_q:
10694      Opcode = X86ISD::VSHL;
10695      break;
10696    case Intrinsic::x86_sse2_psrl_w:
10697    case Intrinsic::x86_sse2_psrl_d:
10698    case Intrinsic::x86_sse2_psrl_q:
10699    case Intrinsic::x86_avx2_psrl_w:
10700    case Intrinsic::x86_avx2_psrl_d:
10701    case Intrinsic::x86_avx2_psrl_q:
10702      Opcode = X86ISD::VSRL;
10703      break;
10704    case Intrinsic::x86_sse2_psra_w:
10705    case Intrinsic::x86_sse2_psra_d:
10706    case Intrinsic::x86_avx2_psra_w:
10707    case Intrinsic::x86_avx2_psra_d:
10708      Opcode = X86ISD::VSRA;
10709      break;
10710    }
10711    return DAG.getNode(Opcode, dl, Op.getValueType(),
10712                       Op.getOperand(1), Op.getOperand(2));
10713  }
10714
10715  // SSE/AVX immediate shift intrinsics
10716  case Intrinsic::x86_sse2_pslli_w:
10717  case Intrinsic::x86_sse2_pslli_d:
10718  case Intrinsic::x86_sse2_pslli_q:
10719  case Intrinsic::x86_avx2_pslli_w:
10720  case Intrinsic::x86_avx2_pslli_d:
10721  case Intrinsic::x86_avx2_pslli_q:
10722  case Intrinsic::x86_sse2_psrli_w:
10723  case Intrinsic::x86_sse2_psrli_d:
10724  case Intrinsic::x86_sse2_psrli_q:
10725  case Intrinsic::x86_avx2_psrli_w:
10726  case Intrinsic::x86_avx2_psrli_d:
10727  case Intrinsic::x86_avx2_psrli_q:
10728  case Intrinsic::x86_sse2_psrai_w:
10729  case Intrinsic::x86_sse2_psrai_d:
10730  case Intrinsic::x86_avx2_psrai_w:
10731  case Intrinsic::x86_avx2_psrai_d: {
10732    unsigned Opcode;
10733    switch (IntNo) {
10734    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10735    case Intrinsic::x86_sse2_pslli_w:
10736    case Intrinsic::x86_sse2_pslli_d:
10737    case Intrinsic::x86_sse2_pslli_q:
10738    case Intrinsic::x86_avx2_pslli_w:
10739    case Intrinsic::x86_avx2_pslli_d:
10740    case Intrinsic::x86_avx2_pslli_q:
10741      Opcode = X86ISD::VSHLI;
10742      break;
10743    case Intrinsic::x86_sse2_psrli_w:
10744    case Intrinsic::x86_sse2_psrli_d:
10745    case Intrinsic::x86_sse2_psrli_q:
10746    case Intrinsic::x86_avx2_psrli_w:
10747    case Intrinsic::x86_avx2_psrli_d:
10748    case Intrinsic::x86_avx2_psrli_q:
10749      Opcode = X86ISD::VSRLI;
10750      break;
10751    case Intrinsic::x86_sse2_psrai_w:
10752    case Intrinsic::x86_sse2_psrai_d:
10753    case Intrinsic::x86_avx2_psrai_w:
10754    case Intrinsic::x86_avx2_psrai_d:
10755      Opcode = X86ISD::VSRAI;
10756      break;
10757    }
10758    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10759                               Op.getOperand(1), Op.getOperand(2), DAG);
10760  }
10761
10762  case Intrinsic::x86_sse42_pcmpistria128:
10763  case Intrinsic::x86_sse42_pcmpestria128:
10764  case Intrinsic::x86_sse42_pcmpistric128:
10765  case Intrinsic::x86_sse42_pcmpestric128:
10766  case Intrinsic::x86_sse42_pcmpistrio128:
10767  case Intrinsic::x86_sse42_pcmpestrio128:
10768  case Intrinsic::x86_sse42_pcmpistris128:
10769  case Intrinsic::x86_sse42_pcmpestris128:
10770  case Intrinsic::x86_sse42_pcmpistriz128:
10771  case Intrinsic::x86_sse42_pcmpestriz128: {
10772    unsigned Opcode;
10773    unsigned X86CC;
10774    switch (IntNo) {
10775    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10776    case Intrinsic::x86_sse42_pcmpistria128:
10777      Opcode = X86ISD::PCMPISTRI;
10778      X86CC = X86::COND_A;
10779      break;
10780    case Intrinsic::x86_sse42_pcmpestria128:
10781      Opcode = X86ISD::PCMPESTRI;
10782      X86CC = X86::COND_A;
10783      break;
10784    case Intrinsic::x86_sse42_pcmpistric128:
10785      Opcode = X86ISD::PCMPISTRI;
10786      X86CC = X86::COND_B;
10787      break;
10788    case Intrinsic::x86_sse42_pcmpestric128:
10789      Opcode = X86ISD::PCMPESTRI;
10790      X86CC = X86::COND_B;
10791      break;
10792    case Intrinsic::x86_sse42_pcmpistrio128:
10793      Opcode = X86ISD::PCMPISTRI;
10794      X86CC = X86::COND_O;
10795      break;
10796    case Intrinsic::x86_sse42_pcmpestrio128:
10797      Opcode = X86ISD::PCMPESTRI;
10798      X86CC = X86::COND_O;
10799      break;
10800    case Intrinsic::x86_sse42_pcmpistris128:
10801      Opcode = X86ISD::PCMPISTRI;
10802      X86CC = X86::COND_S;
10803      break;
10804    case Intrinsic::x86_sse42_pcmpestris128:
10805      Opcode = X86ISD::PCMPESTRI;
10806      X86CC = X86::COND_S;
10807      break;
10808    case Intrinsic::x86_sse42_pcmpistriz128:
10809      Opcode = X86ISD::PCMPISTRI;
10810      X86CC = X86::COND_E;
10811      break;
10812    case Intrinsic::x86_sse42_pcmpestriz128:
10813      Opcode = X86ISD::PCMPESTRI;
10814      X86CC = X86::COND_E;
10815      break;
10816    }
10817    SmallVector<SDValue, 5> NewOps;
10818    NewOps.append(Op->op_begin()+1, Op->op_end());
10819    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10820    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10821    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10822                                DAG.getConstant(X86CC, MVT::i8),
10823                                SDValue(PCMP.getNode(), 1));
10824    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10825  }
10826
10827  case Intrinsic::x86_sse42_pcmpistri128:
10828  case Intrinsic::x86_sse42_pcmpestri128: {
10829    unsigned Opcode;
10830    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10831      Opcode = X86ISD::PCMPISTRI;
10832    else
10833      Opcode = X86ISD::PCMPESTRI;
10834
10835    SmallVector<SDValue, 5> NewOps;
10836    NewOps.append(Op->op_begin()+1, Op->op_end());
10837    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10838    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10839  }
10840  case Intrinsic::x86_fma_vfmadd_ps:
10841  case Intrinsic::x86_fma_vfmadd_pd:
10842  case Intrinsic::x86_fma_vfmsub_ps:
10843  case Intrinsic::x86_fma_vfmsub_pd:
10844  case Intrinsic::x86_fma_vfnmadd_ps:
10845  case Intrinsic::x86_fma_vfnmadd_pd:
10846  case Intrinsic::x86_fma_vfnmsub_ps:
10847  case Intrinsic::x86_fma_vfnmsub_pd:
10848  case Intrinsic::x86_fma_vfmaddsub_ps:
10849  case Intrinsic::x86_fma_vfmaddsub_pd:
10850  case Intrinsic::x86_fma_vfmsubadd_ps:
10851  case Intrinsic::x86_fma_vfmsubadd_pd:
10852  case Intrinsic::x86_fma_vfmadd_ps_256:
10853  case Intrinsic::x86_fma_vfmadd_pd_256:
10854  case Intrinsic::x86_fma_vfmsub_ps_256:
10855  case Intrinsic::x86_fma_vfmsub_pd_256:
10856  case Intrinsic::x86_fma_vfnmadd_ps_256:
10857  case Intrinsic::x86_fma_vfnmadd_pd_256:
10858  case Intrinsic::x86_fma_vfnmsub_ps_256:
10859  case Intrinsic::x86_fma_vfnmsub_pd_256:
10860  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10861  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10862  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10863  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10864    unsigned Opc;
10865    switch (IntNo) {
10866    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10867    case Intrinsic::x86_fma_vfmadd_ps:
10868    case Intrinsic::x86_fma_vfmadd_pd:
10869    case Intrinsic::x86_fma_vfmadd_ps_256:
10870    case Intrinsic::x86_fma_vfmadd_pd_256:
10871      Opc = X86ISD::FMADD;
10872      break;
10873    case Intrinsic::x86_fma_vfmsub_ps:
10874    case Intrinsic::x86_fma_vfmsub_pd:
10875    case Intrinsic::x86_fma_vfmsub_ps_256:
10876    case Intrinsic::x86_fma_vfmsub_pd_256:
10877      Opc = X86ISD::FMSUB;
10878      break;
10879    case Intrinsic::x86_fma_vfnmadd_ps:
10880    case Intrinsic::x86_fma_vfnmadd_pd:
10881    case Intrinsic::x86_fma_vfnmadd_ps_256:
10882    case Intrinsic::x86_fma_vfnmadd_pd_256:
10883      Opc = X86ISD::FNMADD;
10884      break;
10885    case Intrinsic::x86_fma_vfnmsub_ps:
10886    case Intrinsic::x86_fma_vfnmsub_pd:
10887    case Intrinsic::x86_fma_vfnmsub_ps_256:
10888    case Intrinsic::x86_fma_vfnmsub_pd_256:
10889      Opc = X86ISD::FNMSUB;
10890      break;
10891    case Intrinsic::x86_fma_vfmaddsub_ps:
10892    case Intrinsic::x86_fma_vfmaddsub_pd:
10893    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10894    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10895      Opc = X86ISD::FMADDSUB;
10896      break;
10897    case Intrinsic::x86_fma_vfmsubadd_ps:
10898    case Intrinsic::x86_fma_vfmsubadd_pd:
10899    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10900    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10901      Opc = X86ISD::FMSUBADD;
10902      break;
10903    }
10904
10905    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10906                       Op.getOperand(2), Op.getOperand(3));
10907  }
10908  }
10909}
10910
10911static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10912  DebugLoc dl = Op.getDebugLoc();
10913  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10914  switch (IntNo) {
10915  default: return SDValue();    // Don't custom lower most intrinsics.
10916
10917  // RDRAND/RDSEED intrinsics.
10918  case Intrinsic::x86_rdrand_16:
10919  case Intrinsic::x86_rdrand_32:
10920  case Intrinsic::x86_rdrand_64:
10921  case Intrinsic::x86_rdseed_16:
10922  case Intrinsic::x86_rdseed_32:
10923  case Intrinsic::x86_rdseed_64: {
10924    unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10925                       IntNo == Intrinsic::x86_rdseed_32 ||
10926                       IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10927                                                            X86ISD::RDRAND;
10928    // Emit the node with the right value type.
10929    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10930    SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10931
10932    // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10933    // Otherwise return the value from Rand, which is always 0, casted to i32.
10934    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10935                      DAG.getConstant(1, Op->getValueType(1)),
10936                      DAG.getConstant(X86::COND_B, MVT::i32),
10937                      SDValue(Result.getNode(), 1) };
10938    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10939                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10940                                  Ops, 4);
10941
10942    // Return { result, isValid, chain }.
10943    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10944                       SDValue(Result.getNode(), 2));
10945  }
10946
10947  // XTEST intrinsics.
10948  case Intrinsic::x86_xtest: {
10949    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10950    SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10951    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10952                                DAG.getConstant(X86::COND_NE, MVT::i8),
10953                                InTrans);
10954    SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
10955    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
10956                       Ret, SDValue(InTrans.getNode(), 1));
10957  }
10958  }
10959}
10960
10961SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10962                                           SelectionDAG &DAG) const {
10963  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10964  MFI->setReturnAddressIsTaken(true);
10965
10966  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10967  DebugLoc dl = Op.getDebugLoc();
10968  EVT PtrVT = getPointerTy();
10969
10970  if (Depth > 0) {
10971    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10972    SDValue Offset =
10973      DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10974    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10975                       DAG.getNode(ISD::ADD, dl, PtrVT,
10976                                   FrameAddr, Offset),
10977                       MachinePointerInfo(), false, false, false, 0);
10978  }
10979
10980  // Just load the return address.
10981  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10982  return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10983                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10984}
10985
10986SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10987  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10988  MFI->setFrameAddressIsTaken(true);
10989
10990  EVT VT = Op.getValueType();
10991  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10992  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10993  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10994  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10995  while (Depth--)
10996    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10997                            MachinePointerInfo(),
10998                            false, false, false, 0);
10999  return FrameAddr;
11000}
11001
11002SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11003                                                     SelectionDAG &DAG) const {
11004  return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11005}
11006
11007SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11008  SDValue Chain     = Op.getOperand(0);
11009  SDValue Offset    = Op.getOperand(1);
11010  SDValue Handler   = Op.getOperand(2);
11011  DebugLoc dl       = Op.getDebugLoc();
11012
11013  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
11014                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
11015                                     getPointerTy());
11016  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
11017
11018  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11019                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11020  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11021  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11022                       false, false, 0);
11023  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11024
11025  return DAG.getNode(X86ISD::EH_RETURN, dl,
11026                     MVT::Other,
11027                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11028}
11029
11030SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11031                                               SelectionDAG &DAG) const {
11032  DebugLoc DL = Op.getDebugLoc();
11033  return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11034                     DAG.getVTList(MVT::i32, MVT::Other),
11035                     Op.getOperand(0), Op.getOperand(1));
11036}
11037
11038SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11039                                                SelectionDAG &DAG) const {
11040  DebugLoc DL = Op.getDebugLoc();
11041  return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11042                     Op.getOperand(0), Op.getOperand(1));
11043}
11044
11045static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11046  return Op.getOperand(0);
11047}
11048
11049SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11050                                                SelectionDAG &DAG) const {
11051  SDValue Root = Op.getOperand(0);
11052  SDValue Trmp = Op.getOperand(1); // trampoline
11053  SDValue FPtr = Op.getOperand(2); // nested function
11054  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11055  DebugLoc dl  = Op.getDebugLoc();
11056
11057  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11058  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11059
11060  if (Subtarget->is64Bit()) {
11061    SDValue OutChains[6];
11062
11063    // Large code-model.
11064    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11065    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11066
11067    const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11068    const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11069
11070    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11071
11072    // Load the pointer to the nested function into R11.
11073    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11074    SDValue Addr = Trmp;
11075    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11076                                Addr, MachinePointerInfo(TrmpAddr),
11077                                false, false, 0);
11078
11079    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11080                       DAG.getConstant(2, MVT::i64));
11081    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11082                                MachinePointerInfo(TrmpAddr, 2),
11083                                false, false, 2);
11084
11085    // Load the 'nest' parameter value into R10.
11086    // R10 is specified in X86CallingConv.td
11087    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11088    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11089                       DAG.getConstant(10, MVT::i64));
11090    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11091                                Addr, MachinePointerInfo(TrmpAddr, 10),
11092                                false, false, 0);
11093
11094    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11095                       DAG.getConstant(12, MVT::i64));
11096    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11097                                MachinePointerInfo(TrmpAddr, 12),
11098                                false, false, 2);
11099
11100    // Jump to the nested function.
11101    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11102    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11103                       DAG.getConstant(20, MVT::i64));
11104    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11105                                Addr, MachinePointerInfo(TrmpAddr, 20),
11106                                false, false, 0);
11107
11108    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11109    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11110                       DAG.getConstant(22, MVT::i64));
11111    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11112                                MachinePointerInfo(TrmpAddr, 22),
11113                                false, false, 0);
11114
11115    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11116  } else {
11117    const Function *Func =
11118      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11119    CallingConv::ID CC = Func->getCallingConv();
11120    unsigned NestReg;
11121
11122    switch (CC) {
11123    default:
11124      llvm_unreachable("Unsupported calling convention");
11125    case CallingConv::C:
11126    case CallingConv::X86_StdCall: {
11127      // Pass 'nest' parameter in ECX.
11128      // Must be kept in sync with X86CallingConv.td
11129      NestReg = X86::ECX;
11130
11131      // Check that ECX wasn't needed by an 'inreg' parameter.
11132      FunctionType *FTy = Func->getFunctionType();
11133      const AttributeSet &Attrs = Func->getAttributes();
11134
11135      if (!Attrs.isEmpty() && !Func->isVarArg()) {
11136        unsigned InRegCount = 0;
11137        unsigned Idx = 1;
11138
11139        for (FunctionType::param_iterator I = FTy->param_begin(),
11140             E = FTy->param_end(); I != E; ++I, ++Idx)
11141          if (Attrs.hasAttribute(Idx, Attribute::InReg))
11142            // FIXME: should only count parameters that are lowered to integers.
11143            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11144
11145        if (InRegCount > 2) {
11146          report_fatal_error("Nest register in use - reduce number of inreg"
11147                             " parameters!");
11148        }
11149      }
11150      break;
11151    }
11152    case CallingConv::X86_FastCall:
11153    case CallingConv::X86_ThisCall:
11154    case CallingConv::Fast:
11155      // Pass 'nest' parameter in EAX.
11156      // Must be kept in sync with X86CallingConv.td
11157      NestReg = X86::EAX;
11158      break;
11159    }
11160
11161    SDValue OutChains[4];
11162    SDValue Addr, Disp;
11163
11164    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11165                       DAG.getConstant(10, MVT::i32));
11166    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11167
11168    // This is storing the opcode for MOV32ri.
11169    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11170    const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11171    OutChains[0] = DAG.getStore(Root, dl,
11172                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11173                                Trmp, MachinePointerInfo(TrmpAddr),
11174                                false, false, 0);
11175
11176    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11177                       DAG.getConstant(1, MVT::i32));
11178    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11179                                MachinePointerInfo(TrmpAddr, 1),
11180                                false, false, 1);
11181
11182    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11183    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11184                       DAG.getConstant(5, MVT::i32));
11185    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11186                                MachinePointerInfo(TrmpAddr, 5),
11187                                false, false, 1);
11188
11189    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11190                       DAG.getConstant(6, MVT::i32));
11191    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11192                                MachinePointerInfo(TrmpAddr, 6),
11193                                false, false, 1);
11194
11195    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11196  }
11197}
11198
11199SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11200                                            SelectionDAG &DAG) const {
11201  /*
11202   The rounding mode is in bits 11:10 of FPSR, and has the following
11203   settings:
11204     00 Round to nearest
11205     01 Round to -inf
11206     10 Round to +inf
11207     11 Round to 0
11208
11209  FLT_ROUNDS, on the other hand, expects the following:
11210    -1 Undefined
11211     0 Round to 0
11212     1 Round to nearest
11213     2 Round to +inf
11214     3 Round to -inf
11215
11216  To perform the conversion, we do:
11217    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11218  */
11219
11220  MachineFunction &MF = DAG.getMachineFunction();
11221  const TargetMachine &TM = MF.getTarget();
11222  const TargetFrameLowering &TFI = *TM.getFrameLowering();
11223  unsigned StackAlignment = TFI.getStackAlignment();
11224  EVT VT = Op.getValueType();
11225  DebugLoc DL = Op.getDebugLoc();
11226
11227  // Save FP Control Word to stack slot
11228  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11229  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11230
11231  MachineMemOperand *MMO =
11232   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11233                           MachineMemOperand::MOStore, 2, 2);
11234
11235  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11236  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11237                                          DAG.getVTList(MVT::Other),
11238                                          Ops, 2, MVT::i16, MMO);
11239
11240  // Load FP Control Word from stack slot
11241  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11242                            MachinePointerInfo(), false, false, false, 0);
11243
11244  // Transform as necessary
11245  SDValue CWD1 =
11246    DAG.getNode(ISD::SRL, DL, MVT::i16,
11247                DAG.getNode(ISD::AND, DL, MVT::i16,
11248                            CWD, DAG.getConstant(0x800, MVT::i16)),
11249                DAG.getConstant(11, MVT::i8));
11250  SDValue CWD2 =
11251    DAG.getNode(ISD::SRL, DL, MVT::i16,
11252                DAG.getNode(ISD::AND, DL, MVT::i16,
11253                            CWD, DAG.getConstant(0x400, MVT::i16)),
11254                DAG.getConstant(9, MVT::i8));
11255
11256  SDValue RetVal =
11257    DAG.getNode(ISD::AND, DL, MVT::i16,
11258                DAG.getNode(ISD::ADD, DL, MVT::i16,
11259                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11260                            DAG.getConstant(1, MVT::i16)),
11261                DAG.getConstant(3, MVT::i16));
11262
11263  return DAG.getNode((VT.getSizeInBits() < 16 ?
11264                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11265}
11266
11267static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11268  EVT VT = Op.getValueType();
11269  EVT OpVT = VT;
11270  unsigned NumBits = VT.getSizeInBits();
11271  DebugLoc dl = Op.getDebugLoc();
11272
11273  Op = Op.getOperand(0);
11274  if (VT == MVT::i8) {
11275    // Zero extend to i32 since there is not an i8 bsr.
11276    OpVT = MVT::i32;
11277    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11278  }
11279
11280  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11281  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11282  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11283
11284  // If src is zero (i.e. bsr sets ZF), returns NumBits.
11285  SDValue Ops[] = {
11286    Op,
11287    DAG.getConstant(NumBits+NumBits-1, OpVT),
11288    DAG.getConstant(X86::COND_E, MVT::i8),
11289    Op.getValue(1)
11290  };
11291  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11292
11293  // Finally xor with NumBits-1.
11294  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11295
11296  if (VT == MVT::i8)
11297    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11298  return Op;
11299}
11300
11301static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11302  EVT VT = Op.getValueType();
11303  EVT OpVT = VT;
11304  unsigned NumBits = VT.getSizeInBits();
11305  DebugLoc dl = Op.getDebugLoc();
11306
11307  Op = Op.getOperand(0);
11308  if (VT == MVT::i8) {
11309    // Zero extend to i32 since there is not an i8 bsr.
11310    OpVT = MVT::i32;
11311    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11312  }
11313
11314  // Issue a bsr (scan bits in reverse).
11315  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11316  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11317
11318  // And xor with NumBits-1.
11319  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11320
11321  if (VT == MVT::i8)
11322    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11323  return Op;
11324}
11325
11326static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11327  EVT VT = Op.getValueType();
11328  unsigned NumBits = VT.getSizeInBits();
11329  DebugLoc dl = Op.getDebugLoc();
11330  Op = Op.getOperand(0);
11331
11332  // Issue a bsf (scan bits forward) which also sets EFLAGS.
11333  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11334  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11335
11336  // If src is zero (i.e. bsf sets ZF), returns NumBits.
11337  SDValue Ops[] = {
11338    Op,
11339    DAG.getConstant(NumBits, VT),
11340    DAG.getConstant(X86::COND_E, MVT::i8),
11341    Op.getValue(1)
11342  };
11343  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11344}
11345
11346// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11347// ones, and then concatenate the result back.
11348static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11349  EVT VT = Op.getValueType();
11350
11351  assert(VT.is256BitVector() && VT.isInteger() &&
11352         "Unsupported value type for operation");
11353
11354  unsigned NumElems = VT.getVectorNumElements();
11355  DebugLoc dl = Op.getDebugLoc();
11356
11357  // Extract the LHS vectors
11358  SDValue LHS = Op.getOperand(0);
11359  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11360  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11361
11362  // Extract the RHS vectors
11363  SDValue RHS = Op.getOperand(1);
11364  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11365  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11366
11367  MVT EltVT = VT.getVectorElementType().getSimpleVT();
11368  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11369
11370  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11371                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11372                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11373}
11374
11375static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11376  assert(Op.getValueType().is256BitVector() &&
11377         Op.getValueType().isInteger() &&
11378         "Only handle AVX 256-bit vector integer operation");
11379  return Lower256IntArith(Op, DAG);
11380}
11381
11382static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11383  assert(Op.getValueType().is256BitVector() &&
11384         Op.getValueType().isInteger() &&
11385         "Only handle AVX 256-bit vector integer operation");
11386  return Lower256IntArith(Op, DAG);
11387}
11388
11389static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11390                        SelectionDAG &DAG) {
11391  DebugLoc dl = Op.getDebugLoc();
11392  EVT VT = Op.getValueType();
11393
11394  // Decompose 256-bit ops into smaller 128-bit ops.
11395  if (VT.is256BitVector() && !Subtarget->hasInt256())
11396    return Lower256IntArith(Op, DAG);
11397
11398  SDValue A = Op.getOperand(0);
11399  SDValue B = Op.getOperand(1);
11400
11401  // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11402  if (VT == MVT::v4i32) {
11403    assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11404           "Should not custom lower when pmuldq is available!");
11405
11406    // Extract the odd parts.
11407    const int UnpackMask[] = { 1, -1, 3, -1 };
11408    SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11409    SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11410
11411    // Multiply the even parts.
11412    SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11413    // Now multiply odd parts.
11414    SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11415
11416    Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11417    Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11418
11419    // Merge the two vectors back together with a shuffle. This expands into 2
11420    // shuffles.
11421    const int ShufMask[] = { 0, 4, 2, 6 };
11422    return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11423  }
11424
11425  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11426         "Only know how to lower V2I64/V4I64 multiply");
11427
11428  //  Ahi = psrlqi(a, 32);
11429  //  Bhi = psrlqi(b, 32);
11430  //
11431  //  AloBlo = pmuludq(a, b);
11432  //  AloBhi = pmuludq(a, Bhi);
11433  //  AhiBlo = pmuludq(Ahi, b);
11434
11435  //  AloBhi = psllqi(AloBhi, 32);
11436  //  AhiBlo = psllqi(AhiBlo, 32);
11437  //  return AloBlo + AloBhi + AhiBlo;
11438
11439  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11440
11441  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11442  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11443
11444  // Bit cast to 32-bit vectors for MULUDQ
11445  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11446  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11447  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11448  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11449  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11450
11451  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11452  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11453  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11454
11455  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11456  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11457
11458  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11459  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11460}
11461
11462SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11463  EVT VT = Op.getValueType();
11464  EVT EltTy = VT.getVectorElementType();
11465  unsigned NumElts = VT.getVectorNumElements();
11466  SDValue N0 = Op.getOperand(0);
11467  DebugLoc dl = Op.getDebugLoc();
11468
11469  // Lower sdiv X, pow2-const.
11470  BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11471  if (!C)
11472    return SDValue();
11473
11474  APInt SplatValue, SplatUndef;
11475  unsigned MinSplatBits;
11476  bool HasAnyUndefs;
11477  if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11478    return SDValue();
11479
11480  if ((SplatValue != 0) &&
11481      (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11482    unsigned lg2 = SplatValue.countTrailingZeros();
11483    // Splat the sign bit.
11484    SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11485    SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11486    // Add (N0 < 0) ? abs2 - 1 : 0;
11487    SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11488    SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11489    SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11490    SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11491    SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11492
11493    // If we're dividing by a positive value, we're done.  Otherwise, we must
11494    // negate the result.
11495    if (SplatValue.isNonNegative())
11496      return SRA;
11497
11498    SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11499    SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11500    return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11501  }
11502  return SDValue();
11503}
11504
11505static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11506                                         const X86Subtarget *Subtarget) {
11507  EVT VT = Op.getValueType();
11508  DebugLoc dl = Op.getDebugLoc();
11509  SDValue R = Op.getOperand(0);
11510  SDValue Amt = Op.getOperand(1);
11511
11512  // Optimize shl/srl/sra with constant shift amount.
11513  if (isSplatVector(Amt.getNode())) {
11514    SDValue SclrAmt = Amt->getOperand(0);
11515    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11516      uint64_t ShiftAmt = C->getZExtValue();
11517
11518      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11519          (Subtarget->hasInt256() &&
11520           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11521        if (Op.getOpcode() == ISD::SHL)
11522          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11523                             DAG.getConstant(ShiftAmt, MVT::i32));
11524        if (Op.getOpcode() == ISD::SRL)
11525          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11526                             DAG.getConstant(ShiftAmt, MVT::i32));
11527        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11528          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11529                             DAG.getConstant(ShiftAmt, MVT::i32));
11530      }
11531
11532      if (VT == MVT::v16i8) {
11533        if (Op.getOpcode() == ISD::SHL) {
11534          // Make a large shift.
11535          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11536                                    DAG.getConstant(ShiftAmt, MVT::i32));
11537          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11538          // Zero out the rightmost bits.
11539          SmallVector<SDValue, 16> V(16,
11540                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11541                                                     MVT::i8));
11542          return DAG.getNode(ISD::AND, dl, VT, SHL,
11543                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11544        }
11545        if (Op.getOpcode() == ISD::SRL) {
11546          // Make a large shift.
11547          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11548                                    DAG.getConstant(ShiftAmt, MVT::i32));
11549          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11550          // Zero out the leftmost bits.
11551          SmallVector<SDValue, 16> V(16,
11552                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11553                                                     MVT::i8));
11554          return DAG.getNode(ISD::AND, dl, VT, SRL,
11555                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11556        }
11557        if (Op.getOpcode() == ISD::SRA) {
11558          if (ShiftAmt == 7) {
11559            // R s>> 7  ===  R s< 0
11560            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11561            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11562          }
11563
11564          // R s>> a === ((R u>> a) ^ m) - m
11565          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11566          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11567                                                         MVT::i8));
11568          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11569          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11570          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11571          return Res;
11572        }
11573        llvm_unreachable("Unknown shift opcode.");
11574      }
11575
11576      if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11577        if (Op.getOpcode() == ISD::SHL) {
11578          // Make a large shift.
11579          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11580                                    DAG.getConstant(ShiftAmt, MVT::i32));
11581          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11582          // Zero out the rightmost bits.
11583          SmallVector<SDValue, 32> V(32,
11584                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11585                                                     MVT::i8));
11586          return DAG.getNode(ISD::AND, dl, VT, SHL,
11587                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11588        }
11589        if (Op.getOpcode() == ISD::SRL) {
11590          // Make a large shift.
11591          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11592                                    DAG.getConstant(ShiftAmt, MVT::i32));
11593          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11594          // Zero out the leftmost bits.
11595          SmallVector<SDValue, 32> V(32,
11596                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11597                                                     MVT::i8));
11598          return DAG.getNode(ISD::AND, dl, VT, SRL,
11599                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11600        }
11601        if (Op.getOpcode() == ISD::SRA) {
11602          if (ShiftAmt == 7) {
11603            // R s>> 7  ===  R s< 0
11604            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11605            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11606          }
11607
11608          // R s>> a === ((R u>> a) ^ m) - m
11609          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11610          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11611                                                         MVT::i8));
11612          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11613          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11614          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11615          return Res;
11616        }
11617        llvm_unreachable("Unknown shift opcode.");
11618      }
11619    }
11620  }
11621
11622  // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11623  if (!Subtarget->is64Bit() &&
11624      (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11625      Amt.getOpcode() == ISD::BITCAST &&
11626      Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11627    Amt = Amt.getOperand(0);
11628    unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11629                     VT.getVectorNumElements();
11630    unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11631    uint64_t ShiftAmt = 0;
11632    for (unsigned i = 0; i != Ratio; ++i) {
11633      ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11634      if (C == 0)
11635        return SDValue();
11636      // 6 == Log2(64)
11637      ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11638    }
11639    // Check remaining shift amounts.
11640    for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11641      uint64_t ShAmt = 0;
11642      for (unsigned j = 0; j != Ratio; ++j) {
11643        ConstantSDNode *C =
11644          dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11645        if (C == 0)
11646          return SDValue();
11647        // 6 == Log2(64)
11648        ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11649      }
11650      if (ShAmt != ShiftAmt)
11651        return SDValue();
11652    }
11653    switch (Op.getOpcode()) {
11654    default:
11655      llvm_unreachable("Unknown shift opcode!");
11656    case ISD::SHL:
11657      return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11658                         DAG.getConstant(ShiftAmt, MVT::i32));
11659    case ISD::SRL:
11660      return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11661                         DAG.getConstant(ShiftAmt, MVT::i32));
11662    case ISD::SRA:
11663      return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11664                         DAG.getConstant(ShiftAmt, MVT::i32));
11665    }
11666  }
11667
11668  return SDValue();
11669}
11670
11671static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11672                                        const X86Subtarget* Subtarget) {
11673  EVT VT = Op.getValueType();
11674  DebugLoc dl = Op.getDebugLoc();
11675  SDValue R = Op.getOperand(0);
11676  SDValue Amt = Op.getOperand(1);
11677
11678  if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11679      VT == MVT::v4i32 || VT == MVT::v8i16 ||
11680      (Subtarget->hasInt256() &&
11681       ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11682        VT == MVT::v8i32 || VT == MVT::v16i16))) {
11683    SDValue BaseShAmt;
11684    EVT EltVT = VT.getVectorElementType();
11685
11686    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11687      unsigned NumElts = VT.getVectorNumElements();
11688      unsigned i, j;
11689      for (i = 0; i != NumElts; ++i) {
11690        if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11691          continue;
11692        break;
11693      }
11694      for (j = i; j != NumElts; ++j) {
11695        SDValue Arg = Amt.getOperand(j);
11696        if (Arg.getOpcode() == ISD::UNDEF) continue;
11697        if (Arg != Amt.getOperand(i))
11698          break;
11699      }
11700      if (i != NumElts && j == NumElts)
11701        BaseShAmt = Amt.getOperand(i);
11702    } else {
11703      if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11704        Amt = Amt.getOperand(0);
11705      if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11706               cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11707        SDValue InVec = Amt.getOperand(0);
11708        if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11709          unsigned NumElts = InVec.getValueType().getVectorNumElements();
11710          unsigned i = 0;
11711          for (; i != NumElts; ++i) {
11712            SDValue Arg = InVec.getOperand(i);
11713            if (Arg.getOpcode() == ISD::UNDEF) continue;
11714            BaseShAmt = Arg;
11715            break;
11716          }
11717        } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11718           if (ConstantSDNode *C =
11719               dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11720             unsigned SplatIdx =
11721               cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11722             if (C->getZExtValue() == SplatIdx)
11723               BaseShAmt = InVec.getOperand(1);
11724           }
11725        }
11726        if (BaseShAmt.getNode() == 0)
11727          BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11728                                  DAG.getIntPtrConstant(0));
11729      }
11730    }
11731
11732    if (BaseShAmt.getNode()) {
11733      if (EltVT.bitsGT(MVT::i32))
11734        BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11735      else if (EltVT.bitsLT(MVT::i32))
11736        BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11737
11738      switch (Op.getOpcode()) {
11739      default:
11740        llvm_unreachable("Unknown shift opcode!");
11741      case ISD::SHL:
11742        switch (VT.getSimpleVT().SimpleTy) {
11743        default: return SDValue();
11744        case MVT::v2i64:
11745        case MVT::v4i32:
11746        case MVT::v8i16:
11747        case MVT::v4i64:
11748        case MVT::v8i32:
11749        case MVT::v16i16:
11750          return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11751        }
11752      case ISD::SRA:
11753        switch (VT.getSimpleVT().SimpleTy) {
11754        default: return SDValue();
11755        case MVT::v4i32:
11756        case MVT::v8i16:
11757        case MVT::v8i32:
11758        case MVT::v16i16:
11759          return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11760        }
11761      case ISD::SRL:
11762        switch (VT.getSimpleVT().SimpleTy) {
11763        default: return SDValue();
11764        case MVT::v2i64:
11765        case MVT::v4i32:
11766        case MVT::v8i16:
11767        case MVT::v4i64:
11768        case MVT::v8i32:
11769        case MVT::v16i16:
11770          return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11771        }
11772      }
11773    }
11774  }
11775
11776  // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11777  if (!Subtarget->is64Bit() &&
11778      (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11779      Amt.getOpcode() == ISD::BITCAST &&
11780      Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11781    Amt = Amt.getOperand(0);
11782    unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11783                     VT.getVectorNumElements();
11784    std::vector<SDValue> Vals(Ratio);
11785    for (unsigned i = 0; i != Ratio; ++i)
11786      Vals[i] = Amt.getOperand(i);
11787    for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11788      for (unsigned j = 0; j != Ratio; ++j)
11789        if (Vals[j] != Amt.getOperand(i + j))
11790          return SDValue();
11791    }
11792    switch (Op.getOpcode()) {
11793    default:
11794      llvm_unreachable("Unknown shift opcode!");
11795    case ISD::SHL:
11796      return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11797    case ISD::SRL:
11798      return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11799    case ISD::SRA:
11800      return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11801    }
11802  }
11803
11804  return SDValue();
11805}
11806
11807SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11808
11809  EVT VT = Op.getValueType();
11810  DebugLoc dl = Op.getDebugLoc();
11811  SDValue R = Op.getOperand(0);
11812  SDValue Amt = Op.getOperand(1);
11813  SDValue V;
11814
11815  if (!Subtarget->hasSSE2())
11816    return SDValue();
11817
11818  V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11819  if (V.getNode())
11820    return V;
11821
11822  V = LowerScalarVariableShift(Op, DAG, Subtarget);
11823  if (V.getNode())
11824      return V;
11825
11826  // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11827  if (Subtarget->hasInt256()) {
11828    if (Op.getOpcode() == ISD::SRL &&
11829        (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11830         VT == MVT::v4i64 || VT == MVT::v8i32))
11831      return Op;
11832    if (Op.getOpcode() == ISD::SHL &&
11833        (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11834         VT == MVT::v4i64 || VT == MVT::v8i32))
11835      return Op;
11836    if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11837      return Op;
11838  }
11839
11840  // Lower SHL with variable shift amount.
11841  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11842    Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11843
11844    Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11845    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11846    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11847    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11848  }
11849  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11850    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11851
11852    // a = a << 5;
11853    Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11854    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11855
11856    // Turn 'a' into a mask suitable for VSELECT
11857    SDValue VSelM = DAG.getConstant(0x80, VT);
11858    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11859    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11860
11861    SDValue CM1 = DAG.getConstant(0x0f, VT);
11862    SDValue CM2 = DAG.getConstant(0x3f, VT);
11863
11864    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11865    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11866    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11867                            DAG.getConstant(4, MVT::i32), DAG);
11868    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11869    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11870
11871    // a += a
11872    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11873    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11874    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11875
11876    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11877    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11878    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11879                            DAG.getConstant(2, MVT::i32), DAG);
11880    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11881    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11882
11883    // a += a
11884    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11885    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11886    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11887
11888    // return VSELECT(r, r+r, a);
11889    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11890                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11891    return R;
11892  }
11893
11894  // Decompose 256-bit shifts into smaller 128-bit shifts.
11895  if (VT.is256BitVector()) {
11896    unsigned NumElems = VT.getVectorNumElements();
11897    MVT EltVT = VT.getVectorElementType().getSimpleVT();
11898    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11899
11900    // Extract the two vectors
11901    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11902    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11903
11904    // Recreate the shift amount vectors
11905    SDValue Amt1, Amt2;
11906    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11907      // Constant shift amount
11908      SmallVector<SDValue, 4> Amt1Csts;
11909      SmallVector<SDValue, 4> Amt2Csts;
11910      for (unsigned i = 0; i != NumElems/2; ++i)
11911        Amt1Csts.push_back(Amt->getOperand(i));
11912      for (unsigned i = NumElems/2; i != NumElems; ++i)
11913        Amt2Csts.push_back(Amt->getOperand(i));
11914
11915      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11916                                 &Amt1Csts[0], NumElems/2);
11917      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11918                                 &Amt2Csts[0], NumElems/2);
11919    } else {
11920      // Variable shift amount
11921      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11922      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11923    }
11924
11925    // Issue new vector shifts for the smaller types
11926    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11927    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11928
11929    // Concatenate the result back
11930    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11931  }
11932
11933  return SDValue();
11934}
11935
11936static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11937  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11938  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11939  // looks for this combo and may remove the "setcc" instruction if the "setcc"
11940  // has only one use.
11941  SDNode *N = Op.getNode();
11942  SDValue LHS = N->getOperand(0);
11943  SDValue RHS = N->getOperand(1);
11944  unsigned BaseOp = 0;
11945  unsigned Cond = 0;
11946  DebugLoc DL = Op.getDebugLoc();
11947  switch (Op.getOpcode()) {
11948  default: llvm_unreachable("Unknown ovf instruction!");
11949  case ISD::SADDO:
11950    // A subtract of one will be selected as a INC. Note that INC doesn't
11951    // set CF, so we can't do this for UADDO.
11952    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11953      if (C->isOne()) {
11954        BaseOp = X86ISD::INC;
11955        Cond = X86::COND_O;
11956        break;
11957      }
11958    BaseOp = X86ISD::ADD;
11959    Cond = X86::COND_O;
11960    break;
11961  case ISD::UADDO:
11962    BaseOp = X86ISD::ADD;
11963    Cond = X86::COND_B;
11964    break;
11965  case ISD::SSUBO:
11966    // A subtract of one will be selected as a DEC. Note that DEC doesn't
11967    // set CF, so we can't do this for USUBO.
11968    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11969      if (C->isOne()) {
11970        BaseOp = X86ISD::DEC;
11971        Cond = X86::COND_O;
11972        break;
11973      }
11974    BaseOp = X86ISD::SUB;
11975    Cond = X86::COND_O;
11976    break;
11977  case ISD::USUBO:
11978    BaseOp = X86ISD::SUB;
11979    Cond = X86::COND_B;
11980    break;
11981  case ISD::SMULO:
11982    BaseOp = X86ISD::SMUL;
11983    Cond = X86::COND_O;
11984    break;
11985  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11986    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11987                                 MVT::i32);
11988    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11989
11990    SDValue SetCC =
11991      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11992                  DAG.getConstant(X86::COND_O, MVT::i32),
11993                  SDValue(Sum.getNode(), 2));
11994
11995    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11996  }
11997  }
11998
11999  // Also sets EFLAGS.
12000  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12001  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12002
12003  SDValue SetCC =
12004    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12005                DAG.getConstant(Cond, MVT::i32),
12006                SDValue(Sum.getNode(), 1));
12007
12008  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12009}
12010
12011SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12012                                                  SelectionDAG &DAG) const {
12013  DebugLoc dl = Op.getDebugLoc();
12014  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12015  EVT VT = Op.getValueType();
12016
12017  if (!Subtarget->hasSSE2() || !VT.isVector())
12018    return SDValue();
12019
12020  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12021                      ExtraVT.getScalarType().getSizeInBits();
12022  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12023
12024  switch (VT.getSimpleVT().SimpleTy) {
12025    default: return SDValue();
12026    case MVT::v8i32:
12027    case MVT::v16i16:
12028      if (!Subtarget->hasFp256())
12029        return SDValue();
12030      if (!Subtarget->hasInt256()) {
12031        // needs to be split
12032        unsigned NumElems = VT.getVectorNumElements();
12033
12034        // Extract the LHS vectors
12035        SDValue LHS = Op.getOperand(0);
12036        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12037        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12038
12039        MVT EltVT = VT.getVectorElementType().getSimpleVT();
12040        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12041
12042        EVT ExtraEltVT = ExtraVT.getVectorElementType();
12043        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12044        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12045                                   ExtraNumElems/2);
12046        SDValue Extra = DAG.getValueType(ExtraVT);
12047
12048        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12049        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12050
12051        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12052      }
12053      // fall through
12054    case MVT::v4i32:
12055    case MVT::v8i16: {
12056      // (sext (vzext x)) -> (vsext x)
12057      SDValue Op0 = Op.getOperand(0);
12058      SDValue Op00 = Op0.getOperand(0);
12059      SDValue Tmp1;
12060      // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12061      if (Op0.getOpcode() == ISD::BITCAST &&
12062          Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12063        Tmp1 = LowerVectorIntExtend(Op00, DAG);
12064      if (Tmp1.getNode()) {
12065        SDValue Tmp1Op0 = Tmp1.getOperand(0);
12066        assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12067               "This optimization is invalid without a VZEXT.");
12068        return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12069      }
12070
12071      // If the above didn't work, then just use Shift-Left + Shift-Right.
12072      Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12073      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12074    }
12075  }
12076}
12077
12078static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
12079                              SelectionDAG &DAG) {
12080  DebugLoc dl = Op.getDebugLoc();
12081
12082  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
12083  // There isn't any reason to disable it if the target processor supports it.
12084  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
12085    SDValue Chain = Op.getOperand(0);
12086    SDValue Zero = DAG.getConstant(0, MVT::i32);
12087    SDValue Ops[] = {
12088      DAG.getRegister(X86::ESP, MVT::i32), // Base
12089      DAG.getTargetConstant(1, MVT::i8),   // Scale
12090      DAG.getRegister(0, MVT::i32),        // Index
12091      DAG.getTargetConstant(0, MVT::i32),  // Disp
12092      DAG.getRegister(0, MVT::i32),        // Segment.
12093      Zero,
12094      Chain
12095    };
12096    SDNode *Res =
12097      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12098                          array_lengthof(Ops));
12099    return SDValue(Res, 0);
12100  }
12101
12102  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
12103  if (!isDev)
12104    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12105
12106  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12107  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12108  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
12109  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
12110
12111  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
12112  if (!Op1 && !Op2 && !Op3 && Op4)
12113    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
12114
12115  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
12116  if (Op1 && !Op2 && !Op3 && !Op4)
12117    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
12118
12119  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
12120  //           (MFENCE)>;
12121  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12122}
12123
12124static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12125                                 SelectionDAG &DAG) {
12126  DebugLoc dl = Op.getDebugLoc();
12127  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12128    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12129  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12130    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12131
12132  // The only fence that needs an instruction is a sequentially-consistent
12133  // cross-thread fence.
12134  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12135    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12136    // no-sse2). There isn't any reason to disable it if the target processor
12137    // supports it.
12138    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12139      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12140
12141    SDValue Chain = Op.getOperand(0);
12142    SDValue Zero = DAG.getConstant(0, MVT::i32);
12143    SDValue Ops[] = {
12144      DAG.getRegister(X86::ESP, MVT::i32), // Base
12145      DAG.getTargetConstant(1, MVT::i8),   // Scale
12146      DAG.getRegister(0, MVT::i32),        // Index
12147      DAG.getTargetConstant(0, MVT::i32),  // Disp
12148      DAG.getRegister(0, MVT::i32),        // Segment.
12149      Zero,
12150      Chain
12151    };
12152    SDNode *Res =
12153      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12154                         array_lengthof(Ops));
12155    return SDValue(Res, 0);
12156  }
12157
12158  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12159  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12160}
12161
12162static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12163                             SelectionDAG &DAG) {
12164  EVT T = Op.getValueType();
12165  DebugLoc DL = Op.getDebugLoc();
12166  unsigned Reg = 0;
12167  unsigned size = 0;
12168  switch(T.getSimpleVT().SimpleTy) {
12169  default: llvm_unreachable("Invalid value type!");
12170  case MVT::i8:  Reg = X86::AL;  size = 1; break;
12171  case MVT::i16: Reg = X86::AX;  size = 2; break;
12172  case MVT::i32: Reg = X86::EAX; size = 4; break;
12173  case MVT::i64:
12174    assert(Subtarget->is64Bit() && "Node not type legal!");
12175    Reg = X86::RAX; size = 8;
12176    break;
12177  }
12178  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12179                                    Op.getOperand(2), SDValue());
12180  SDValue Ops[] = { cpIn.getValue(0),
12181                    Op.getOperand(1),
12182                    Op.getOperand(3),
12183                    DAG.getTargetConstant(size, MVT::i8),
12184                    cpIn.getValue(1) };
12185  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12186  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12187  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12188                                           Ops, 5, T, MMO);
12189  SDValue cpOut =
12190    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12191  return cpOut;
12192}
12193
12194static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12195                                     SelectionDAG &DAG) {
12196  assert(Subtarget->is64Bit() && "Result not type legalized?");
12197  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12198  SDValue TheChain = Op.getOperand(0);
12199  DebugLoc dl = Op.getDebugLoc();
12200  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12201  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12202  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12203                                   rax.getValue(2));
12204  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12205                            DAG.getConstant(32, MVT::i8));
12206  SDValue Ops[] = {
12207    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12208    rdx.getValue(1)
12209  };
12210  return DAG.getMergeValues(Ops, 2, dl);
12211}
12212
12213SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12214  EVT SrcVT = Op.getOperand(0).getValueType();
12215  EVT DstVT = Op.getValueType();
12216  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12217         Subtarget->hasMMX() && "Unexpected custom BITCAST");
12218  assert((DstVT == MVT::i64 ||
12219          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12220         "Unexpected custom BITCAST");
12221  // i64 <=> MMX conversions are Legal.
12222  if (SrcVT==MVT::i64 && DstVT.isVector())
12223    return Op;
12224  if (DstVT==MVT::i64 && SrcVT.isVector())
12225    return Op;
12226  // MMX <=> MMX conversions are Legal.
12227  if (SrcVT.isVector() && DstVT.isVector())
12228    return Op;
12229  // All other conversions need to be expanded.
12230  return SDValue();
12231}
12232
12233static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12234  SDNode *Node = Op.getNode();
12235  DebugLoc dl = Node->getDebugLoc();
12236  EVT T = Node->getValueType(0);
12237  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12238                              DAG.getConstant(0, T), Node->getOperand(2));
12239  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12240                       cast<AtomicSDNode>(Node)->getMemoryVT(),
12241                       Node->getOperand(0),
12242                       Node->getOperand(1), negOp,
12243                       cast<AtomicSDNode>(Node)->getSrcValue(),
12244                       cast<AtomicSDNode>(Node)->getAlignment(),
12245                       cast<AtomicSDNode>(Node)->getOrdering(),
12246                       cast<AtomicSDNode>(Node)->getSynchScope());
12247}
12248
12249static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12250  SDNode *Node = Op.getNode();
12251  DebugLoc dl = Node->getDebugLoc();
12252  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12253
12254  // Convert seq_cst store -> xchg
12255  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12256  // FIXME: On 32-bit, store -> fist or movq would be more efficient
12257  //        (The only way to get a 16-byte store is cmpxchg16b)
12258  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12259  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12260      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12261    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12262                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
12263                                 Node->getOperand(0),
12264                                 Node->getOperand(1), Node->getOperand(2),
12265                                 cast<AtomicSDNode>(Node)->getMemOperand(),
12266                                 cast<AtomicSDNode>(Node)->getOrdering(),
12267                                 cast<AtomicSDNode>(Node)->getSynchScope());
12268    return Swap.getValue(1);
12269  }
12270  // Other atomic stores have a simple pattern.
12271  return Op;
12272}
12273
12274static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12275  EVT VT = Op.getNode()->getValueType(0);
12276
12277  // Let legalize expand this if it isn't a legal type yet.
12278  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12279    return SDValue();
12280
12281  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12282
12283  unsigned Opc;
12284  bool ExtraOp = false;
12285  switch (Op.getOpcode()) {
12286  default: llvm_unreachable("Invalid code");
12287  case ISD::ADDC: Opc = X86ISD::ADD; break;
12288  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12289  case ISD::SUBC: Opc = X86ISD::SUB; break;
12290  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12291  }
12292
12293  if (!ExtraOp)
12294    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12295                       Op.getOperand(1));
12296  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12297                     Op.getOperand(1), Op.getOperand(2));
12298}
12299
12300SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12301  assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12302
12303  // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12304  // which returns the values in two XMM registers.
12305  DebugLoc dl = Op.getDebugLoc();
12306  SDValue Arg = Op.getOperand(0);
12307  EVT ArgVT = Arg.getValueType();
12308  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12309
12310  ArgListTy Args;
12311  ArgListEntry Entry;
12312
12313  Entry.Node = Arg;
12314  Entry.Ty = ArgTy;
12315  Entry.isSExt = false;
12316  Entry.isZExt = false;
12317  Args.push_back(Entry);
12318
12319  // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12320  // the small struct {f32, f32} is returned in (eax, edx). For f64,
12321  // the results are returned via SRet in memory.
12322  const char *LibcallName = (ArgVT == MVT::f64)
12323    ? "__sincos_stret" : "__sincosf_stret";
12324  SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12325
12326  StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12327  TargetLowering::
12328    CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12329                         false, false, false, false, 0,
12330                         CallingConv::C, /*isTaillCall=*/false,
12331                         /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12332                         Callee, Args, DAG, dl);
12333  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12334  return CallResult.first;
12335}
12336
12337/// LowerOperation - Provide custom lowering hooks for some operations.
12338///
12339SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12340  switch (Op.getOpcode()) {
12341  default: llvm_unreachable("Should not custom lower this!");
12342  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12343  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12344  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12345  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12346  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12347  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12348  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12349  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12350  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12351  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12352  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12353  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12354  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12355  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12356  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12357  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12358  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12359  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12360  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12361  case ISD::SHL_PARTS:
12362  case ISD::SRA_PARTS:
12363  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12364  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12365  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12366  case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12367  case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12368  case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12369  case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12370  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12371  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12372  case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12373  case ISD::FABS:               return LowerFABS(Op, DAG);
12374  case ISD::FNEG:               return LowerFNEG(Op, DAG);
12375  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12376  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12377  case ISD::SETCC:              return LowerSETCC(Op, DAG);
12378  case ISD::SELECT:             return LowerSELECT(Op, DAG);
12379  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12380  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12381  case ISD::VASTART:            return LowerVASTART(Op, DAG);
12382  case ISD::VAARG:              return LowerVAARG(Op, DAG);
12383  case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12384  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12385  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12386  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12387  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12388  case ISD::FRAME_TO_ARGS_OFFSET:
12389                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12390  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12391  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12392  case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12393  case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12394  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12395  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12396  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12397  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12398  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12399  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12400  case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12401  case ISD::SRA:
12402  case ISD::SRL:
12403  case ISD::SHL:                return LowerShift(Op, DAG);
12404  case ISD::SADDO:
12405  case ISD::UADDO:
12406  case ISD::SSUBO:
12407  case ISD::USUBO:
12408  case ISD::SMULO:
12409  case ISD::UMULO:              return LowerXALUO(Op, DAG);
12410  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12411  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12412  case ISD::ADDC:
12413  case ISD::ADDE:
12414  case ISD::SUBC:
12415  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12416  case ISD::ADD:                return LowerADD(Op, DAG);
12417  case ISD::SUB:                return LowerSUB(Op, DAG);
12418  case ISD::SDIV:               return LowerSDIV(Op, DAG);
12419  case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12420  }
12421}
12422
12423static void ReplaceATOMIC_LOAD(SDNode *Node,
12424                                  SmallVectorImpl<SDValue> &Results,
12425                                  SelectionDAG &DAG) {
12426  DebugLoc dl = Node->getDebugLoc();
12427  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12428
12429  // Convert wide load -> cmpxchg8b/cmpxchg16b
12430  // FIXME: On 32-bit, load -> fild or movq would be more efficient
12431  //        (The only way to get a 16-byte load is cmpxchg16b)
12432  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12433  SDValue Zero = DAG.getConstant(0, VT);
12434  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12435                               Node->getOperand(0),
12436                               Node->getOperand(1), Zero, Zero,
12437                               cast<AtomicSDNode>(Node)->getMemOperand(),
12438                               cast<AtomicSDNode>(Node)->getOrdering(),
12439                               cast<AtomicSDNode>(Node)->getSynchScope());
12440  Results.push_back(Swap.getValue(0));
12441  Results.push_back(Swap.getValue(1));
12442}
12443
12444static void
12445ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12446                        SelectionDAG &DAG, unsigned NewOp) {
12447  DebugLoc dl = Node->getDebugLoc();
12448  assert (Node->getValueType(0) == MVT::i64 &&
12449          "Only know how to expand i64 atomics");
12450
12451  SDValue Chain = Node->getOperand(0);
12452  SDValue In1 = Node->getOperand(1);
12453  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12454                             Node->getOperand(2), DAG.getIntPtrConstant(0));
12455  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12456                             Node->getOperand(2), DAG.getIntPtrConstant(1));
12457  SDValue Ops[] = { Chain, In1, In2L, In2H };
12458  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12459  SDValue Result =
12460    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12461                            cast<MemSDNode>(Node)->getMemOperand());
12462  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12463  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12464  Results.push_back(Result.getValue(2));
12465}
12466
12467/// ReplaceNodeResults - Replace a node with an illegal result type
12468/// with a new node built out of custom code.
12469void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12470                                           SmallVectorImpl<SDValue>&Results,
12471                                           SelectionDAG &DAG) const {
12472  DebugLoc dl = N->getDebugLoc();
12473  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12474  switch (N->getOpcode()) {
12475  default:
12476    llvm_unreachable("Do not know how to custom type legalize this operation!");
12477  case ISD::SIGN_EXTEND_INREG:
12478  case ISD::ADDC:
12479  case ISD::ADDE:
12480  case ISD::SUBC:
12481  case ISD::SUBE:
12482    // We don't want to expand or promote these.
12483    return;
12484  case ISD::FP_TO_SINT:
12485  case ISD::FP_TO_UINT: {
12486    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12487
12488    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12489      return;
12490
12491    std::pair<SDValue,SDValue> Vals =
12492        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12493    SDValue FIST = Vals.first, StackSlot = Vals.second;
12494    if (FIST.getNode() != 0) {
12495      EVT VT = N->getValueType(0);
12496      // Return a load from the stack slot.
12497      if (StackSlot.getNode() != 0)
12498        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12499                                      MachinePointerInfo(),
12500                                      false, false, false, 0));
12501      else
12502        Results.push_back(FIST);
12503    }
12504    return;
12505  }
12506  case ISD::UINT_TO_FP: {
12507    assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12508    if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12509        N->getValueType(0) != MVT::v2f32)
12510      return;
12511    SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12512                                 N->getOperand(0));
12513    SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12514                                     MVT::f64);
12515    SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12516    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12517                             DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12518    Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12519    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12520    Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12521    return;
12522  }
12523  case ISD::FP_ROUND: {
12524    if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12525        return;
12526    SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12527    Results.push_back(V);
12528    return;
12529  }
12530  case ISD::READCYCLECOUNTER: {
12531    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12532    SDValue TheChain = N->getOperand(0);
12533    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12534    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12535                                     rd.getValue(1));
12536    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12537                                     eax.getValue(2));
12538    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12539    SDValue Ops[] = { eax, edx };
12540    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12541    Results.push_back(edx.getValue(1));
12542    return;
12543  }
12544  case ISD::ATOMIC_CMP_SWAP: {
12545    EVT T = N->getValueType(0);
12546    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12547    bool Regs64bit = T == MVT::i128;
12548    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12549    SDValue cpInL, cpInH;
12550    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12551                        DAG.getConstant(0, HalfT));
12552    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12553                        DAG.getConstant(1, HalfT));
12554    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12555                             Regs64bit ? X86::RAX : X86::EAX,
12556                             cpInL, SDValue());
12557    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12558                             Regs64bit ? X86::RDX : X86::EDX,
12559                             cpInH, cpInL.getValue(1));
12560    SDValue swapInL, swapInH;
12561    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12562                          DAG.getConstant(0, HalfT));
12563    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12564                          DAG.getConstant(1, HalfT));
12565    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12566                               Regs64bit ? X86::RBX : X86::EBX,
12567                               swapInL, cpInH.getValue(1));
12568    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12569                               Regs64bit ? X86::RCX : X86::ECX,
12570                               swapInH, swapInL.getValue(1));
12571    SDValue Ops[] = { swapInH.getValue(0),
12572                      N->getOperand(1),
12573                      swapInH.getValue(1) };
12574    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12575    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12576    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12577                                  X86ISD::LCMPXCHG8_DAG;
12578    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12579                                             Ops, 3, T, MMO);
12580    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12581                                        Regs64bit ? X86::RAX : X86::EAX,
12582                                        HalfT, Result.getValue(1));
12583    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12584                                        Regs64bit ? X86::RDX : X86::EDX,
12585                                        HalfT, cpOutL.getValue(2));
12586    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12587    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12588    Results.push_back(cpOutH.getValue(1));
12589    return;
12590  }
12591  case ISD::ATOMIC_LOAD_ADD:
12592  case ISD::ATOMIC_LOAD_AND:
12593  case ISD::ATOMIC_LOAD_NAND:
12594  case ISD::ATOMIC_LOAD_OR:
12595  case ISD::ATOMIC_LOAD_SUB:
12596  case ISD::ATOMIC_LOAD_XOR:
12597  case ISD::ATOMIC_LOAD_MAX:
12598  case ISD::ATOMIC_LOAD_MIN:
12599  case ISD::ATOMIC_LOAD_UMAX:
12600  case ISD::ATOMIC_LOAD_UMIN:
12601  case ISD::ATOMIC_SWAP: {
12602    unsigned Opc;
12603    switch (N->getOpcode()) {
12604    default: llvm_unreachable("Unexpected opcode");
12605    case ISD::ATOMIC_LOAD_ADD:
12606      Opc = X86ISD::ATOMADD64_DAG;
12607      break;
12608    case ISD::ATOMIC_LOAD_AND:
12609      Opc = X86ISD::ATOMAND64_DAG;
12610      break;
12611    case ISD::ATOMIC_LOAD_NAND:
12612      Opc = X86ISD::ATOMNAND64_DAG;
12613      break;
12614    case ISD::ATOMIC_LOAD_OR:
12615      Opc = X86ISD::ATOMOR64_DAG;
12616      break;
12617    case ISD::ATOMIC_LOAD_SUB:
12618      Opc = X86ISD::ATOMSUB64_DAG;
12619      break;
12620    case ISD::ATOMIC_LOAD_XOR:
12621      Opc = X86ISD::ATOMXOR64_DAG;
12622      break;
12623    case ISD::ATOMIC_LOAD_MAX:
12624      Opc = X86ISD::ATOMMAX64_DAG;
12625      break;
12626    case ISD::ATOMIC_LOAD_MIN:
12627      Opc = X86ISD::ATOMMIN64_DAG;
12628      break;
12629    case ISD::ATOMIC_LOAD_UMAX:
12630      Opc = X86ISD::ATOMUMAX64_DAG;
12631      break;
12632    case ISD::ATOMIC_LOAD_UMIN:
12633      Opc = X86ISD::ATOMUMIN64_DAG;
12634      break;
12635    case ISD::ATOMIC_SWAP:
12636      Opc = X86ISD::ATOMSWAP64_DAG;
12637      break;
12638    }
12639    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12640    return;
12641  }
12642  case ISD::ATOMIC_LOAD:
12643    ReplaceATOMIC_LOAD(N, Results, DAG);
12644  }
12645}
12646
12647const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12648  switch (Opcode) {
12649  default: return NULL;
12650  case X86ISD::BSF:                return "X86ISD::BSF";
12651  case X86ISD::BSR:                return "X86ISD::BSR";
12652  case X86ISD::SHLD:               return "X86ISD::SHLD";
12653  case X86ISD::SHRD:               return "X86ISD::SHRD";
12654  case X86ISD::FAND:               return "X86ISD::FAND";
12655  case X86ISD::FOR:                return "X86ISD::FOR";
12656  case X86ISD::FXOR:               return "X86ISD::FXOR";
12657  case X86ISD::FSRL:               return "X86ISD::FSRL";
12658  case X86ISD::FILD:               return "X86ISD::FILD";
12659  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12660  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12661  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12662  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12663  case X86ISD::FLD:                return "X86ISD::FLD";
12664  case X86ISD::FST:                return "X86ISD::FST";
12665  case X86ISD::CALL:               return "X86ISD::CALL";
12666  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12667  case X86ISD::BT:                 return "X86ISD::BT";
12668  case X86ISD::CMP:                return "X86ISD::CMP";
12669  case X86ISD::COMI:               return "X86ISD::COMI";
12670  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12671  case X86ISD::SETCC:              return "X86ISD::SETCC";
12672  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12673  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12674  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12675  case X86ISD::CMOV:               return "X86ISD::CMOV";
12676  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12677  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12678  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12679  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12680  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12681  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12682  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12683  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12684  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12685  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12686  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12687  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12688  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12689  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12690  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12691  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12692  case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12693  case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12694  case X86ISD::HADD:               return "X86ISD::HADD";
12695  case X86ISD::HSUB:               return "X86ISD::HSUB";
12696  case X86ISD::FHADD:              return "X86ISD::FHADD";
12697  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12698  case X86ISD::UMAX:               return "X86ISD::UMAX";
12699  case X86ISD::UMIN:               return "X86ISD::UMIN";
12700  case X86ISD::SMAX:               return "X86ISD::SMAX";
12701  case X86ISD::SMIN:               return "X86ISD::SMIN";
12702  case X86ISD::FMAX:               return "X86ISD::FMAX";
12703  case X86ISD::FMIN:               return "X86ISD::FMIN";
12704  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12705  case X86ISD::FMINC:              return "X86ISD::FMINC";
12706  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12707  case X86ISD::FRCP:               return "X86ISD::FRCP";
12708  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12709  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12710  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12711  case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12712  case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12713  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12714  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12715  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12716  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12717  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12718  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12719  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12720  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12721  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12722  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12723  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12724  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12725  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12726  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12727  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12728  case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12729  case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12730  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12731  case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12732  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12733  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12734  case X86ISD::VSHL:               return "X86ISD::VSHL";
12735  case X86ISD::VSRL:               return "X86ISD::VSRL";
12736  case X86ISD::VSRA:               return "X86ISD::VSRA";
12737  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12738  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12739  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12740  case X86ISD::CMPP:               return "X86ISD::CMPP";
12741  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12742  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12743  case X86ISD::ADD:                return "X86ISD::ADD";
12744  case X86ISD::SUB:                return "X86ISD::SUB";
12745  case X86ISD::ADC:                return "X86ISD::ADC";
12746  case X86ISD::SBB:                return "X86ISD::SBB";
12747  case X86ISD::SMUL:               return "X86ISD::SMUL";
12748  case X86ISD::UMUL:               return "X86ISD::UMUL";
12749  case X86ISD::INC:                return "X86ISD::INC";
12750  case X86ISD::DEC:                return "X86ISD::DEC";
12751  case X86ISD::OR:                 return "X86ISD::OR";
12752  case X86ISD::XOR:                return "X86ISD::XOR";
12753  case X86ISD::AND:                return "X86ISD::AND";
12754  case X86ISD::BLSI:               return "X86ISD::BLSI";
12755  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12756  case X86ISD::BLSR:               return "X86ISD::BLSR";
12757  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12758  case X86ISD::PTEST:              return "X86ISD::PTEST";
12759  case X86ISD::TESTP:              return "X86ISD::TESTP";
12760  case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12761  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12762  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12763  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12764  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12765  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12766  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12767  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12768  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12769  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12770  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12771  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12772  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12773  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12774  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12775  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12776  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12777  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12778  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12779  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12780  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12781  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12782  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12783  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12784  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12785  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12786  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12787  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12788  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12789  case X86ISD::SAHF:               return "X86ISD::SAHF";
12790  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12791  case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12792  case X86ISD::FMADD:              return "X86ISD::FMADD";
12793  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12794  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12795  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12796  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12797  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12798  case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12799  case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12800  case X86ISD::XTEST:              return "X86ISD::XTEST";
12801  }
12802}
12803
12804// isLegalAddressingMode - Return true if the addressing mode represented
12805// by AM is legal for this target, for a load/store of the specified type.
12806bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12807                                              Type *Ty) const {
12808  // X86 supports extremely general addressing modes.
12809  CodeModel::Model M = getTargetMachine().getCodeModel();
12810  Reloc::Model R = getTargetMachine().getRelocationModel();
12811
12812  // X86 allows a sign-extended 32-bit immediate field as a displacement.
12813  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12814    return false;
12815
12816  if (AM.BaseGV) {
12817    unsigned GVFlags =
12818      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12819
12820    // If a reference to this global requires an extra load, we can't fold it.
12821    if (isGlobalStubReference(GVFlags))
12822      return false;
12823
12824    // If BaseGV requires a register for the PIC base, we cannot also have a
12825    // BaseReg specified.
12826    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12827      return false;
12828
12829    // If lower 4G is not available, then we must use rip-relative addressing.
12830    if ((M != CodeModel::Small || R != Reloc::Static) &&
12831        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12832      return false;
12833  }
12834
12835  switch (AM.Scale) {
12836  case 0:
12837  case 1:
12838  case 2:
12839  case 4:
12840  case 8:
12841    // These scales always work.
12842    break;
12843  case 3:
12844  case 5:
12845  case 9:
12846    // These scales are formed with basereg+scalereg.  Only accept if there is
12847    // no basereg yet.
12848    if (AM.HasBaseReg)
12849      return false;
12850    break;
12851  default:  // Other stuff never works.
12852    return false;
12853  }
12854
12855  return true;
12856}
12857
12858bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12859  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12860    return false;
12861  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12862  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12863  return NumBits1 > NumBits2;
12864}
12865
12866bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12867  return isInt<32>(Imm);
12868}
12869
12870bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12871  // Can also use sub to handle negated immediates.
12872  return isInt<32>(Imm);
12873}
12874
12875bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12876  if (!VT1.isInteger() || !VT2.isInteger())
12877    return false;
12878  unsigned NumBits1 = VT1.getSizeInBits();
12879  unsigned NumBits2 = VT2.getSizeInBits();
12880  return NumBits1 > NumBits2;
12881}
12882
12883bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12884  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12885  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12886}
12887
12888bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12889  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12890  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12891}
12892
12893bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12894  EVT VT1 = Val.getValueType();
12895  if (isZExtFree(VT1, VT2))
12896    return true;
12897
12898  if (Val.getOpcode() != ISD::LOAD)
12899    return false;
12900
12901  if (!VT1.isSimple() || !VT1.isInteger() ||
12902      !VT2.isSimple() || !VT2.isInteger())
12903    return false;
12904
12905  switch (VT1.getSimpleVT().SimpleTy) {
12906  default: break;
12907  case MVT::i8:
12908  case MVT::i16:
12909  case MVT::i32:
12910    // X86 has 8, 16, and 32-bit zero-extending loads.
12911    return true;
12912  }
12913
12914  return false;
12915}
12916
12917bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12918  // i16 instructions are longer (0x66 prefix) and potentially slower.
12919  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12920}
12921
12922/// isShuffleMaskLegal - Targets can use this to indicate that they only
12923/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12924/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12925/// are assumed to be legal.
12926bool
12927X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12928                                      EVT VT) const {
12929  // Very little shuffling can be done for 64-bit vectors right now.
12930  if (VT.getSizeInBits() == 64)
12931    return false;
12932
12933  // FIXME: pshufb, blends, shifts.
12934  return (VT.getVectorNumElements() == 2 ||
12935          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12936          isMOVLMask(M, VT) ||
12937          isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12938          isPSHUFDMask(M, VT) ||
12939          isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12940          isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12941          isPALIGNRMask(M, VT, Subtarget) ||
12942          isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12943          isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12944          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12945          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12946}
12947
12948bool
12949X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12950                                          EVT VT) const {
12951  unsigned NumElts = VT.getVectorNumElements();
12952  // FIXME: This collection of masks seems suspect.
12953  if (NumElts == 2)
12954    return true;
12955  if (NumElts == 4 && VT.is128BitVector()) {
12956    return (isMOVLMask(Mask, VT)  ||
12957            isCommutedMOVLMask(Mask, VT, true) ||
12958            isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12959            isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12960  }
12961  return false;
12962}
12963
12964//===----------------------------------------------------------------------===//
12965//                           X86 Scheduler Hooks
12966//===----------------------------------------------------------------------===//
12967
12968/// Utility function to emit xbegin specifying the start of an RTM region.
12969static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12970                                     const TargetInstrInfo *TII) {
12971  DebugLoc DL = MI->getDebugLoc();
12972
12973  const BasicBlock *BB = MBB->getBasicBlock();
12974  MachineFunction::iterator I = MBB;
12975  ++I;
12976
12977  // For the v = xbegin(), we generate
12978  //
12979  // thisMBB:
12980  //  xbegin sinkMBB
12981  //
12982  // mainMBB:
12983  //  eax = -1
12984  //
12985  // sinkMBB:
12986  //  v = eax
12987
12988  MachineBasicBlock *thisMBB = MBB;
12989  MachineFunction *MF = MBB->getParent();
12990  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12991  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12992  MF->insert(I, mainMBB);
12993  MF->insert(I, sinkMBB);
12994
12995  // Transfer the remainder of BB and its successor edges to sinkMBB.
12996  sinkMBB->splice(sinkMBB->begin(), MBB,
12997                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12998  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12999
13000  // thisMBB:
13001  //  xbegin sinkMBB
13002  //  # fallthrough to mainMBB
13003  //  # abortion to sinkMBB
13004  BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13005  thisMBB->addSuccessor(mainMBB);
13006  thisMBB->addSuccessor(sinkMBB);
13007
13008  // mainMBB:
13009  //  EAX = -1
13010  BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13011  mainMBB->addSuccessor(sinkMBB);
13012
13013  // sinkMBB:
13014  // EAX is live into the sinkMBB
13015  sinkMBB->addLiveIn(X86::EAX);
13016  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13017          TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13018    .addReg(X86::EAX);
13019
13020  MI->eraseFromParent();
13021  return sinkMBB;
13022}
13023
13024// Get CMPXCHG opcode for the specified data type.
13025static unsigned getCmpXChgOpcode(EVT VT) {
13026  switch (VT.getSimpleVT().SimpleTy) {
13027  case MVT::i8:  return X86::LCMPXCHG8;
13028  case MVT::i16: return X86::LCMPXCHG16;
13029  case MVT::i32: return X86::LCMPXCHG32;
13030  case MVT::i64: return X86::LCMPXCHG64;
13031  default:
13032    break;
13033  }
13034  llvm_unreachable("Invalid operand size!");
13035}
13036
13037// Get LOAD opcode for the specified data type.
13038static unsigned getLoadOpcode(EVT VT) {
13039  switch (VT.getSimpleVT().SimpleTy) {
13040  case MVT::i8:  return X86::MOV8rm;
13041  case MVT::i16: return X86::MOV16rm;
13042  case MVT::i32: return X86::MOV32rm;
13043  case MVT::i64: return X86::MOV64rm;
13044  default:
13045    break;
13046  }
13047  llvm_unreachable("Invalid operand size!");
13048}
13049
13050// Get opcode of the non-atomic one from the specified atomic instruction.
13051static unsigned getNonAtomicOpcode(unsigned Opc) {
13052  switch (Opc) {
13053  case X86::ATOMAND8:  return X86::AND8rr;
13054  case X86::ATOMAND16: return X86::AND16rr;
13055  case X86::ATOMAND32: return X86::AND32rr;
13056  case X86::ATOMAND64: return X86::AND64rr;
13057  case X86::ATOMOR8:   return X86::OR8rr;
13058  case X86::ATOMOR16:  return X86::OR16rr;
13059  case X86::ATOMOR32:  return X86::OR32rr;
13060  case X86::ATOMOR64:  return X86::OR64rr;
13061  case X86::ATOMXOR8:  return X86::XOR8rr;
13062  case X86::ATOMXOR16: return X86::XOR16rr;
13063  case X86::ATOMXOR32: return X86::XOR32rr;
13064  case X86::ATOMXOR64: return X86::XOR64rr;
13065  }
13066  llvm_unreachable("Unhandled atomic-load-op opcode!");
13067}
13068
13069// Get opcode of the non-atomic one from the specified atomic instruction with
13070// extra opcode.
13071static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13072                                               unsigned &ExtraOpc) {
13073  switch (Opc) {
13074  case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13075  case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13076  case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13077  case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13078  case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13079  case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13080  case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13081  case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13082  case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13083  case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13084  case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13085  case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13086  case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13087  case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13088  case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13089  case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13090  case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13091  case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13092  case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13093  case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13094  }
13095  llvm_unreachable("Unhandled atomic-load-op opcode!");
13096}
13097
13098// Get opcode of the non-atomic one from the specified atomic instruction for
13099// 64-bit data type on 32-bit target.
13100static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13101  switch (Opc) {
13102  case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13103  case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13104  case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13105  case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13106  case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13107  case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13108  case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13109  case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13110  case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13111  case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13112  }
13113  llvm_unreachable("Unhandled atomic-load-op opcode!");
13114}
13115
13116// Get opcode of the non-atomic one from the specified atomic instruction for
13117// 64-bit data type on 32-bit target with extra opcode.
13118static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13119                                                   unsigned &HiOpc,
13120                                                   unsigned &ExtraOpc) {
13121  switch (Opc) {
13122  case X86::ATOMNAND6432:
13123    ExtraOpc = X86::NOT32r;
13124    HiOpc = X86::AND32rr;
13125    return X86::AND32rr;
13126  }
13127  llvm_unreachable("Unhandled atomic-load-op opcode!");
13128}
13129
13130// Get pseudo CMOV opcode from the specified data type.
13131static unsigned getPseudoCMOVOpc(EVT VT) {
13132  switch (VT.getSimpleVT().SimpleTy) {
13133  case MVT::i8:  return X86::CMOV_GR8;
13134  case MVT::i16: return X86::CMOV_GR16;
13135  case MVT::i32: return X86::CMOV_GR32;
13136  default:
13137    break;
13138  }
13139  llvm_unreachable("Unknown CMOV opcode!");
13140}
13141
13142// EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13143// They will be translated into a spin-loop or compare-exchange loop from
13144//
13145//    ...
13146//    dst = atomic-fetch-op MI.addr, MI.val
13147//    ...
13148//
13149// to
13150//
13151//    ...
13152//    t1 = LOAD MI.addr
13153// loop:
13154//    t4 = phi(t1, t3 / loop)
13155//    t2 = OP MI.val, t4
13156//    EAX = t4
13157//    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13158//    t3 = EAX
13159//    JNE loop
13160// sink:
13161//    dst = t3
13162//    ...
13163MachineBasicBlock *
13164X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13165                                       MachineBasicBlock *MBB) const {
13166  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13167  DebugLoc DL = MI->getDebugLoc();
13168
13169  MachineFunction *MF = MBB->getParent();
13170  MachineRegisterInfo &MRI = MF->getRegInfo();
13171
13172  const BasicBlock *BB = MBB->getBasicBlock();
13173  MachineFunction::iterator I = MBB;
13174  ++I;
13175
13176  assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13177         "Unexpected number of operands");
13178
13179  assert(MI->hasOneMemOperand() &&
13180         "Expected atomic-load-op to have one memoperand");
13181
13182  // Memory Reference
13183  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13184  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13185
13186  unsigned DstReg, SrcReg;
13187  unsigned MemOpndSlot;
13188
13189  unsigned CurOp = 0;
13190
13191  DstReg = MI->getOperand(CurOp++).getReg();
13192  MemOpndSlot = CurOp;
13193  CurOp += X86::AddrNumOperands;
13194  SrcReg = MI->getOperand(CurOp++).getReg();
13195
13196  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13197  MVT::SimpleValueType VT = *RC->vt_begin();
13198  unsigned t1 = MRI.createVirtualRegister(RC);
13199  unsigned t2 = MRI.createVirtualRegister(RC);
13200  unsigned t3 = MRI.createVirtualRegister(RC);
13201  unsigned t4 = MRI.createVirtualRegister(RC);
13202  unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13203
13204  unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13205  unsigned LOADOpc = getLoadOpcode(VT);
13206
13207  // For the atomic load-arith operator, we generate
13208  //
13209  //  thisMBB:
13210  //    t1 = LOAD [MI.addr]
13211  //  mainMBB:
13212  //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13213  //    t1 = OP MI.val, EAX
13214  //    EAX = t4
13215  //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13216  //    t3 = EAX
13217  //    JNE mainMBB
13218  //  sinkMBB:
13219  //    dst = t3
13220
13221  MachineBasicBlock *thisMBB = MBB;
13222  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13223  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13224  MF->insert(I, mainMBB);
13225  MF->insert(I, sinkMBB);
13226
13227  MachineInstrBuilder MIB;
13228
13229  // Transfer the remainder of BB and its successor edges to sinkMBB.
13230  sinkMBB->splice(sinkMBB->begin(), MBB,
13231                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13232  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13233
13234  // thisMBB:
13235  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13236  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13237    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13238    if (NewMO.isReg())
13239      NewMO.setIsKill(false);
13240    MIB.addOperand(NewMO);
13241  }
13242  for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13243    unsigned flags = (*MMOI)->getFlags();
13244    flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13245    MachineMemOperand *MMO =
13246      MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13247                               (*MMOI)->getSize(),
13248                               (*MMOI)->getBaseAlignment(),
13249                               (*MMOI)->getTBAAInfo(),
13250                               (*MMOI)->getRanges());
13251    MIB.addMemOperand(MMO);
13252  }
13253
13254  thisMBB->addSuccessor(mainMBB);
13255
13256  // mainMBB:
13257  MachineBasicBlock *origMainMBB = mainMBB;
13258
13259  // Add a PHI.
13260  MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13261                        .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13262
13263  unsigned Opc = MI->getOpcode();
13264  switch (Opc) {
13265  default:
13266    llvm_unreachable("Unhandled atomic-load-op opcode!");
13267  case X86::ATOMAND8:
13268  case X86::ATOMAND16:
13269  case X86::ATOMAND32:
13270  case X86::ATOMAND64:
13271  case X86::ATOMOR8:
13272  case X86::ATOMOR16:
13273  case X86::ATOMOR32:
13274  case X86::ATOMOR64:
13275  case X86::ATOMXOR8:
13276  case X86::ATOMXOR16:
13277  case X86::ATOMXOR32:
13278  case X86::ATOMXOR64: {
13279    unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13280    BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13281      .addReg(t4);
13282    break;
13283  }
13284  case X86::ATOMNAND8:
13285  case X86::ATOMNAND16:
13286  case X86::ATOMNAND32:
13287  case X86::ATOMNAND64: {
13288    unsigned Tmp = MRI.createVirtualRegister(RC);
13289    unsigned NOTOpc;
13290    unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13291    BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13292      .addReg(t4);
13293    BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13294    break;
13295  }
13296  case X86::ATOMMAX8:
13297  case X86::ATOMMAX16:
13298  case X86::ATOMMAX32:
13299  case X86::ATOMMAX64:
13300  case X86::ATOMMIN8:
13301  case X86::ATOMMIN16:
13302  case X86::ATOMMIN32:
13303  case X86::ATOMMIN64:
13304  case X86::ATOMUMAX8:
13305  case X86::ATOMUMAX16:
13306  case X86::ATOMUMAX32:
13307  case X86::ATOMUMAX64:
13308  case X86::ATOMUMIN8:
13309  case X86::ATOMUMIN16:
13310  case X86::ATOMUMIN32:
13311  case X86::ATOMUMIN64: {
13312    unsigned CMPOpc;
13313    unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13314
13315    BuildMI(mainMBB, DL, TII->get(CMPOpc))
13316      .addReg(SrcReg)
13317      .addReg(t4);
13318
13319    if (Subtarget->hasCMov()) {
13320      if (VT != MVT::i8) {
13321        // Native support
13322        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13323          .addReg(SrcReg)
13324          .addReg(t4);
13325      } else {
13326        // Promote i8 to i32 to use CMOV32
13327        const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13328        const TargetRegisterClass *RC32 =
13329          TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13330        unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13331        unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13332        unsigned Tmp = MRI.createVirtualRegister(RC32);
13333
13334        unsigned Undef = MRI.createVirtualRegister(RC32);
13335        BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13336
13337        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13338          .addReg(Undef)
13339          .addReg(SrcReg)
13340          .addImm(X86::sub_8bit);
13341        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13342          .addReg(Undef)
13343          .addReg(t4)
13344          .addImm(X86::sub_8bit);
13345
13346        BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13347          .addReg(SrcReg32)
13348          .addReg(AccReg32);
13349
13350        BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13351          .addReg(Tmp, 0, X86::sub_8bit);
13352      }
13353    } else {
13354      // Use pseudo select and lower them.
13355      assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13356             "Invalid atomic-load-op transformation!");
13357      unsigned SelOpc = getPseudoCMOVOpc(VT);
13358      X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13359      assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13360      MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13361              .addReg(SrcReg).addReg(t4)
13362              .addImm(CC);
13363      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13364      // Replace the original PHI node as mainMBB is changed after CMOV
13365      // lowering.
13366      BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13367        .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13368      Phi->eraseFromParent();
13369    }
13370    break;
13371  }
13372  }
13373
13374  // Copy PhyReg back from virtual register.
13375  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13376    .addReg(t4);
13377
13378  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13379  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13380    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13381    if (NewMO.isReg())
13382      NewMO.setIsKill(false);
13383    MIB.addOperand(NewMO);
13384  }
13385  MIB.addReg(t2);
13386  MIB.setMemRefs(MMOBegin, MMOEnd);
13387
13388  // Copy PhyReg back to virtual register.
13389  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13390    .addReg(PhyReg);
13391
13392  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13393
13394  mainMBB->addSuccessor(origMainMBB);
13395  mainMBB->addSuccessor(sinkMBB);
13396
13397  // sinkMBB:
13398  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13399          TII->get(TargetOpcode::COPY), DstReg)
13400    .addReg(t3);
13401
13402  MI->eraseFromParent();
13403  return sinkMBB;
13404}
13405
13406// EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13407// instructions. They will be translated into a spin-loop or compare-exchange
13408// loop from
13409//
13410//    ...
13411//    dst = atomic-fetch-op MI.addr, MI.val
13412//    ...
13413//
13414// to
13415//
13416//    ...
13417//    t1L = LOAD [MI.addr + 0]
13418//    t1H = LOAD [MI.addr + 4]
13419// loop:
13420//    t4L = phi(t1L, t3L / loop)
13421//    t4H = phi(t1H, t3H / loop)
13422//    t2L = OP MI.val.lo, t4L
13423//    t2H = OP MI.val.hi, t4H
13424//    EAX = t4L
13425//    EDX = t4H
13426//    EBX = t2L
13427//    ECX = t2H
13428//    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13429//    t3L = EAX
13430//    t3H = EDX
13431//    JNE loop
13432// sink:
13433//    dstL = t3L
13434//    dstH = t3H
13435//    ...
13436MachineBasicBlock *
13437X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13438                                           MachineBasicBlock *MBB) const {
13439  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13440  DebugLoc DL = MI->getDebugLoc();
13441
13442  MachineFunction *MF = MBB->getParent();
13443  MachineRegisterInfo &MRI = MF->getRegInfo();
13444
13445  const BasicBlock *BB = MBB->getBasicBlock();
13446  MachineFunction::iterator I = MBB;
13447  ++I;
13448
13449  assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13450         "Unexpected number of operands");
13451
13452  assert(MI->hasOneMemOperand() &&
13453         "Expected atomic-load-op32 to have one memoperand");
13454
13455  // Memory Reference
13456  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13457  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13458
13459  unsigned DstLoReg, DstHiReg;
13460  unsigned SrcLoReg, SrcHiReg;
13461  unsigned MemOpndSlot;
13462
13463  unsigned CurOp = 0;
13464
13465  DstLoReg = MI->getOperand(CurOp++).getReg();
13466  DstHiReg = MI->getOperand(CurOp++).getReg();
13467  MemOpndSlot = CurOp;
13468  CurOp += X86::AddrNumOperands;
13469  SrcLoReg = MI->getOperand(CurOp++).getReg();
13470  SrcHiReg = MI->getOperand(CurOp++).getReg();
13471
13472  const TargetRegisterClass *RC = &X86::GR32RegClass;
13473  const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13474
13475  unsigned t1L = MRI.createVirtualRegister(RC);
13476  unsigned t1H = MRI.createVirtualRegister(RC);
13477  unsigned t2L = MRI.createVirtualRegister(RC);
13478  unsigned t2H = MRI.createVirtualRegister(RC);
13479  unsigned t3L = MRI.createVirtualRegister(RC);
13480  unsigned t3H = MRI.createVirtualRegister(RC);
13481  unsigned t4L = MRI.createVirtualRegister(RC);
13482  unsigned t4H = MRI.createVirtualRegister(RC);
13483
13484  unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13485  unsigned LOADOpc = X86::MOV32rm;
13486
13487  // For the atomic load-arith operator, we generate
13488  //
13489  //  thisMBB:
13490  //    t1L = LOAD [MI.addr + 0]
13491  //    t1H = LOAD [MI.addr + 4]
13492  //  mainMBB:
13493  //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13494  //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13495  //    t2L = OP MI.val.lo, t4L
13496  //    t2H = OP MI.val.hi, t4H
13497  //    EBX = t2L
13498  //    ECX = t2H
13499  //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13500  //    t3L = EAX
13501  //    t3H = EDX
13502  //    JNE loop
13503  //  sinkMBB:
13504  //    dstL = t3L
13505  //    dstH = t3H
13506
13507  MachineBasicBlock *thisMBB = MBB;
13508  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13509  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13510  MF->insert(I, mainMBB);
13511  MF->insert(I, sinkMBB);
13512
13513  MachineInstrBuilder MIB;
13514
13515  // Transfer the remainder of BB and its successor edges to sinkMBB.
13516  sinkMBB->splice(sinkMBB->begin(), MBB,
13517                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13518  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13519
13520  // thisMBB:
13521  // Lo
13522  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13523  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13524    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13525    if (NewMO.isReg())
13526      NewMO.setIsKill(false);
13527    MIB.addOperand(NewMO);
13528  }
13529  for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13530    unsigned flags = (*MMOI)->getFlags();
13531    flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13532    MachineMemOperand *MMO =
13533      MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13534                               (*MMOI)->getSize(),
13535                               (*MMOI)->getBaseAlignment(),
13536                               (*MMOI)->getTBAAInfo(),
13537                               (*MMOI)->getRanges());
13538    MIB.addMemOperand(MMO);
13539  };
13540  MachineInstr *LowMI = MIB;
13541
13542  // Hi
13543  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13544  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13545    if (i == X86::AddrDisp) {
13546      MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13547    } else {
13548      MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13549      if (NewMO.isReg())
13550        NewMO.setIsKill(false);
13551      MIB.addOperand(NewMO);
13552    }
13553  }
13554  MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13555
13556  thisMBB->addSuccessor(mainMBB);
13557
13558  // mainMBB:
13559  MachineBasicBlock *origMainMBB = mainMBB;
13560
13561  // Add PHIs.
13562  MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13563                        .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13564  MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13565                        .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13566
13567  unsigned Opc = MI->getOpcode();
13568  switch (Opc) {
13569  default:
13570    llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13571  case X86::ATOMAND6432:
13572  case X86::ATOMOR6432:
13573  case X86::ATOMXOR6432:
13574  case X86::ATOMADD6432:
13575  case X86::ATOMSUB6432: {
13576    unsigned HiOpc;
13577    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13578    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13579      .addReg(SrcLoReg);
13580    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13581      .addReg(SrcHiReg);
13582    break;
13583  }
13584  case X86::ATOMNAND6432: {
13585    unsigned HiOpc, NOTOpc;
13586    unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13587    unsigned TmpL = MRI.createVirtualRegister(RC);
13588    unsigned TmpH = MRI.createVirtualRegister(RC);
13589    BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13590      .addReg(t4L);
13591    BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13592      .addReg(t4H);
13593    BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13594    BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13595    break;
13596  }
13597  case X86::ATOMMAX6432:
13598  case X86::ATOMMIN6432:
13599  case X86::ATOMUMAX6432:
13600  case X86::ATOMUMIN6432: {
13601    unsigned HiOpc;
13602    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13603    unsigned cL = MRI.createVirtualRegister(RC8);
13604    unsigned cH = MRI.createVirtualRegister(RC8);
13605    unsigned cL32 = MRI.createVirtualRegister(RC);
13606    unsigned cH32 = MRI.createVirtualRegister(RC);
13607    unsigned cc = MRI.createVirtualRegister(RC);
13608    // cl := cmp src_lo, lo
13609    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13610      .addReg(SrcLoReg).addReg(t4L);
13611    BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13612    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13613    // ch := cmp src_hi, hi
13614    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13615      .addReg(SrcHiReg).addReg(t4H);
13616    BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13617    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13618    // cc := if (src_hi == hi) ? cl : ch;
13619    if (Subtarget->hasCMov()) {
13620      BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13621        .addReg(cH32).addReg(cL32);
13622    } else {
13623      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13624              .addReg(cH32).addReg(cL32)
13625              .addImm(X86::COND_E);
13626      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13627    }
13628    BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13629    if (Subtarget->hasCMov()) {
13630      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13631        .addReg(SrcLoReg).addReg(t4L);
13632      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13633        .addReg(SrcHiReg).addReg(t4H);
13634    } else {
13635      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13636              .addReg(SrcLoReg).addReg(t4L)
13637              .addImm(X86::COND_NE);
13638      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13639      // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13640      // 2nd CMOV lowering.
13641      mainMBB->addLiveIn(X86::EFLAGS);
13642      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13643              .addReg(SrcHiReg).addReg(t4H)
13644              .addImm(X86::COND_NE);
13645      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13646      // Replace the original PHI node as mainMBB is changed after CMOV
13647      // lowering.
13648      BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13649        .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13650      BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13651        .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13652      PhiL->eraseFromParent();
13653      PhiH->eraseFromParent();
13654    }
13655    break;
13656  }
13657  case X86::ATOMSWAP6432: {
13658    unsigned HiOpc;
13659    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13660    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13661    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13662    break;
13663  }
13664  }
13665
13666  // Copy EDX:EAX back from HiReg:LoReg
13667  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13668  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13669  // Copy ECX:EBX from t1H:t1L
13670  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13671  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13672
13673  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13674  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13675    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13676    if (NewMO.isReg())
13677      NewMO.setIsKill(false);
13678    MIB.addOperand(NewMO);
13679  }
13680  MIB.setMemRefs(MMOBegin, MMOEnd);
13681
13682  // Copy EDX:EAX back to t3H:t3L
13683  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13684  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13685
13686  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13687
13688  mainMBB->addSuccessor(origMainMBB);
13689  mainMBB->addSuccessor(sinkMBB);
13690
13691  // sinkMBB:
13692  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13693          TII->get(TargetOpcode::COPY), DstLoReg)
13694    .addReg(t3L);
13695  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13696          TII->get(TargetOpcode::COPY), DstHiReg)
13697    .addReg(t3H);
13698
13699  MI->eraseFromParent();
13700  return sinkMBB;
13701}
13702
13703// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13704// or XMM0_V32I8 in AVX all of this code can be replaced with that
13705// in the .td file.
13706static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13707                                       const TargetInstrInfo *TII) {
13708  unsigned Opc;
13709  switch (MI->getOpcode()) {
13710  default: llvm_unreachable("illegal opcode!");
13711  case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13712  case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13713  case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13714  case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13715  case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13716  case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13717  case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13718  case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13719  }
13720
13721  DebugLoc dl = MI->getDebugLoc();
13722  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13723
13724  unsigned NumArgs = MI->getNumOperands();
13725  for (unsigned i = 1; i < NumArgs; ++i) {
13726    MachineOperand &Op = MI->getOperand(i);
13727    if (!(Op.isReg() && Op.isImplicit()))
13728      MIB.addOperand(Op);
13729  }
13730  if (MI->hasOneMemOperand())
13731    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13732
13733  BuildMI(*BB, MI, dl,
13734    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13735    .addReg(X86::XMM0);
13736
13737  MI->eraseFromParent();
13738  return BB;
13739}
13740
13741// FIXME: Custom handling because TableGen doesn't support multiple implicit
13742// defs in an instruction pattern
13743static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13744                                       const TargetInstrInfo *TII) {
13745  unsigned Opc;
13746  switch (MI->getOpcode()) {
13747  default: llvm_unreachable("illegal opcode!");
13748  case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13749  case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13750  case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13751  case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13752  case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13753  case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13754  case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13755  case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13756  }
13757
13758  DebugLoc dl = MI->getDebugLoc();
13759  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13760
13761  unsigned NumArgs = MI->getNumOperands(); // remove the results
13762  for (unsigned i = 1; i < NumArgs; ++i) {
13763    MachineOperand &Op = MI->getOperand(i);
13764    if (!(Op.isReg() && Op.isImplicit()))
13765      MIB.addOperand(Op);
13766  }
13767  if (MI->hasOneMemOperand())
13768    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13769
13770  BuildMI(*BB, MI, dl,
13771    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13772    .addReg(X86::ECX);
13773
13774  MI->eraseFromParent();
13775  return BB;
13776}
13777
13778static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13779                                       const TargetInstrInfo *TII,
13780                                       const X86Subtarget* Subtarget) {
13781  DebugLoc dl = MI->getDebugLoc();
13782
13783  // Address into RAX/EAX, other two args into ECX, EDX.
13784  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13785  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13786  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13787  for (int i = 0; i < X86::AddrNumOperands; ++i)
13788    MIB.addOperand(MI->getOperand(i));
13789
13790  unsigned ValOps = X86::AddrNumOperands;
13791  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13792    .addReg(MI->getOperand(ValOps).getReg());
13793  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13794    .addReg(MI->getOperand(ValOps+1).getReg());
13795
13796  // The instruction doesn't actually take any operands though.
13797  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13798
13799  MI->eraseFromParent(); // The pseudo is gone now.
13800  return BB;
13801}
13802
13803MachineBasicBlock *
13804X86TargetLowering::EmitVAARG64WithCustomInserter(
13805                   MachineInstr *MI,
13806                   MachineBasicBlock *MBB) const {
13807  // Emit va_arg instruction on X86-64.
13808
13809  // Operands to this pseudo-instruction:
13810  // 0  ) Output        : destination address (reg)
13811  // 1-5) Input         : va_list address (addr, i64mem)
13812  // 6  ) ArgSize       : Size (in bytes) of vararg type
13813  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13814  // 8  ) Align         : Alignment of type
13815  // 9  ) EFLAGS (implicit-def)
13816
13817  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13818  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13819
13820  unsigned DestReg = MI->getOperand(0).getReg();
13821  MachineOperand &Base = MI->getOperand(1);
13822  MachineOperand &Scale = MI->getOperand(2);
13823  MachineOperand &Index = MI->getOperand(3);
13824  MachineOperand &Disp = MI->getOperand(4);
13825  MachineOperand &Segment = MI->getOperand(5);
13826  unsigned ArgSize = MI->getOperand(6).getImm();
13827  unsigned ArgMode = MI->getOperand(7).getImm();
13828  unsigned Align = MI->getOperand(8).getImm();
13829
13830  // Memory Reference
13831  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13832  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13833  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13834
13835  // Machine Information
13836  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13837  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13838  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13839  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13840  DebugLoc DL = MI->getDebugLoc();
13841
13842  // struct va_list {
13843  //   i32   gp_offset
13844  //   i32   fp_offset
13845  //   i64   overflow_area (address)
13846  //   i64   reg_save_area (address)
13847  // }
13848  // sizeof(va_list) = 24
13849  // alignment(va_list) = 8
13850
13851  unsigned TotalNumIntRegs = 6;
13852  unsigned TotalNumXMMRegs = 8;
13853  bool UseGPOffset = (ArgMode == 1);
13854  bool UseFPOffset = (ArgMode == 2);
13855  unsigned MaxOffset = TotalNumIntRegs * 8 +
13856                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13857
13858  /* Align ArgSize to a multiple of 8 */
13859  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13860  bool NeedsAlign = (Align > 8);
13861
13862  MachineBasicBlock *thisMBB = MBB;
13863  MachineBasicBlock *overflowMBB;
13864  MachineBasicBlock *offsetMBB;
13865  MachineBasicBlock *endMBB;
13866
13867  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13868  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13869  unsigned OffsetReg = 0;
13870
13871  if (!UseGPOffset && !UseFPOffset) {
13872    // If we only pull from the overflow region, we don't create a branch.
13873    // We don't need to alter control flow.
13874    OffsetDestReg = 0; // unused
13875    OverflowDestReg = DestReg;
13876
13877    offsetMBB = NULL;
13878    overflowMBB = thisMBB;
13879    endMBB = thisMBB;
13880  } else {
13881    // First emit code to check if gp_offset (or fp_offset) is below the bound.
13882    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13883    // If not, pull from overflow_area. (branch to overflowMBB)
13884    //
13885    //       thisMBB
13886    //         |     .
13887    //         |        .
13888    //     offsetMBB   overflowMBB
13889    //         |        .
13890    //         |     .
13891    //        endMBB
13892
13893    // Registers for the PHI in endMBB
13894    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13895    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13896
13897    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13898    MachineFunction *MF = MBB->getParent();
13899    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13900    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13901    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13902
13903    MachineFunction::iterator MBBIter = MBB;
13904    ++MBBIter;
13905
13906    // Insert the new basic blocks
13907    MF->insert(MBBIter, offsetMBB);
13908    MF->insert(MBBIter, overflowMBB);
13909    MF->insert(MBBIter, endMBB);
13910
13911    // Transfer the remainder of MBB and its successor edges to endMBB.
13912    endMBB->splice(endMBB->begin(), thisMBB,
13913                    llvm::next(MachineBasicBlock::iterator(MI)),
13914                    thisMBB->end());
13915    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13916
13917    // Make offsetMBB and overflowMBB successors of thisMBB
13918    thisMBB->addSuccessor(offsetMBB);
13919    thisMBB->addSuccessor(overflowMBB);
13920
13921    // endMBB is a successor of both offsetMBB and overflowMBB
13922    offsetMBB->addSuccessor(endMBB);
13923    overflowMBB->addSuccessor(endMBB);
13924
13925    // Load the offset value into a register
13926    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13927    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13928      .addOperand(Base)
13929      .addOperand(Scale)
13930      .addOperand(Index)
13931      .addDisp(Disp, UseFPOffset ? 4 : 0)
13932      .addOperand(Segment)
13933      .setMemRefs(MMOBegin, MMOEnd);
13934
13935    // Check if there is enough room left to pull this argument.
13936    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13937      .addReg(OffsetReg)
13938      .addImm(MaxOffset + 8 - ArgSizeA8);
13939
13940    // Branch to "overflowMBB" if offset >= max
13941    // Fall through to "offsetMBB" otherwise
13942    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13943      .addMBB(overflowMBB);
13944  }
13945
13946  // In offsetMBB, emit code to use the reg_save_area.
13947  if (offsetMBB) {
13948    assert(OffsetReg != 0);
13949
13950    // Read the reg_save_area address.
13951    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13952    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13953      .addOperand(Base)
13954      .addOperand(Scale)
13955      .addOperand(Index)
13956      .addDisp(Disp, 16)
13957      .addOperand(Segment)
13958      .setMemRefs(MMOBegin, MMOEnd);
13959
13960    // Zero-extend the offset
13961    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13962      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13963        .addImm(0)
13964        .addReg(OffsetReg)
13965        .addImm(X86::sub_32bit);
13966
13967    // Add the offset to the reg_save_area to get the final address.
13968    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13969      .addReg(OffsetReg64)
13970      .addReg(RegSaveReg);
13971
13972    // Compute the offset for the next argument
13973    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13974    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13975      .addReg(OffsetReg)
13976      .addImm(UseFPOffset ? 16 : 8);
13977
13978    // Store it back into the va_list.
13979    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13980      .addOperand(Base)
13981      .addOperand(Scale)
13982      .addOperand(Index)
13983      .addDisp(Disp, UseFPOffset ? 4 : 0)
13984      .addOperand(Segment)
13985      .addReg(NextOffsetReg)
13986      .setMemRefs(MMOBegin, MMOEnd);
13987
13988    // Jump to endMBB
13989    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13990      .addMBB(endMBB);
13991  }
13992
13993  //
13994  // Emit code to use overflow area
13995  //
13996
13997  // Load the overflow_area address into a register.
13998  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13999  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14000    .addOperand(Base)
14001    .addOperand(Scale)
14002    .addOperand(Index)
14003    .addDisp(Disp, 8)
14004    .addOperand(Segment)
14005    .setMemRefs(MMOBegin, MMOEnd);
14006
14007  // If we need to align it, do so. Otherwise, just copy the address
14008  // to OverflowDestReg.
14009  if (NeedsAlign) {
14010    // Align the overflow address
14011    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14012    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14013
14014    // aligned_addr = (addr + (align-1)) & ~(align-1)
14015    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14016      .addReg(OverflowAddrReg)
14017      .addImm(Align-1);
14018
14019    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14020      .addReg(TmpReg)
14021      .addImm(~(uint64_t)(Align-1));
14022  } else {
14023    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14024      .addReg(OverflowAddrReg);
14025  }
14026
14027  // Compute the next overflow address after this argument.
14028  // (the overflow address should be kept 8-byte aligned)
14029  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14030  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14031    .addReg(OverflowDestReg)
14032    .addImm(ArgSizeA8);
14033
14034  // Store the new overflow address.
14035  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14036    .addOperand(Base)
14037    .addOperand(Scale)
14038    .addOperand(Index)
14039    .addDisp(Disp, 8)
14040    .addOperand(Segment)
14041    .addReg(NextAddrReg)
14042    .setMemRefs(MMOBegin, MMOEnd);
14043
14044  // If we branched, emit the PHI to the front of endMBB.
14045  if (offsetMBB) {
14046    BuildMI(*endMBB, endMBB->begin(), DL,
14047            TII->get(X86::PHI), DestReg)
14048      .addReg(OffsetDestReg).addMBB(offsetMBB)
14049      .addReg(OverflowDestReg).addMBB(overflowMBB);
14050  }
14051
14052  // Erase the pseudo instruction
14053  MI->eraseFromParent();
14054
14055  return endMBB;
14056}
14057
14058MachineBasicBlock *
14059X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14060                                                 MachineInstr *MI,
14061                                                 MachineBasicBlock *MBB) const {
14062  // Emit code to save XMM registers to the stack. The ABI says that the
14063  // number of registers to save is given in %al, so it's theoretically
14064  // possible to do an indirect jump trick to avoid saving all of them,
14065  // however this code takes a simpler approach and just executes all
14066  // of the stores if %al is non-zero. It's less code, and it's probably
14067  // easier on the hardware branch predictor, and stores aren't all that
14068  // expensive anyway.
14069
14070  // Create the new basic blocks. One block contains all the XMM stores,
14071  // and one block is the final destination regardless of whether any
14072  // stores were performed.
14073  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14074  MachineFunction *F = MBB->getParent();
14075  MachineFunction::iterator MBBIter = MBB;
14076  ++MBBIter;
14077  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14078  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14079  F->insert(MBBIter, XMMSaveMBB);
14080  F->insert(MBBIter, EndMBB);
14081
14082  // Transfer the remainder of MBB and its successor edges to EndMBB.
14083  EndMBB->splice(EndMBB->begin(), MBB,
14084                 llvm::next(MachineBasicBlock::iterator(MI)),
14085                 MBB->end());
14086  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14087
14088  // The original block will now fall through to the XMM save block.
14089  MBB->addSuccessor(XMMSaveMBB);
14090  // The XMMSaveMBB will fall through to the end block.
14091  XMMSaveMBB->addSuccessor(EndMBB);
14092
14093  // Now add the instructions.
14094  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14095  DebugLoc DL = MI->getDebugLoc();
14096
14097  unsigned CountReg = MI->getOperand(0).getReg();
14098  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14099  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14100
14101  if (!Subtarget->isTargetWin64()) {
14102    // If %al is 0, branch around the XMM save block.
14103    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14104    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14105    MBB->addSuccessor(EndMBB);
14106  }
14107
14108  unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14109  // In the XMM save block, save all the XMM argument registers.
14110  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14111    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14112    MachineMemOperand *MMO =
14113      F->getMachineMemOperand(
14114          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14115        MachineMemOperand::MOStore,
14116        /*Size=*/16, /*Align=*/16);
14117    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14118      .addFrameIndex(RegSaveFrameIndex)
14119      .addImm(/*Scale=*/1)
14120      .addReg(/*IndexReg=*/0)
14121      .addImm(/*Disp=*/Offset)
14122      .addReg(/*Segment=*/0)
14123      .addReg(MI->getOperand(i).getReg())
14124      .addMemOperand(MMO);
14125  }
14126
14127  MI->eraseFromParent();   // The pseudo instruction is gone now.
14128
14129  return EndMBB;
14130}
14131
14132// The EFLAGS operand of SelectItr might be missing a kill marker
14133// because there were multiple uses of EFLAGS, and ISel didn't know
14134// which to mark. Figure out whether SelectItr should have had a
14135// kill marker, and set it if it should. Returns the correct kill
14136// marker value.
14137static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14138                                     MachineBasicBlock* BB,
14139                                     const TargetRegisterInfo* TRI) {
14140  // Scan forward through BB for a use/def of EFLAGS.
14141  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14142  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14143    const MachineInstr& mi = *miI;
14144    if (mi.readsRegister(X86::EFLAGS))
14145      return false;
14146    if (mi.definesRegister(X86::EFLAGS))
14147      break; // Should have kill-flag - update below.
14148  }
14149
14150  // If we hit the end of the block, check whether EFLAGS is live into a
14151  // successor.
14152  if (miI == BB->end()) {
14153    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14154                                          sEnd = BB->succ_end();
14155         sItr != sEnd; ++sItr) {
14156      MachineBasicBlock* succ = *sItr;
14157      if (succ->isLiveIn(X86::EFLAGS))
14158        return false;
14159    }
14160  }
14161
14162  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14163  // out. SelectMI should have a kill flag on EFLAGS.
14164  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14165  return true;
14166}
14167
14168MachineBasicBlock *
14169X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14170                                     MachineBasicBlock *BB) const {
14171  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14172  DebugLoc DL = MI->getDebugLoc();
14173
14174  // To "insert" a SELECT_CC instruction, we actually have to insert the
14175  // diamond control-flow pattern.  The incoming instruction knows the
14176  // destination vreg to set, the condition code register to branch on, the
14177  // true/false values to select between, and a branch opcode to use.
14178  const BasicBlock *LLVM_BB = BB->getBasicBlock();
14179  MachineFunction::iterator It = BB;
14180  ++It;
14181
14182  //  thisMBB:
14183  //  ...
14184  //   TrueVal = ...
14185  //   cmpTY ccX, r1, r2
14186  //   bCC copy1MBB
14187  //   fallthrough --> copy0MBB
14188  MachineBasicBlock *thisMBB = BB;
14189  MachineFunction *F = BB->getParent();
14190  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14191  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14192  F->insert(It, copy0MBB);
14193  F->insert(It, sinkMBB);
14194
14195  // If the EFLAGS register isn't dead in the terminator, then claim that it's
14196  // live into the sink and copy blocks.
14197  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14198  if (!MI->killsRegister(X86::EFLAGS) &&
14199      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14200    copy0MBB->addLiveIn(X86::EFLAGS);
14201    sinkMBB->addLiveIn(X86::EFLAGS);
14202  }
14203
14204  // Transfer the remainder of BB and its successor edges to sinkMBB.
14205  sinkMBB->splice(sinkMBB->begin(), BB,
14206                  llvm::next(MachineBasicBlock::iterator(MI)),
14207                  BB->end());
14208  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14209
14210  // Add the true and fallthrough blocks as its successors.
14211  BB->addSuccessor(copy0MBB);
14212  BB->addSuccessor(sinkMBB);
14213
14214  // Create the conditional branch instruction.
14215  unsigned Opc =
14216    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14217  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14218
14219  //  copy0MBB:
14220  //   %FalseValue = ...
14221  //   # fallthrough to sinkMBB
14222  copy0MBB->addSuccessor(sinkMBB);
14223
14224  //  sinkMBB:
14225  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14226  //  ...
14227  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14228          TII->get(X86::PHI), MI->getOperand(0).getReg())
14229    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14230    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14231
14232  MI->eraseFromParent();   // The pseudo instruction is gone now.
14233  return sinkMBB;
14234}
14235
14236MachineBasicBlock *
14237X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14238                                        bool Is64Bit) const {
14239  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14240  DebugLoc DL = MI->getDebugLoc();
14241  MachineFunction *MF = BB->getParent();
14242  const BasicBlock *LLVM_BB = BB->getBasicBlock();
14243
14244  assert(getTargetMachine().Options.EnableSegmentedStacks);
14245
14246  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14247  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14248
14249  // BB:
14250  //  ... [Till the alloca]
14251  // If stacklet is not large enough, jump to mallocMBB
14252  //
14253  // bumpMBB:
14254  //  Allocate by subtracting from RSP
14255  //  Jump to continueMBB
14256  //
14257  // mallocMBB:
14258  //  Allocate by call to runtime
14259  //
14260  // continueMBB:
14261  //  ...
14262  //  [rest of original BB]
14263  //
14264
14265  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14266  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14267  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14268
14269  MachineRegisterInfo &MRI = MF->getRegInfo();
14270  const TargetRegisterClass *AddrRegClass =
14271    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14272
14273  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14274    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14275    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14276    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14277    sizeVReg = MI->getOperand(1).getReg(),
14278    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14279
14280  MachineFunction::iterator MBBIter = BB;
14281  ++MBBIter;
14282
14283  MF->insert(MBBIter, bumpMBB);
14284  MF->insert(MBBIter, mallocMBB);
14285  MF->insert(MBBIter, continueMBB);
14286
14287  continueMBB->splice(continueMBB->begin(), BB, llvm::next
14288                      (MachineBasicBlock::iterator(MI)), BB->end());
14289  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14290
14291  // Add code to the main basic block to check if the stack limit has been hit,
14292  // and if so, jump to mallocMBB otherwise to bumpMBB.
14293  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14294  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14295    .addReg(tmpSPVReg).addReg(sizeVReg);
14296  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14297    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14298    .addReg(SPLimitVReg);
14299  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14300
14301  // bumpMBB simply decreases the stack pointer, since we know the current
14302  // stacklet has enough space.
14303  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14304    .addReg(SPLimitVReg);
14305  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14306    .addReg(SPLimitVReg);
14307  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14308
14309  // Calls into a routine in libgcc to allocate more space from the heap.
14310  const uint32_t *RegMask =
14311    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14312  if (Is64Bit) {
14313    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14314      .addReg(sizeVReg);
14315    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14316      .addExternalSymbol("__morestack_allocate_stack_space")
14317      .addRegMask(RegMask)
14318      .addReg(X86::RDI, RegState::Implicit)
14319      .addReg(X86::RAX, RegState::ImplicitDefine);
14320  } else {
14321    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14322      .addImm(12);
14323    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14324    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14325      .addExternalSymbol("__morestack_allocate_stack_space")
14326      .addRegMask(RegMask)
14327      .addReg(X86::EAX, RegState::ImplicitDefine);
14328  }
14329
14330  if (!Is64Bit)
14331    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14332      .addImm(16);
14333
14334  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14335    .addReg(Is64Bit ? X86::RAX : X86::EAX);
14336  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14337
14338  // Set up the CFG correctly.
14339  BB->addSuccessor(bumpMBB);
14340  BB->addSuccessor(mallocMBB);
14341  mallocMBB->addSuccessor(continueMBB);
14342  bumpMBB->addSuccessor(continueMBB);
14343
14344  // Take care of the PHI nodes.
14345  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14346          MI->getOperand(0).getReg())
14347    .addReg(mallocPtrVReg).addMBB(mallocMBB)
14348    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14349
14350  // Delete the original pseudo instruction.
14351  MI->eraseFromParent();
14352
14353  // And we're done.
14354  return continueMBB;
14355}
14356
14357MachineBasicBlock *
14358X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14359                                          MachineBasicBlock *BB) const {
14360  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14361  DebugLoc DL = MI->getDebugLoc();
14362
14363  assert(!Subtarget->isTargetEnvMacho());
14364
14365  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14366  // non-trivial part is impdef of ESP.
14367
14368  if (Subtarget->isTargetWin64()) {
14369    if (Subtarget->isTargetCygMing()) {
14370      // ___chkstk(Mingw64):
14371      // Clobbers R10, R11, RAX and EFLAGS.
14372      // Updates RSP.
14373      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14374        .addExternalSymbol("___chkstk")
14375        .addReg(X86::RAX, RegState::Implicit)
14376        .addReg(X86::RSP, RegState::Implicit)
14377        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14378        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14379        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14380    } else {
14381      // __chkstk(MSVCRT): does not update stack pointer.
14382      // Clobbers R10, R11 and EFLAGS.
14383      // FIXME: RAX(allocated size) might be reused and not killed.
14384      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14385        .addExternalSymbol("__chkstk")
14386        .addReg(X86::RAX, RegState::Implicit)
14387        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14388      // RAX has the offset to subtracted from RSP.
14389      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14390        .addReg(X86::RSP)
14391        .addReg(X86::RAX);
14392    }
14393  } else {
14394    const char *StackProbeSymbol =
14395      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14396
14397    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14398      .addExternalSymbol(StackProbeSymbol)
14399      .addReg(X86::EAX, RegState::Implicit)
14400      .addReg(X86::ESP, RegState::Implicit)
14401      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14402      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14403      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14404  }
14405
14406  MI->eraseFromParent();   // The pseudo instruction is gone now.
14407  return BB;
14408}
14409
14410MachineBasicBlock *
14411X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14412                                      MachineBasicBlock *BB) const {
14413  // This is pretty easy.  We're taking the value that we received from
14414  // our load from the relocation, sticking it in either RDI (x86-64)
14415  // or EAX and doing an indirect call.  The return value will then
14416  // be in the normal return register.
14417  const X86InstrInfo *TII
14418    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14419  DebugLoc DL = MI->getDebugLoc();
14420  MachineFunction *F = BB->getParent();
14421
14422  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14423  assert(MI->getOperand(3).isGlobal() && "This should be a global");
14424
14425  // Get a register mask for the lowered call.
14426  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14427  // proper register mask.
14428  const uint32_t *RegMask =
14429    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14430  if (Subtarget->is64Bit()) {
14431    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14432                                      TII->get(X86::MOV64rm), X86::RDI)
14433    .addReg(X86::RIP)
14434    .addImm(0).addReg(0)
14435    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14436                      MI->getOperand(3).getTargetFlags())
14437    .addReg(0);
14438    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14439    addDirectMem(MIB, X86::RDI);
14440    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14441  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14442    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14443                                      TII->get(X86::MOV32rm), X86::EAX)
14444    .addReg(0)
14445    .addImm(0).addReg(0)
14446    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14447                      MI->getOperand(3).getTargetFlags())
14448    .addReg(0);
14449    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14450    addDirectMem(MIB, X86::EAX);
14451    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14452  } else {
14453    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14454                                      TII->get(X86::MOV32rm), X86::EAX)
14455    .addReg(TII->getGlobalBaseReg(F))
14456    .addImm(0).addReg(0)
14457    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14458                      MI->getOperand(3).getTargetFlags())
14459    .addReg(0);
14460    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14461    addDirectMem(MIB, X86::EAX);
14462    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14463  }
14464
14465  MI->eraseFromParent(); // The pseudo instruction is gone now.
14466  return BB;
14467}
14468
14469MachineBasicBlock *
14470X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14471                                    MachineBasicBlock *MBB) const {
14472  DebugLoc DL = MI->getDebugLoc();
14473  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14474
14475  MachineFunction *MF = MBB->getParent();
14476  MachineRegisterInfo &MRI = MF->getRegInfo();
14477
14478  const BasicBlock *BB = MBB->getBasicBlock();
14479  MachineFunction::iterator I = MBB;
14480  ++I;
14481
14482  // Memory Reference
14483  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14484  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14485
14486  unsigned DstReg;
14487  unsigned MemOpndSlot = 0;
14488
14489  unsigned CurOp = 0;
14490
14491  DstReg = MI->getOperand(CurOp++).getReg();
14492  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14493  assert(RC->hasType(MVT::i32) && "Invalid destination!");
14494  unsigned mainDstReg = MRI.createVirtualRegister(RC);
14495  unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14496
14497  MemOpndSlot = CurOp;
14498
14499  MVT PVT = getPointerTy();
14500  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14501         "Invalid Pointer Size!");
14502
14503  // For v = setjmp(buf), we generate
14504  //
14505  // thisMBB:
14506  //  buf[LabelOffset] = restoreMBB
14507  //  SjLjSetup restoreMBB
14508  //
14509  // mainMBB:
14510  //  v_main = 0
14511  //
14512  // sinkMBB:
14513  //  v = phi(main, restore)
14514  //
14515  // restoreMBB:
14516  //  v_restore = 1
14517
14518  MachineBasicBlock *thisMBB = MBB;
14519  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14520  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14521  MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14522  MF->insert(I, mainMBB);
14523  MF->insert(I, sinkMBB);
14524  MF->push_back(restoreMBB);
14525
14526  MachineInstrBuilder MIB;
14527
14528  // Transfer the remainder of BB and its successor edges to sinkMBB.
14529  sinkMBB->splice(sinkMBB->begin(), MBB,
14530                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14531  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14532
14533  // thisMBB:
14534  unsigned PtrStoreOpc = 0;
14535  unsigned LabelReg = 0;
14536  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14537  Reloc::Model RM = getTargetMachine().getRelocationModel();
14538  bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14539                     (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14540
14541  // Prepare IP either in reg or imm.
14542  if (!UseImmLabel) {
14543    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14544    const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14545    LabelReg = MRI.createVirtualRegister(PtrRC);
14546    if (Subtarget->is64Bit()) {
14547      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14548              .addReg(X86::RIP)
14549              .addImm(0)
14550              .addReg(0)
14551              .addMBB(restoreMBB)
14552              .addReg(0);
14553    } else {
14554      const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14555      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14556              .addReg(XII->getGlobalBaseReg(MF))
14557              .addImm(0)
14558              .addReg(0)
14559              .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14560              .addReg(0);
14561    }
14562  } else
14563    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14564  // Store IP
14565  MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14566  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14567    if (i == X86::AddrDisp)
14568      MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14569    else
14570      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14571  }
14572  if (!UseImmLabel)
14573    MIB.addReg(LabelReg);
14574  else
14575    MIB.addMBB(restoreMBB);
14576  MIB.setMemRefs(MMOBegin, MMOEnd);
14577  // Setup
14578  MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14579          .addMBB(restoreMBB);
14580  MIB.addRegMask(RegInfo->getNoPreservedMask());
14581  thisMBB->addSuccessor(mainMBB);
14582  thisMBB->addSuccessor(restoreMBB);
14583
14584  // mainMBB:
14585  //  EAX = 0
14586  BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14587  mainMBB->addSuccessor(sinkMBB);
14588
14589  // sinkMBB:
14590  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14591          TII->get(X86::PHI), DstReg)
14592    .addReg(mainDstReg).addMBB(mainMBB)
14593    .addReg(restoreDstReg).addMBB(restoreMBB);
14594
14595  // restoreMBB:
14596  BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14597  BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14598  restoreMBB->addSuccessor(sinkMBB);
14599
14600  MI->eraseFromParent();
14601  return sinkMBB;
14602}
14603
14604MachineBasicBlock *
14605X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14606                                     MachineBasicBlock *MBB) const {
14607  DebugLoc DL = MI->getDebugLoc();
14608  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14609
14610  MachineFunction *MF = MBB->getParent();
14611  MachineRegisterInfo &MRI = MF->getRegInfo();
14612
14613  // Memory Reference
14614  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14615  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14616
14617  MVT PVT = getPointerTy();
14618  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14619         "Invalid Pointer Size!");
14620
14621  const TargetRegisterClass *RC =
14622    (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14623  unsigned Tmp = MRI.createVirtualRegister(RC);
14624  // Since FP is only updated here but NOT referenced, it's treated as GPR.
14625  unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14626  unsigned SP = RegInfo->getStackRegister();
14627
14628  MachineInstrBuilder MIB;
14629
14630  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14631  const int64_t SPOffset = 2 * PVT.getStoreSize();
14632
14633  unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14634  unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14635
14636  // Reload FP
14637  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14638  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14639    MIB.addOperand(MI->getOperand(i));
14640  MIB.setMemRefs(MMOBegin, MMOEnd);
14641  // Reload IP
14642  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14643  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14644    if (i == X86::AddrDisp)
14645      MIB.addDisp(MI->getOperand(i), LabelOffset);
14646    else
14647      MIB.addOperand(MI->getOperand(i));
14648  }
14649  MIB.setMemRefs(MMOBegin, MMOEnd);
14650  // Reload SP
14651  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14652  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14653    if (i == X86::AddrDisp)
14654      MIB.addDisp(MI->getOperand(i), SPOffset);
14655    else
14656      MIB.addOperand(MI->getOperand(i));
14657  }
14658  MIB.setMemRefs(MMOBegin, MMOEnd);
14659  // Jump
14660  BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14661
14662  MI->eraseFromParent();
14663  return MBB;
14664}
14665
14666MachineBasicBlock *
14667X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14668                                               MachineBasicBlock *BB) const {
14669  switch (MI->getOpcode()) {
14670  default: llvm_unreachable("Unexpected instr type to insert");
14671  case X86::TAILJMPd64:
14672  case X86::TAILJMPr64:
14673  case X86::TAILJMPm64:
14674    llvm_unreachable("TAILJMP64 would not be touched here.");
14675  case X86::TCRETURNdi64:
14676  case X86::TCRETURNri64:
14677  case X86::TCRETURNmi64:
14678    return BB;
14679  case X86::WIN_ALLOCA:
14680    return EmitLoweredWinAlloca(MI, BB);
14681  case X86::SEG_ALLOCA_32:
14682    return EmitLoweredSegAlloca(MI, BB, false);
14683  case X86::SEG_ALLOCA_64:
14684    return EmitLoweredSegAlloca(MI, BB, true);
14685  case X86::TLSCall_32:
14686  case X86::TLSCall_64:
14687    return EmitLoweredTLSCall(MI, BB);
14688  case X86::CMOV_GR8:
14689  case X86::CMOV_FR32:
14690  case X86::CMOV_FR64:
14691  case X86::CMOV_V4F32:
14692  case X86::CMOV_V2F64:
14693  case X86::CMOV_V2I64:
14694  case X86::CMOV_V8F32:
14695  case X86::CMOV_V4F64:
14696  case X86::CMOV_V4I64:
14697  case X86::CMOV_GR16:
14698  case X86::CMOV_GR32:
14699  case X86::CMOV_RFP32:
14700  case X86::CMOV_RFP64:
14701  case X86::CMOV_RFP80:
14702    return EmitLoweredSelect(MI, BB);
14703
14704  case X86::FP32_TO_INT16_IN_MEM:
14705  case X86::FP32_TO_INT32_IN_MEM:
14706  case X86::FP32_TO_INT64_IN_MEM:
14707  case X86::FP64_TO_INT16_IN_MEM:
14708  case X86::FP64_TO_INT32_IN_MEM:
14709  case X86::FP64_TO_INT64_IN_MEM:
14710  case X86::FP80_TO_INT16_IN_MEM:
14711  case X86::FP80_TO_INT32_IN_MEM:
14712  case X86::FP80_TO_INT64_IN_MEM: {
14713    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14714    DebugLoc DL = MI->getDebugLoc();
14715
14716    // Change the floating point control register to use "round towards zero"
14717    // mode when truncating to an integer value.
14718    MachineFunction *F = BB->getParent();
14719    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14720    addFrameReference(BuildMI(*BB, MI, DL,
14721                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
14722
14723    // Load the old value of the high byte of the control word...
14724    unsigned OldCW =
14725      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14726    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14727                      CWFrameIdx);
14728
14729    // Set the high part to be round to zero...
14730    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14731      .addImm(0xC7F);
14732
14733    // Reload the modified control word now...
14734    addFrameReference(BuildMI(*BB, MI, DL,
14735                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14736
14737    // Restore the memory image of control word to original value
14738    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14739      .addReg(OldCW);
14740
14741    // Get the X86 opcode to use.
14742    unsigned Opc;
14743    switch (MI->getOpcode()) {
14744    default: llvm_unreachable("illegal opcode!");
14745    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14746    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14747    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14748    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14749    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14750    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14751    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14752    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14753    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14754    }
14755
14756    X86AddressMode AM;
14757    MachineOperand &Op = MI->getOperand(0);
14758    if (Op.isReg()) {
14759      AM.BaseType = X86AddressMode::RegBase;
14760      AM.Base.Reg = Op.getReg();
14761    } else {
14762      AM.BaseType = X86AddressMode::FrameIndexBase;
14763      AM.Base.FrameIndex = Op.getIndex();
14764    }
14765    Op = MI->getOperand(1);
14766    if (Op.isImm())
14767      AM.Scale = Op.getImm();
14768    Op = MI->getOperand(2);
14769    if (Op.isImm())
14770      AM.IndexReg = Op.getImm();
14771    Op = MI->getOperand(3);
14772    if (Op.isGlobal()) {
14773      AM.GV = Op.getGlobal();
14774    } else {
14775      AM.Disp = Op.getImm();
14776    }
14777    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14778                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14779
14780    // Reload the original control word now.
14781    addFrameReference(BuildMI(*BB, MI, DL,
14782                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14783
14784    MI->eraseFromParent();   // The pseudo instruction is gone now.
14785    return BB;
14786  }
14787    // String/text processing lowering.
14788  case X86::PCMPISTRM128REG:
14789  case X86::VPCMPISTRM128REG:
14790  case X86::PCMPISTRM128MEM:
14791  case X86::VPCMPISTRM128MEM:
14792  case X86::PCMPESTRM128REG:
14793  case X86::VPCMPESTRM128REG:
14794  case X86::PCMPESTRM128MEM:
14795  case X86::VPCMPESTRM128MEM:
14796    assert(Subtarget->hasSSE42() &&
14797           "Target must have SSE4.2 or AVX features enabled");
14798    return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14799
14800  // String/text processing lowering.
14801  case X86::PCMPISTRIREG:
14802  case X86::VPCMPISTRIREG:
14803  case X86::PCMPISTRIMEM:
14804  case X86::VPCMPISTRIMEM:
14805  case X86::PCMPESTRIREG:
14806  case X86::VPCMPESTRIREG:
14807  case X86::PCMPESTRIMEM:
14808  case X86::VPCMPESTRIMEM:
14809    assert(Subtarget->hasSSE42() &&
14810           "Target must have SSE4.2 or AVX features enabled");
14811    return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14812
14813  // Thread synchronization.
14814  case X86::MONITOR:
14815    return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14816
14817  // xbegin
14818  case X86::XBEGIN:
14819    return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14820
14821  // Atomic Lowering.
14822  case X86::ATOMAND8:
14823  case X86::ATOMAND16:
14824  case X86::ATOMAND32:
14825  case X86::ATOMAND64:
14826    // Fall through
14827  case X86::ATOMOR8:
14828  case X86::ATOMOR16:
14829  case X86::ATOMOR32:
14830  case X86::ATOMOR64:
14831    // Fall through
14832  case X86::ATOMXOR16:
14833  case X86::ATOMXOR8:
14834  case X86::ATOMXOR32:
14835  case X86::ATOMXOR64:
14836    // Fall through
14837  case X86::ATOMNAND8:
14838  case X86::ATOMNAND16:
14839  case X86::ATOMNAND32:
14840  case X86::ATOMNAND64:
14841    // Fall through
14842  case X86::ATOMMAX8:
14843  case X86::ATOMMAX16:
14844  case X86::ATOMMAX32:
14845  case X86::ATOMMAX64:
14846    // Fall through
14847  case X86::ATOMMIN8:
14848  case X86::ATOMMIN16:
14849  case X86::ATOMMIN32:
14850  case X86::ATOMMIN64:
14851    // Fall through
14852  case X86::ATOMUMAX8:
14853  case X86::ATOMUMAX16:
14854  case X86::ATOMUMAX32:
14855  case X86::ATOMUMAX64:
14856    // Fall through
14857  case X86::ATOMUMIN8:
14858  case X86::ATOMUMIN16:
14859  case X86::ATOMUMIN32:
14860  case X86::ATOMUMIN64:
14861    return EmitAtomicLoadArith(MI, BB);
14862
14863  // This group does 64-bit operations on a 32-bit host.
14864  case X86::ATOMAND6432:
14865  case X86::ATOMOR6432:
14866  case X86::ATOMXOR6432:
14867  case X86::ATOMNAND6432:
14868  case X86::ATOMADD6432:
14869  case X86::ATOMSUB6432:
14870  case X86::ATOMMAX6432:
14871  case X86::ATOMMIN6432:
14872  case X86::ATOMUMAX6432:
14873  case X86::ATOMUMIN6432:
14874  case X86::ATOMSWAP6432:
14875    return EmitAtomicLoadArith6432(MI, BB);
14876
14877  case X86::VASTART_SAVE_XMM_REGS:
14878    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14879
14880  case X86::VAARG_64:
14881    return EmitVAARG64WithCustomInserter(MI, BB);
14882
14883  case X86::EH_SjLj_SetJmp32:
14884  case X86::EH_SjLj_SetJmp64:
14885    return emitEHSjLjSetJmp(MI, BB);
14886
14887  case X86::EH_SjLj_LongJmp32:
14888  case X86::EH_SjLj_LongJmp64:
14889    return emitEHSjLjLongJmp(MI, BB);
14890  }
14891}
14892
14893//===----------------------------------------------------------------------===//
14894//                           X86 Optimization Hooks
14895//===----------------------------------------------------------------------===//
14896
14897void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14898                                                       APInt &KnownZero,
14899                                                       APInt &KnownOne,
14900                                                       const SelectionDAG &DAG,
14901                                                       unsigned Depth) const {
14902  unsigned BitWidth = KnownZero.getBitWidth();
14903  unsigned Opc = Op.getOpcode();
14904  assert((Opc >= ISD::BUILTIN_OP_END ||
14905          Opc == ISD::INTRINSIC_WO_CHAIN ||
14906          Opc == ISD::INTRINSIC_W_CHAIN ||
14907          Opc == ISD::INTRINSIC_VOID) &&
14908         "Should use MaskedValueIsZero if you don't know whether Op"
14909         " is a target node!");
14910
14911  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14912  switch (Opc) {
14913  default: break;
14914  case X86ISD::ADD:
14915  case X86ISD::SUB:
14916  case X86ISD::ADC:
14917  case X86ISD::SBB:
14918  case X86ISD::SMUL:
14919  case X86ISD::UMUL:
14920  case X86ISD::INC:
14921  case X86ISD::DEC:
14922  case X86ISD::OR:
14923  case X86ISD::XOR:
14924  case X86ISD::AND:
14925    // These nodes' second result is a boolean.
14926    if (Op.getResNo() == 0)
14927      break;
14928    // Fallthrough
14929  case X86ISD::SETCC:
14930    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14931    break;
14932  case ISD::INTRINSIC_WO_CHAIN: {
14933    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14934    unsigned NumLoBits = 0;
14935    switch (IntId) {
14936    default: break;
14937    case Intrinsic::x86_sse_movmsk_ps:
14938    case Intrinsic::x86_avx_movmsk_ps_256:
14939    case Intrinsic::x86_sse2_movmsk_pd:
14940    case Intrinsic::x86_avx_movmsk_pd_256:
14941    case Intrinsic::x86_mmx_pmovmskb:
14942    case Intrinsic::x86_sse2_pmovmskb_128:
14943    case Intrinsic::x86_avx2_pmovmskb: {
14944      // High bits of movmskp{s|d}, pmovmskb are known zero.
14945      switch (IntId) {
14946        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14947        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14948        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14949        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14950        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14951        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14952        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14953        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14954      }
14955      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14956      break;
14957    }
14958    }
14959    break;
14960  }
14961  }
14962}
14963
14964unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14965                                                         unsigned Depth) const {
14966  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14967  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14968    return Op.getValueType().getScalarType().getSizeInBits();
14969
14970  // Fallback case.
14971  return 1;
14972}
14973
14974/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14975/// node is a GlobalAddress + offset.
14976bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14977                                       const GlobalValue* &GA,
14978                                       int64_t &Offset) const {
14979  if (N->getOpcode() == X86ISD::Wrapper) {
14980    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14981      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14982      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14983      return true;
14984    }
14985  }
14986  return TargetLowering::isGAPlusOffset(N, GA, Offset);
14987}
14988
14989/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14990/// same as extracting the high 128-bit part of 256-bit vector and then
14991/// inserting the result into the low part of a new 256-bit vector
14992static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14993  EVT VT = SVOp->getValueType(0);
14994  unsigned NumElems = VT.getVectorNumElements();
14995
14996  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14997  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14998    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14999        SVOp->getMaskElt(j) >= 0)
15000      return false;
15001
15002  return true;
15003}
15004
15005/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15006/// same as extracting the low 128-bit part of 256-bit vector and then
15007/// inserting the result into the high part of a new 256-bit vector
15008static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15009  EVT VT = SVOp->getValueType(0);
15010  unsigned NumElems = VT.getVectorNumElements();
15011
15012  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15013  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15014    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15015        SVOp->getMaskElt(j) >= 0)
15016      return false;
15017
15018  return true;
15019}
15020
15021/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15022static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15023                                        TargetLowering::DAGCombinerInfo &DCI,
15024                                        const X86Subtarget* Subtarget) {
15025  DebugLoc dl = N->getDebugLoc();
15026  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15027  SDValue V1 = SVOp->getOperand(0);
15028  SDValue V2 = SVOp->getOperand(1);
15029  EVT VT = SVOp->getValueType(0);
15030  unsigned NumElems = VT.getVectorNumElements();
15031
15032  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15033      V2.getOpcode() == ISD::CONCAT_VECTORS) {
15034    //
15035    //                   0,0,0,...
15036    //                      |
15037    //    V      UNDEF    BUILD_VECTOR    UNDEF
15038    //     \      /           \           /
15039    //  CONCAT_VECTOR         CONCAT_VECTOR
15040    //         \                  /
15041    //          \                /
15042    //          RESULT: V + zero extended
15043    //
15044    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15045        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15046        V1.getOperand(1).getOpcode() != ISD::UNDEF)
15047      return SDValue();
15048
15049    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15050      return SDValue();
15051
15052    // To match the shuffle mask, the first half of the mask should
15053    // be exactly the first vector, and all the rest a splat with the
15054    // first element of the second one.
15055    for (unsigned i = 0; i != NumElems/2; ++i)
15056      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15057          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15058        return SDValue();
15059
15060    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15061    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15062      if (Ld->hasNUsesOfValue(1, 0)) {
15063        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15064        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15065        SDValue ResNode =
15066          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
15067                                  Ld->getMemoryVT(),
15068                                  Ld->getPointerInfo(),
15069                                  Ld->getAlignment(),
15070                                  false/*isVolatile*/, true/*ReadMem*/,
15071                                  false/*WriteMem*/);
15072
15073        // Make sure the newly-created LOAD is in the same position as Ld in
15074        // terms of dependency. We create a TokenFactor for Ld and ResNode,
15075        // and update uses of Ld's output chain to use the TokenFactor.
15076        if (Ld->hasAnyUseOfValue(1)) {
15077          SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15078                             SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15079          DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15080          DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15081                                 SDValue(ResNode.getNode(), 1));
15082        }
15083
15084        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15085      }
15086    }
15087
15088    // Emit a zeroed vector and insert the desired subvector on its
15089    // first half.
15090    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15091    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15092    return DCI.CombineTo(N, InsV);
15093  }
15094
15095  //===--------------------------------------------------------------------===//
15096  // Combine some shuffles into subvector extracts and inserts:
15097  //
15098
15099  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15100  if (isShuffleHigh128VectorInsertLow(SVOp)) {
15101    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15102    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15103    return DCI.CombineTo(N, InsV);
15104  }
15105
15106  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15107  if (isShuffleLow128VectorInsertHigh(SVOp)) {
15108    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15109    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15110    return DCI.CombineTo(N, InsV);
15111  }
15112
15113  return SDValue();
15114}
15115
15116/// PerformShuffleCombine - Performs several different shuffle combines.
15117static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15118                                     TargetLowering::DAGCombinerInfo &DCI,
15119                                     const X86Subtarget *Subtarget) {
15120  DebugLoc dl = N->getDebugLoc();
15121  EVT VT = N->getValueType(0);
15122
15123  // Don't create instructions with illegal types after legalize types has run.
15124  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15125  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15126    return SDValue();
15127
15128  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15129  if (Subtarget->hasFp256() && VT.is256BitVector() &&
15130      N->getOpcode() == ISD::VECTOR_SHUFFLE)
15131    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15132
15133  // Only handle 128 wide vector from here on.
15134  if (!VT.is128BitVector())
15135    return SDValue();
15136
15137  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15138  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15139  // consecutive, non-overlapping, and in the right order.
15140  SmallVector<SDValue, 16> Elts;
15141  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15142    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15143
15144  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15145}
15146
15147/// PerformTruncateCombine - Converts truncate operation to
15148/// a sequence of vector shuffle operations.
15149/// It is possible when we truncate 256-bit vector to 128-bit vector
15150static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15151                                      TargetLowering::DAGCombinerInfo &DCI,
15152                                      const X86Subtarget *Subtarget)  {
15153  return SDValue();
15154}
15155
15156/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15157/// specific shuffle of a load can be folded into a single element load.
15158/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15159/// shuffles have been customed lowered so we need to handle those here.
15160static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15161                                         TargetLowering::DAGCombinerInfo &DCI) {
15162  if (DCI.isBeforeLegalizeOps())
15163    return SDValue();
15164
15165  SDValue InVec = N->getOperand(0);
15166  SDValue EltNo = N->getOperand(1);
15167
15168  if (!isa<ConstantSDNode>(EltNo))
15169    return SDValue();
15170
15171  EVT VT = InVec.getValueType();
15172
15173  bool HasShuffleIntoBitcast = false;
15174  if (InVec.getOpcode() == ISD::BITCAST) {
15175    // Don't duplicate a load with other uses.
15176    if (!InVec.hasOneUse())
15177      return SDValue();
15178    EVT BCVT = InVec.getOperand(0).getValueType();
15179    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15180      return SDValue();
15181    InVec = InVec.getOperand(0);
15182    HasShuffleIntoBitcast = true;
15183  }
15184
15185  if (!isTargetShuffle(InVec.getOpcode()))
15186    return SDValue();
15187
15188  // Don't duplicate a load with other uses.
15189  if (!InVec.hasOneUse())
15190    return SDValue();
15191
15192  SmallVector<int, 16> ShuffleMask;
15193  bool UnaryShuffle;
15194  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15195                            UnaryShuffle))
15196    return SDValue();
15197
15198  // Select the input vector, guarding against out of range extract vector.
15199  unsigned NumElems = VT.getVectorNumElements();
15200  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15201  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15202  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15203                                         : InVec.getOperand(1);
15204
15205  // If inputs to shuffle are the same for both ops, then allow 2 uses
15206  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15207
15208  if (LdNode.getOpcode() == ISD::BITCAST) {
15209    // Don't duplicate a load with other uses.
15210    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15211      return SDValue();
15212
15213    AllowedUses = 1; // only allow 1 load use if we have a bitcast
15214    LdNode = LdNode.getOperand(0);
15215  }
15216
15217  if (!ISD::isNormalLoad(LdNode.getNode()))
15218    return SDValue();
15219
15220  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15221
15222  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15223    return SDValue();
15224
15225  if (HasShuffleIntoBitcast) {
15226    // If there's a bitcast before the shuffle, check if the load type and
15227    // alignment is valid.
15228    unsigned Align = LN0->getAlignment();
15229    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15230    unsigned NewAlign = TLI.getDataLayout()->
15231      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15232
15233    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15234      return SDValue();
15235  }
15236
15237  // All checks match so transform back to vector_shuffle so that DAG combiner
15238  // can finish the job
15239  DebugLoc dl = N->getDebugLoc();
15240
15241  // Create shuffle node taking into account the case that its a unary shuffle
15242  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15243  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15244                                 InVec.getOperand(0), Shuffle,
15245                                 &ShuffleMask[0]);
15246  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15247  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15248                     EltNo);
15249}
15250
15251/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15252/// generation and convert it from being a bunch of shuffles and extracts
15253/// to a simple store and scalar loads to extract the elements.
15254static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15255                                         TargetLowering::DAGCombinerInfo &DCI) {
15256  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15257  if (NewOp.getNode())
15258    return NewOp;
15259
15260  SDValue InputVector = N->getOperand(0);
15261  // Detect whether we are trying to convert from mmx to i32 and the bitcast
15262  // from mmx to v2i32 has a single usage.
15263  if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15264      InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15265      InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15266    return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15267                       N->getValueType(0),
15268                       InputVector.getNode()->getOperand(0));
15269
15270  // Only operate on vectors of 4 elements, where the alternative shuffling
15271  // gets to be more expensive.
15272  if (InputVector.getValueType() != MVT::v4i32)
15273    return SDValue();
15274
15275  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15276  // single use which is a sign-extend or zero-extend, and all elements are
15277  // used.
15278  SmallVector<SDNode *, 4> Uses;
15279  unsigned ExtractedElements = 0;
15280  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15281       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15282    if (UI.getUse().getResNo() != InputVector.getResNo())
15283      return SDValue();
15284
15285    SDNode *Extract = *UI;
15286    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15287      return SDValue();
15288
15289    if (Extract->getValueType(0) != MVT::i32)
15290      return SDValue();
15291    if (!Extract->hasOneUse())
15292      return SDValue();
15293    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15294        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15295      return SDValue();
15296    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15297      return SDValue();
15298
15299    // Record which element was extracted.
15300    ExtractedElements |=
15301      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15302
15303    Uses.push_back(Extract);
15304  }
15305
15306  // If not all the elements were used, this may not be worthwhile.
15307  if (ExtractedElements != 15)
15308    return SDValue();
15309
15310  // Ok, we've now decided to do the transformation.
15311  DebugLoc dl = InputVector.getDebugLoc();
15312
15313  // Store the value to a temporary stack slot.
15314  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15315  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15316                            MachinePointerInfo(), false, false, 0);
15317
15318  // Replace each use (extract) with a load of the appropriate element.
15319  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15320       UE = Uses.end(); UI != UE; ++UI) {
15321    SDNode *Extract = *UI;
15322
15323    // cOMpute the element's address.
15324    SDValue Idx = Extract->getOperand(1);
15325    unsigned EltSize =
15326        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15327    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15328    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15329    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15330
15331    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15332                                     StackPtr, OffsetVal);
15333
15334    // Load the scalar.
15335    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15336                                     ScalarAddr, MachinePointerInfo(),
15337                                     false, false, false, 0);
15338
15339    // Replace the exact with the load.
15340    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15341  }
15342
15343  // The replacement was made in place; don't return anything.
15344  return SDValue();
15345}
15346
15347/// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15348static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15349                                   SDValue RHS, SelectionDAG &DAG,
15350                                   const X86Subtarget *Subtarget) {
15351  if (!VT.isVector())
15352    return 0;
15353
15354  switch (VT.getSimpleVT().SimpleTy) {
15355  default: return 0;
15356  case MVT::v32i8:
15357  case MVT::v16i16:
15358  case MVT::v8i32:
15359    if (!Subtarget->hasAVX2())
15360      return 0;
15361  case MVT::v16i8:
15362  case MVT::v8i16:
15363  case MVT::v4i32:
15364    if (!Subtarget->hasSSE2())
15365      return 0;
15366  }
15367
15368  // SSE2 has only a small subset of the operations.
15369  bool hasUnsigned = Subtarget->hasSSE41() ||
15370                     (Subtarget->hasSSE2() && VT == MVT::v16i8);
15371  bool hasSigned = Subtarget->hasSSE41() ||
15372                   (Subtarget->hasSSE2() && VT == MVT::v8i16);
15373
15374  ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15375
15376  // Check for x CC y ? x : y.
15377  if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15378      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15379    switch (CC) {
15380    default: break;
15381    case ISD::SETULT:
15382    case ISD::SETULE:
15383      return hasUnsigned ? X86ISD::UMIN : 0;
15384    case ISD::SETUGT:
15385    case ISD::SETUGE:
15386      return hasUnsigned ? X86ISD::UMAX : 0;
15387    case ISD::SETLT:
15388    case ISD::SETLE:
15389      return hasSigned ? X86ISD::SMIN : 0;
15390    case ISD::SETGT:
15391    case ISD::SETGE:
15392      return hasSigned ? X86ISD::SMAX : 0;
15393    }
15394  // Check for x CC y ? y : x -- a min/max with reversed arms.
15395  } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15396             DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15397    switch (CC) {
15398    default: break;
15399    case ISD::SETULT:
15400    case ISD::SETULE:
15401      return hasUnsigned ? X86ISD::UMAX : 0;
15402    case ISD::SETUGT:
15403    case ISD::SETUGE:
15404      return hasUnsigned ? X86ISD::UMIN : 0;
15405    case ISD::SETLT:
15406    case ISD::SETLE:
15407      return hasSigned ? X86ISD::SMAX : 0;
15408    case ISD::SETGT:
15409    case ISD::SETGE:
15410      return hasSigned ? X86ISD::SMIN : 0;
15411    }
15412  }
15413
15414  return 0;
15415}
15416
15417/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15418/// nodes.
15419static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15420                                    TargetLowering::DAGCombinerInfo &DCI,
15421                                    const X86Subtarget *Subtarget) {
15422  DebugLoc DL = N->getDebugLoc();
15423  SDValue Cond = N->getOperand(0);
15424  // Get the LHS/RHS of the select.
15425  SDValue LHS = N->getOperand(1);
15426  SDValue RHS = N->getOperand(2);
15427  EVT VT = LHS.getValueType();
15428
15429  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15430  // instructions match the semantics of the common C idiom x<y?x:y but not
15431  // x<=y?x:y, because of how they handle negative zero (which can be
15432  // ignored in unsafe-math mode).
15433  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15434      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15435      (Subtarget->hasSSE2() ||
15436       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15437    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15438
15439    unsigned Opcode = 0;
15440    // Check for x CC y ? x : y.
15441    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15442        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15443      switch (CC) {
15444      default: break;
15445      case ISD::SETULT:
15446        // Converting this to a min would handle NaNs incorrectly, and swapping
15447        // the operands would cause it to handle comparisons between positive
15448        // and negative zero incorrectly.
15449        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15450          if (!DAG.getTarget().Options.UnsafeFPMath &&
15451              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15452            break;
15453          std::swap(LHS, RHS);
15454        }
15455        Opcode = X86ISD::FMIN;
15456        break;
15457      case ISD::SETOLE:
15458        // Converting this to a min would handle comparisons between positive
15459        // and negative zero incorrectly.
15460        if (!DAG.getTarget().Options.UnsafeFPMath &&
15461            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15462          break;
15463        Opcode = X86ISD::FMIN;
15464        break;
15465      case ISD::SETULE:
15466        // Converting this to a min would handle both negative zeros and NaNs
15467        // incorrectly, but we can swap the operands to fix both.
15468        std::swap(LHS, RHS);
15469      case ISD::SETOLT:
15470      case ISD::SETLT:
15471      case ISD::SETLE:
15472        Opcode = X86ISD::FMIN;
15473        break;
15474
15475      case ISD::SETOGE:
15476        // Converting this to a max would handle comparisons between positive
15477        // and negative zero incorrectly.
15478        if (!DAG.getTarget().Options.UnsafeFPMath &&
15479            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15480          break;
15481        Opcode = X86ISD::FMAX;
15482        break;
15483      case ISD::SETUGT:
15484        // Converting this to a max would handle NaNs incorrectly, and swapping
15485        // the operands would cause it to handle comparisons between positive
15486        // and negative zero incorrectly.
15487        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15488          if (!DAG.getTarget().Options.UnsafeFPMath &&
15489              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15490            break;
15491          std::swap(LHS, RHS);
15492        }
15493        Opcode = X86ISD::FMAX;
15494        break;
15495      case ISD::SETUGE:
15496        // Converting this to a max would handle both negative zeros and NaNs
15497        // incorrectly, but we can swap the operands to fix both.
15498        std::swap(LHS, RHS);
15499      case ISD::SETOGT:
15500      case ISD::SETGT:
15501      case ISD::SETGE:
15502        Opcode = X86ISD::FMAX;
15503        break;
15504      }
15505    // Check for x CC y ? y : x -- a min/max with reversed arms.
15506    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15507               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15508      switch (CC) {
15509      default: break;
15510      case ISD::SETOGE:
15511        // Converting this to a min would handle comparisons between positive
15512        // and negative zero incorrectly, and swapping the operands would
15513        // cause it to handle NaNs incorrectly.
15514        if (!DAG.getTarget().Options.UnsafeFPMath &&
15515            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15516          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15517            break;
15518          std::swap(LHS, RHS);
15519        }
15520        Opcode = X86ISD::FMIN;
15521        break;
15522      case ISD::SETUGT:
15523        // Converting this to a min would handle NaNs incorrectly.
15524        if (!DAG.getTarget().Options.UnsafeFPMath &&
15525            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15526          break;
15527        Opcode = X86ISD::FMIN;
15528        break;
15529      case ISD::SETUGE:
15530        // Converting this to a min would handle both negative zeros and NaNs
15531        // incorrectly, but we can swap the operands to fix both.
15532        std::swap(LHS, RHS);
15533      case ISD::SETOGT:
15534      case ISD::SETGT:
15535      case ISD::SETGE:
15536        Opcode = X86ISD::FMIN;
15537        break;
15538
15539      case ISD::SETULT:
15540        // Converting this to a max would handle NaNs incorrectly.
15541        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15542          break;
15543        Opcode = X86ISD::FMAX;
15544        break;
15545      case ISD::SETOLE:
15546        // Converting this to a max would handle comparisons between positive
15547        // and negative zero incorrectly, and swapping the operands would
15548        // cause it to handle NaNs incorrectly.
15549        if (!DAG.getTarget().Options.UnsafeFPMath &&
15550            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15551          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15552            break;
15553          std::swap(LHS, RHS);
15554        }
15555        Opcode = X86ISD::FMAX;
15556        break;
15557      case ISD::SETULE:
15558        // Converting this to a max would handle both negative zeros and NaNs
15559        // incorrectly, but we can swap the operands to fix both.
15560        std::swap(LHS, RHS);
15561      case ISD::SETOLT:
15562      case ISD::SETLT:
15563      case ISD::SETLE:
15564        Opcode = X86ISD::FMAX;
15565        break;
15566      }
15567    }
15568
15569    if (Opcode)
15570      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15571  }
15572
15573  // If this is a select between two integer constants, try to do some
15574  // optimizations.
15575  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15576    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15577      // Don't do this for crazy integer types.
15578      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15579        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15580        // so that TrueC (the true value) is larger than FalseC.
15581        bool NeedsCondInvert = false;
15582
15583        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15584            // Efficiently invertible.
15585            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15586             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15587              isa<ConstantSDNode>(Cond.getOperand(1))))) {
15588          NeedsCondInvert = true;
15589          std::swap(TrueC, FalseC);
15590        }
15591
15592        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15593        if (FalseC->getAPIntValue() == 0 &&
15594            TrueC->getAPIntValue().isPowerOf2()) {
15595          if (NeedsCondInvert) // Invert the condition if needed.
15596            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15597                               DAG.getConstant(1, Cond.getValueType()));
15598
15599          // Zero extend the condition if needed.
15600          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15601
15602          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15603          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15604                             DAG.getConstant(ShAmt, MVT::i8));
15605        }
15606
15607        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15608        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15609          if (NeedsCondInvert) // Invert the condition if needed.
15610            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15611                               DAG.getConstant(1, Cond.getValueType()));
15612
15613          // Zero extend the condition if needed.
15614          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15615                             FalseC->getValueType(0), Cond);
15616          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15617                             SDValue(FalseC, 0));
15618        }
15619
15620        // Optimize cases that will turn into an LEA instruction.  This requires
15621        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15622        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15623          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15624          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15625
15626          bool isFastMultiplier = false;
15627          if (Diff < 10) {
15628            switch ((unsigned char)Diff) {
15629              default: break;
15630              case 1:  // result = add base, cond
15631              case 2:  // result = lea base(    , cond*2)
15632              case 3:  // result = lea base(cond, cond*2)
15633              case 4:  // result = lea base(    , cond*4)
15634              case 5:  // result = lea base(cond, cond*4)
15635              case 8:  // result = lea base(    , cond*8)
15636              case 9:  // result = lea base(cond, cond*8)
15637                isFastMultiplier = true;
15638                break;
15639            }
15640          }
15641
15642          if (isFastMultiplier) {
15643            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15644            if (NeedsCondInvert) // Invert the condition if needed.
15645              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15646                                 DAG.getConstant(1, Cond.getValueType()));
15647
15648            // Zero extend the condition if needed.
15649            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15650                               Cond);
15651            // Scale the condition by the difference.
15652            if (Diff != 1)
15653              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15654                                 DAG.getConstant(Diff, Cond.getValueType()));
15655
15656            // Add the base if non-zero.
15657            if (FalseC->getAPIntValue() != 0)
15658              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15659                                 SDValue(FalseC, 0));
15660            return Cond;
15661          }
15662        }
15663      }
15664  }
15665
15666  // Canonicalize max and min:
15667  // (x > y) ? x : y -> (x >= y) ? x : y
15668  // (x < y) ? x : y -> (x <= y) ? x : y
15669  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15670  // the need for an extra compare
15671  // against zero. e.g.
15672  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15673  // subl   %esi, %edi
15674  // testl  %edi, %edi
15675  // movl   $0, %eax
15676  // cmovgl %edi, %eax
15677  // =>
15678  // xorl   %eax, %eax
15679  // subl   %esi, $edi
15680  // cmovsl %eax, %edi
15681  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15682      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15683      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15684    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15685    switch (CC) {
15686    default: break;
15687    case ISD::SETLT:
15688    case ISD::SETGT: {
15689      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15690      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15691                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
15692      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15693    }
15694    }
15695  }
15696
15697  // Match VSELECTs into subs with unsigned saturation.
15698  if (!DCI.isBeforeLegalize() &&
15699      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15700      // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15701      ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15702       (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15703    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15704
15705    // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15706    // left side invert the predicate to simplify logic below.
15707    SDValue Other;
15708    if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15709      Other = RHS;
15710      CC = ISD::getSetCCInverse(CC, true);
15711    } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15712      Other = LHS;
15713    }
15714
15715    if (Other.getNode() && Other->getNumOperands() == 2 &&
15716        DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15717      SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15718      SDValue CondRHS = Cond->getOperand(1);
15719
15720      // Look for a general sub with unsigned saturation first.
15721      // x >= y ? x-y : 0 --> subus x, y
15722      // x >  y ? x-y : 0 --> subus x, y
15723      if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15724          Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15725        return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15726
15727      // If the RHS is a constant we have to reverse the const canonicalization.
15728      // x > C-1 ? x+-C : 0 --> subus x, C
15729      if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15730          isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15731        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15732        if (CondRHS.getConstantOperandVal(0) == -A-1)
15733          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15734                             DAG.getConstant(-A, VT));
15735      }
15736
15737      // Another special case: If C was a sign bit, the sub has been
15738      // canonicalized into a xor.
15739      // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15740      //        it's safe to decanonicalize the xor?
15741      // x s< 0 ? x^C : 0 --> subus x, C
15742      if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15743          ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15744          isSplatVector(OpRHS.getNode())) {
15745        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15746        if (A.isSignBit())
15747          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15748      }
15749    }
15750  }
15751
15752  // Try to match a min/max vector operation.
15753  if (!DCI.isBeforeLegalize() &&
15754      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15755    if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15756      return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15757
15758  // If we know that this node is legal then we know that it is going to be
15759  // matched by one of the SSE/AVX BLEND instructions. These instructions only
15760  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15761  // to simplify previous instructions.
15762  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15763  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15764      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15765    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15766
15767    // Don't optimize vector selects that map to mask-registers.
15768    if (BitWidth == 1)
15769      return SDValue();
15770
15771    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15772    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15773
15774    APInt KnownZero, KnownOne;
15775    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15776                                          DCI.isBeforeLegalizeOps());
15777    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15778        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15779      DCI.CommitTargetLoweringOpt(TLO);
15780  }
15781
15782  return SDValue();
15783}
15784
15785// Check whether a boolean test is testing a boolean value generated by
15786// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15787// code.
15788//
15789// Simplify the following patterns:
15790// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15791// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15792// to (Op EFLAGS Cond)
15793//
15794// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15795// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15796// to (Op EFLAGS !Cond)
15797//
15798// where Op could be BRCOND or CMOV.
15799//
15800static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15801  // Quit if not CMP and SUB with its value result used.
15802  if (Cmp.getOpcode() != X86ISD::CMP &&
15803      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15804      return SDValue();
15805
15806  // Quit if not used as a boolean value.
15807  if (CC != X86::COND_E && CC != X86::COND_NE)
15808    return SDValue();
15809
15810  // Check CMP operands. One of them should be 0 or 1 and the other should be
15811  // an SetCC or extended from it.
15812  SDValue Op1 = Cmp.getOperand(0);
15813  SDValue Op2 = Cmp.getOperand(1);
15814
15815  SDValue SetCC;
15816  const ConstantSDNode* C = 0;
15817  bool needOppositeCond = (CC == X86::COND_E);
15818
15819  if ((C = dyn_cast<ConstantSDNode>(Op1)))
15820    SetCC = Op2;
15821  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15822    SetCC = Op1;
15823  else // Quit if all operands are not constants.
15824    return SDValue();
15825
15826  if (C->getZExtValue() == 1)
15827    needOppositeCond = !needOppositeCond;
15828  else if (C->getZExtValue() != 0)
15829    // Quit if the constant is neither 0 or 1.
15830    return SDValue();
15831
15832  // Skip 'zext' or 'trunc' node.
15833  if (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15834      SetCC.getOpcode() == ISD::TRUNCATE)
15835    SetCC = SetCC.getOperand(0);
15836
15837  switch (SetCC.getOpcode()) {
15838  case X86ISD::SETCC:
15839    // Set the condition code or opposite one if necessary.
15840    CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15841    if (needOppositeCond)
15842      CC = X86::GetOppositeBranchCondition(CC);
15843    return SetCC.getOperand(1);
15844  case X86ISD::CMOV: {
15845    // Check whether false/true value has canonical one, i.e. 0 or 1.
15846    ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15847    ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15848    // Quit if true value is not a constant.
15849    if (!TVal)
15850      return SDValue();
15851    // Quit if false value is not a constant.
15852    if (!FVal) {
15853      SDValue Op = SetCC.getOperand(0);
15854      // Skip 'zext' or 'trunc' node.
15855      if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15856          Op.getOpcode() == ISD::TRUNCATE)
15857        Op = Op.getOperand(0);
15858      // A special case for rdrand/rdseed, where 0 is set if false cond is
15859      // found.
15860      if ((Op.getOpcode() != X86ISD::RDRAND &&
15861           Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15862        return SDValue();
15863    }
15864    // Quit if false value is not the constant 0 or 1.
15865    bool FValIsFalse = true;
15866    if (FVal && FVal->getZExtValue() != 0) {
15867      if (FVal->getZExtValue() != 1)
15868        return SDValue();
15869      // If FVal is 1, opposite cond is needed.
15870      needOppositeCond = !needOppositeCond;
15871      FValIsFalse = false;
15872    }
15873    // Quit if TVal is not the constant opposite of FVal.
15874    if (FValIsFalse && TVal->getZExtValue() != 1)
15875      return SDValue();
15876    if (!FValIsFalse && TVal->getZExtValue() != 0)
15877      return SDValue();
15878    CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15879    if (needOppositeCond)
15880      CC = X86::GetOppositeBranchCondition(CC);
15881    return SetCC.getOperand(3);
15882  }
15883  }
15884
15885  return SDValue();
15886}
15887
15888/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15889static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15890                                  TargetLowering::DAGCombinerInfo &DCI,
15891                                  const X86Subtarget *Subtarget) {
15892  DebugLoc DL = N->getDebugLoc();
15893
15894  // If the flag operand isn't dead, don't touch this CMOV.
15895  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15896    return SDValue();
15897
15898  SDValue FalseOp = N->getOperand(0);
15899  SDValue TrueOp = N->getOperand(1);
15900  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15901  SDValue Cond = N->getOperand(3);
15902
15903  if (CC == X86::COND_E || CC == X86::COND_NE) {
15904    switch (Cond.getOpcode()) {
15905    default: break;
15906    case X86ISD::BSR:
15907    case X86ISD::BSF:
15908      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15909      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15910        return (CC == X86::COND_E) ? FalseOp : TrueOp;
15911    }
15912  }
15913
15914  SDValue Flags;
15915
15916  Flags = checkBoolTestSetCCCombine(Cond, CC);
15917  if (Flags.getNode() &&
15918      // Extra check as FCMOV only supports a subset of X86 cond.
15919      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15920    SDValue Ops[] = { FalseOp, TrueOp,
15921                      DAG.getConstant(CC, MVT::i8), Flags };
15922    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15923                       Ops, array_lengthof(Ops));
15924  }
15925
15926  // If this is a select between two integer constants, try to do some
15927  // optimizations.  Note that the operands are ordered the opposite of SELECT
15928  // operands.
15929  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15930    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15931      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15932      // larger than FalseC (the false value).
15933      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15934        CC = X86::GetOppositeBranchCondition(CC);
15935        std::swap(TrueC, FalseC);
15936        std::swap(TrueOp, FalseOp);
15937      }
15938
15939      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15940      // This is efficient for any integer data type (including i8/i16) and
15941      // shift amount.
15942      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15943        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15944                           DAG.getConstant(CC, MVT::i8), Cond);
15945
15946        // Zero extend the condition if needed.
15947        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15948
15949        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15950        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15951                           DAG.getConstant(ShAmt, MVT::i8));
15952        if (N->getNumValues() == 2)  // Dead flag value?
15953          return DCI.CombineTo(N, Cond, SDValue());
15954        return Cond;
15955      }
15956
15957      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15958      // for any integer data type, including i8/i16.
15959      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15960        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15961                           DAG.getConstant(CC, MVT::i8), Cond);
15962
15963        // Zero extend the condition if needed.
15964        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15965                           FalseC->getValueType(0), Cond);
15966        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15967                           SDValue(FalseC, 0));
15968
15969        if (N->getNumValues() == 2)  // Dead flag value?
15970          return DCI.CombineTo(N, Cond, SDValue());
15971        return Cond;
15972      }
15973
15974      // Optimize cases that will turn into an LEA instruction.  This requires
15975      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15976      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15977        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15978        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15979
15980        bool isFastMultiplier = false;
15981        if (Diff < 10) {
15982          switch ((unsigned char)Diff) {
15983          default: break;
15984          case 1:  // result = add base, cond
15985          case 2:  // result = lea base(    , cond*2)
15986          case 3:  // result = lea base(cond, cond*2)
15987          case 4:  // result = lea base(    , cond*4)
15988          case 5:  // result = lea base(cond, cond*4)
15989          case 8:  // result = lea base(    , cond*8)
15990          case 9:  // result = lea base(cond, cond*8)
15991            isFastMultiplier = true;
15992            break;
15993          }
15994        }
15995
15996        if (isFastMultiplier) {
15997          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15998          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15999                             DAG.getConstant(CC, MVT::i8), Cond);
16000          // Zero extend the condition if needed.
16001          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16002                             Cond);
16003          // Scale the condition by the difference.
16004          if (Diff != 1)
16005            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16006                               DAG.getConstant(Diff, Cond.getValueType()));
16007
16008          // Add the base if non-zero.
16009          if (FalseC->getAPIntValue() != 0)
16010            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16011                               SDValue(FalseC, 0));
16012          if (N->getNumValues() == 2)  // Dead flag value?
16013            return DCI.CombineTo(N, Cond, SDValue());
16014          return Cond;
16015        }
16016      }
16017    }
16018  }
16019
16020  // Handle these cases:
16021  //   (select (x != c), e, c) -> select (x != c), e, x),
16022  //   (select (x == c), c, e) -> select (x == c), x, e)
16023  // where the c is an integer constant, and the "select" is the combination
16024  // of CMOV and CMP.
16025  //
16026  // The rationale for this change is that the conditional-move from a constant
16027  // needs two instructions, however, conditional-move from a register needs
16028  // only one instruction.
16029  //
16030  // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16031  //  some instruction-combining opportunities. This opt needs to be
16032  //  postponed as late as possible.
16033  //
16034  if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16035    // the DCI.xxxx conditions are provided to postpone the optimization as
16036    // late as possible.
16037
16038    ConstantSDNode *CmpAgainst = 0;
16039    if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16040        (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16041        !isa<ConstantSDNode>(Cond.getOperand(0))) {
16042
16043      if (CC == X86::COND_NE &&
16044          CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16045        CC = X86::GetOppositeBranchCondition(CC);
16046        std::swap(TrueOp, FalseOp);
16047      }
16048
16049      if (CC == X86::COND_E &&
16050          CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16051        SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16052                          DAG.getConstant(CC, MVT::i8), Cond };
16053        return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16054                           array_lengthof(Ops));
16055      }
16056    }
16057  }
16058
16059  return SDValue();
16060}
16061
16062/// PerformMulCombine - Optimize a single multiply with constant into two
16063/// in order to implement it with two cheaper instructions, e.g.
16064/// LEA + SHL, LEA + LEA.
16065static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16066                                 TargetLowering::DAGCombinerInfo &DCI) {
16067  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16068    return SDValue();
16069
16070  EVT VT = N->getValueType(0);
16071  if (VT != MVT::i64)
16072    return SDValue();
16073
16074  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16075  if (!C)
16076    return SDValue();
16077  uint64_t MulAmt = C->getZExtValue();
16078  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16079    return SDValue();
16080
16081  uint64_t MulAmt1 = 0;
16082  uint64_t MulAmt2 = 0;
16083  if ((MulAmt % 9) == 0) {
16084    MulAmt1 = 9;
16085    MulAmt2 = MulAmt / 9;
16086  } else if ((MulAmt % 5) == 0) {
16087    MulAmt1 = 5;
16088    MulAmt2 = MulAmt / 5;
16089  } else if ((MulAmt % 3) == 0) {
16090    MulAmt1 = 3;
16091    MulAmt2 = MulAmt / 3;
16092  }
16093  if (MulAmt2 &&
16094      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16095    DebugLoc DL = N->getDebugLoc();
16096
16097    if (isPowerOf2_64(MulAmt2) &&
16098        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16099      // If second multiplifer is pow2, issue it first. We want the multiply by
16100      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16101      // is an add.
16102      std::swap(MulAmt1, MulAmt2);
16103
16104    SDValue NewMul;
16105    if (isPowerOf2_64(MulAmt1))
16106      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16107                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16108    else
16109      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16110                           DAG.getConstant(MulAmt1, VT));
16111
16112    if (isPowerOf2_64(MulAmt2))
16113      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16114                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16115    else
16116      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16117                           DAG.getConstant(MulAmt2, VT));
16118
16119    // Do not add new nodes to DAG combiner worklist.
16120    DCI.CombineTo(N, NewMul, false);
16121  }
16122  return SDValue();
16123}
16124
16125static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16126  SDValue N0 = N->getOperand(0);
16127  SDValue N1 = N->getOperand(1);
16128  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16129  EVT VT = N0.getValueType();
16130
16131  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16132  // since the result of setcc_c is all zero's or all ones.
16133  if (VT.isInteger() && !VT.isVector() &&
16134      N1C && N0.getOpcode() == ISD::AND &&
16135      N0.getOperand(1).getOpcode() == ISD::Constant) {
16136    SDValue N00 = N0.getOperand(0);
16137    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16138        ((N00.getOpcode() == ISD::ANY_EXTEND ||
16139          N00.getOpcode() == ISD::ZERO_EXTEND) &&
16140         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16141      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16142      APInt ShAmt = N1C->getAPIntValue();
16143      Mask = Mask.shl(ShAmt);
16144      if (Mask != 0)
16145        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16146                           N00, DAG.getConstant(Mask, VT));
16147    }
16148  }
16149
16150  // Hardware support for vector shifts is sparse which makes us scalarize the
16151  // vector operations in many cases. Also, on sandybridge ADD is faster than
16152  // shl.
16153  // (shl V, 1) -> add V,V
16154  if (isSplatVector(N1.getNode())) {
16155    assert(N0.getValueType().isVector() && "Invalid vector shift type");
16156    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16157    // We shift all of the values by one. In many cases we do not have
16158    // hardware support for this operation. This is better expressed as an ADD
16159    // of two values.
16160    if (N1C && (1 == N1C->getZExtValue())) {
16161      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16162    }
16163  }
16164
16165  return SDValue();
16166}
16167
16168/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16169///                       when possible.
16170static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16171                                   TargetLowering::DAGCombinerInfo &DCI,
16172                                   const X86Subtarget *Subtarget) {
16173  if (N->getOpcode() == ISD::SHL) {
16174    SDValue V = PerformSHLCombine(N, DAG);
16175    if (V.getNode()) return V;
16176  }
16177
16178  return SDValue();
16179}
16180
16181// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16182// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16183// and friends.  Likewise for OR -> CMPNEQSS.
16184static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16185                            TargetLowering::DAGCombinerInfo &DCI,
16186                            const X86Subtarget *Subtarget) {
16187  unsigned opcode;
16188
16189  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16190  // we're requiring SSE2 for both.
16191  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16192    SDValue N0 = N->getOperand(0);
16193    SDValue N1 = N->getOperand(1);
16194    SDValue CMP0 = N0->getOperand(1);
16195    SDValue CMP1 = N1->getOperand(1);
16196    DebugLoc DL = N->getDebugLoc();
16197
16198    // The SETCCs should both refer to the same CMP.
16199    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16200      return SDValue();
16201
16202    SDValue CMP00 = CMP0->getOperand(0);
16203    SDValue CMP01 = CMP0->getOperand(1);
16204    EVT     VT    = CMP00.getValueType();
16205
16206    if (VT == MVT::f32 || VT == MVT::f64) {
16207      bool ExpectingFlags = false;
16208      // Check for any users that want flags:
16209      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16210           !ExpectingFlags && UI != UE; ++UI)
16211        switch (UI->getOpcode()) {
16212        default:
16213        case ISD::BR_CC:
16214        case ISD::BRCOND:
16215        case ISD::SELECT:
16216          ExpectingFlags = true;
16217          break;
16218        case ISD::CopyToReg:
16219        case ISD::SIGN_EXTEND:
16220        case ISD::ZERO_EXTEND:
16221        case ISD::ANY_EXTEND:
16222          break;
16223        }
16224
16225      if (!ExpectingFlags) {
16226        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16227        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16228
16229        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16230          X86::CondCode tmp = cc0;
16231          cc0 = cc1;
16232          cc1 = tmp;
16233        }
16234
16235        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16236            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16237          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16238          X86ISD::NodeType NTOperator = is64BitFP ?
16239            X86ISD::FSETCCsd : X86ISD::FSETCCss;
16240          // FIXME: need symbolic constants for these magic numbers.
16241          // See X86ATTInstPrinter.cpp:printSSECC().
16242          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16243          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16244                                              DAG.getConstant(x86cc, MVT::i8));
16245          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16246                                              OnesOrZeroesF);
16247          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16248                                      DAG.getConstant(1, MVT::i32));
16249          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16250          return OneBitOfTruth;
16251        }
16252      }
16253    }
16254  }
16255  return SDValue();
16256}
16257
16258/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16259/// so it can be folded inside ANDNP.
16260static bool CanFoldXORWithAllOnes(const SDNode *N) {
16261  EVT VT = N->getValueType(0);
16262
16263  // Match direct AllOnes for 128 and 256-bit vectors
16264  if (ISD::isBuildVectorAllOnes(N))
16265    return true;
16266
16267  // Look through a bit convert.
16268  if (N->getOpcode() == ISD::BITCAST)
16269    N = N->getOperand(0).getNode();
16270
16271  // Sometimes the operand may come from a insert_subvector building a 256-bit
16272  // allones vector
16273  if (VT.is256BitVector() &&
16274      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16275    SDValue V1 = N->getOperand(0);
16276    SDValue V2 = N->getOperand(1);
16277
16278    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16279        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16280        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16281        ISD::isBuildVectorAllOnes(V2.getNode()))
16282      return true;
16283  }
16284
16285  return false;
16286}
16287
16288// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16289// register. In most cases we actually compare or select YMM-sized registers
16290// and mixing the two types creates horrible code. This method optimizes
16291// some of the transition sequences.
16292static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16293                                 TargetLowering::DAGCombinerInfo &DCI,
16294                                 const X86Subtarget *Subtarget) {
16295  EVT VT = N->getValueType(0);
16296  if (!VT.is256BitVector())
16297    return SDValue();
16298
16299  assert((N->getOpcode() == ISD::ANY_EXTEND ||
16300          N->getOpcode() == ISD::ZERO_EXTEND ||
16301          N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16302
16303  SDValue Narrow = N->getOperand(0);
16304  EVT NarrowVT = Narrow->getValueType(0);
16305  if (!NarrowVT.is128BitVector())
16306    return SDValue();
16307
16308  if (Narrow->getOpcode() != ISD::XOR &&
16309      Narrow->getOpcode() != ISD::AND &&
16310      Narrow->getOpcode() != ISD::OR)
16311    return SDValue();
16312
16313  SDValue N0  = Narrow->getOperand(0);
16314  SDValue N1  = Narrow->getOperand(1);
16315  DebugLoc DL = Narrow->getDebugLoc();
16316
16317  // The Left side has to be a trunc.
16318  if (N0.getOpcode() != ISD::TRUNCATE)
16319    return SDValue();
16320
16321  // The type of the truncated inputs.
16322  EVT WideVT = N0->getOperand(0)->getValueType(0);
16323  if (WideVT != VT)
16324    return SDValue();
16325
16326  // The right side has to be a 'trunc' or a constant vector.
16327  bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16328  bool RHSConst = (isSplatVector(N1.getNode()) &&
16329                   isa<ConstantSDNode>(N1->getOperand(0)));
16330  if (!RHSTrunc && !RHSConst)
16331    return SDValue();
16332
16333  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16334
16335  if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16336    return SDValue();
16337
16338  // Set N0 and N1 to hold the inputs to the new wide operation.
16339  N0 = N0->getOperand(0);
16340  if (RHSConst) {
16341    N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16342                     N1->getOperand(0));
16343    SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16344    N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16345  } else if (RHSTrunc) {
16346    N1 = N1->getOperand(0);
16347  }
16348
16349  // Generate the wide operation.
16350  SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16351  unsigned Opcode = N->getOpcode();
16352  switch (Opcode) {
16353  case ISD::ANY_EXTEND:
16354    return Op;
16355  case ISD::ZERO_EXTEND: {
16356    unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16357    APInt Mask = APInt::getAllOnesValue(InBits);
16358    Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16359    return DAG.getNode(ISD::AND, DL, VT,
16360                       Op, DAG.getConstant(Mask, VT));
16361  }
16362  case ISD::SIGN_EXTEND:
16363    return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16364                       Op, DAG.getValueType(NarrowVT));
16365  default:
16366    llvm_unreachable("Unexpected opcode");
16367  }
16368}
16369
16370static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16371                                 TargetLowering::DAGCombinerInfo &DCI,
16372                                 const X86Subtarget *Subtarget) {
16373  EVT VT = N->getValueType(0);
16374  if (DCI.isBeforeLegalizeOps())
16375    return SDValue();
16376
16377  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16378  if (R.getNode())
16379    return R;
16380
16381  // Create BLSI, and BLSR instructions
16382  // BLSI is X & (-X)
16383  // BLSR is X & (X-1)
16384  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16385    SDValue N0 = N->getOperand(0);
16386    SDValue N1 = N->getOperand(1);
16387    DebugLoc DL = N->getDebugLoc();
16388
16389    // Check LHS for neg
16390    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16391        isZero(N0.getOperand(0)))
16392      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16393
16394    // Check RHS for neg
16395    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16396        isZero(N1.getOperand(0)))
16397      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16398
16399    // Check LHS for X-1
16400    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16401        isAllOnes(N0.getOperand(1)))
16402      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16403
16404    // Check RHS for X-1
16405    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16406        isAllOnes(N1.getOperand(1)))
16407      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16408
16409    return SDValue();
16410  }
16411
16412  // Want to form ANDNP nodes:
16413  // 1) In the hopes of then easily combining them with OR and AND nodes
16414  //    to form PBLEND/PSIGN.
16415  // 2) To match ANDN packed intrinsics
16416  if (VT != MVT::v2i64 && VT != MVT::v4i64)
16417    return SDValue();
16418
16419  SDValue N0 = N->getOperand(0);
16420  SDValue N1 = N->getOperand(1);
16421  DebugLoc DL = N->getDebugLoc();
16422
16423  // Check LHS for vnot
16424  if (N0.getOpcode() == ISD::XOR &&
16425      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16426      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16427    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16428
16429  // Check RHS for vnot
16430  if (N1.getOpcode() == ISD::XOR &&
16431      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16432      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16433    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16434
16435  return SDValue();
16436}
16437
16438static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16439                                TargetLowering::DAGCombinerInfo &DCI,
16440                                const X86Subtarget *Subtarget) {
16441  EVT VT = N->getValueType(0);
16442  if (DCI.isBeforeLegalizeOps())
16443    return SDValue();
16444
16445  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16446  if (R.getNode())
16447    return R;
16448
16449  SDValue N0 = N->getOperand(0);
16450  SDValue N1 = N->getOperand(1);
16451
16452  // look for psign/blend
16453  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16454    if (!Subtarget->hasSSSE3() ||
16455        (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16456      return SDValue();
16457
16458    // Canonicalize pandn to RHS
16459    if (N0.getOpcode() == X86ISD::ANDNP)
16460      std::swap(N0, N1);
16461    // or (and (m, y), (pandn m, x))
16462    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16463      SDValue Mask = N1.getOperand(0);
16464      SDValue X    = N1.getOperand(1);
16465      SDValue Y;
16466      if (N0.getOperand(0) == Mask)
16467        Y = N0.getOperand(1);
16468      if (N0.getOperand(1) == Mask)
16469        Y = N0.getOperand(0);
16470
16471      // Check to see if the mask appeared in both the AND and ANDNP and
16472      if (!Y.getNode())
16473        return SDValue();
16474
16475      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16476      // Look through mask bitcast.
16477      if (Mask.getOpcode() == ISD::BITCAST)
16478        Mask = Mask.getOperand(0);
16479      if (X.getOpcode() == ISD::BITCAST)
16480        X = X.getOperand(0);
16481      if (Y.getOpcode() == ISD::BITCAST)
16482        Y = Y.getOperand(0);
16483
16484      EVT MaskVT = Mask.getValueType();
16485
16486      // Validate that the Mask operand is a vector sra node.
16487      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16488      // there is no psrai.b
16489      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16490      unsigned SraAmt = ~0;
16491      if (Mask.getOpcode() == ISD::SRA) {
16492        SDValue Amt = Mask.getOperand(1);
16493        if (isSplatVector(Amt.getNode())) {
16494          SDValue SclrAmt = Amt->getOperand(0);
16495          if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16496            SraAmt = C->getZExtValue();
16497        }
16498      } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16499        SDValue SraC = Mask.getOperand(1);
16500        SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16501      }
16502      if ((SraAmt + 1) != EltBits)
16503        return SDValue();
16504
16505      DebugLoc DL = N->getDebugLoc();
16506
16507      // Now we know we at least have a plendvb with the mask val.  See if
16508      // we can form a psignb/w/d.
16509      // psign = x.type == y.type == mask.type && y = sub(0, x);
16510      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16511          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16512          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16513        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16514               "Unsupported VT for PSIGN");
16515        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16516        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16517      }
16518      // PBLENDVB only available on SSE 4.1
16519      if (!Subtarget->hasSSE41())
16520        return SDValue();
16521
16522      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16523
16524      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16525      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16526      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16527      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16528      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16529    }
16530  }
16531
16532  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16533    return SDValue();
16534
16535  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16536  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16537    std::swap(N0, N1);
16538  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16539    return SDValue();
16540  if (!N0.hasOneUse() || !N1.hasOneUse())
16541    return SDValue();
16542
16543  SDValue ShAmt0 = N0.getOperand(1);
16544  if (ShAmt0.getValueType() != MVT::i8)
16545    return SDValue();
16546  SDValue ShAmt1 = N1.getOperand(1);
16547  if (ShAmt1.getValueType() != MVT::i8)
16548    return SDValue();
16549  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16550    ShAmt0 = ShAmt0.getOperand(0);
16551  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16552    ShAmt1 = ShAmt1.getOperand(0);
16553
16554  DebugLoc DL = N->getDebugLoc();
16555  unsigned Opc = X86ISD::SHLD;
16556  SDValue Op0 = N0.getOperand(0);
16557  SDValue Op1 = N1.getOperand(0);
16558  if (ShAmt0.getOpcode() == ISD::SUB) {
16559    Opc = X86ISD::SHRD;
16560    std::swap(Op0, Op1);
16561    std::swap(ShAmt0, ShAmt1);
16562  }
16563
16564  unsigned Bits = VT.getSizeInBits();
16565  if (ShAmt1.getOpcode() == ISD::SUB) {
16566    SDValue Sum = ShAmt1.getOperand(0);
16567    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16568      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16569      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16570        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16571      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16572        return DAG.getNode(Opc, DL, VT,
16573                           Op0, Op1,
16574                           DAG.getNode(ISD::TRUNCATE, DL,
16575                                       MVT::i8, ShAmt0));
16576    }
16577  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16578    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16579    if (ShAmt0C &&
16580        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16581      return DAG.getNode(Opc, DL, VT,
16582                         N0.getOperand(0), N1.getOperand(0),
16583                         DAG.getNode(ISD::TRUNCATE, DL,
16584                                       MVT::i8, ShAmt0));
16585  }
16586
16587  return SDValue();
16588}
16589
16590// Generate NEG and CMOV for integer abs.
16591static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16592  EVT VT = N->getValueType(0);
16593
16594  // Since X86 does not have CMOV for 8-bit integer, we don't convert
16595  // 8-bit integer abs to NEG and CMOV.
16596  if (VT.isInteger() && VT.getSizeInBits() == 8)
16597    return SDValue();
16598
16599  SDValue N0 = N->getOperand(0);
16600  SDValue N1 = N->getOperand(1);
16601  DebugLoc DL = N->getDebugLoc();
16602
16603  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16604  // and change it to SUB and CMOV.
16605  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16606      N0.getOpcode() == ISD::ADD &&
16607      N0.getOperand(1) == N1 &&
16608      N1.getOpcode() == ISD::SRA &&
16609      N1.getOperand(0) == N0.getOperand(0))
16610    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16611      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16612        // Generate SUB & CMOV.
16613        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16614                                  DAG.getConstant(0, VT), N0.getOperand(0));
16615
16616        SDValue Ops[] = { N0.getOperand(0), Neg,
16617                          DAG.getConstant(X86::COND_GE, MVT::i8),
16618                          SDValue(Neg.getNode(), 1) };
16619        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16620                           Ops, array_lengthof(Ops));
16621      }
16622  return SDValue();
16623}
16624
16625// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16626static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16627                                 TargetLowering::DAGCombinerInfo &DCI,
16628                                 const X86Subtarget *Subtarget) {
16629  EVT VT = N->getValueType(0);
16630  if (DCI.isBeforeLegalizeOps())
16631    return SDValue();
16632
16633  if (Subtarget->hasCMov()) {
16634    SDValue RV = performIntegerAbsCombine(N, DAG);
16635    if (RV.getNode())
16636      return RV;
16637  }
16638
16639  // Try forming BMI if it is available.
16640  if (!Subtarget->hasBMI())
16641    return SDValue();
16642
16643  if (VT != MVT::i32 && VT != MVT::i64)
16644    return SDValue();
16645
16646  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16647
16648  // Create BLSMSK instructions by finding X ^ (X-1)
16649  SDValue N0 = N->getOperand(0);
16650  SDValue N1 = N->getOperand(1);
16651  DebugLoc DL = N->getDebugLoc();
16652
16653  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16654      isAllOnes(N0.getOperand(1)))
16655    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16656
16657  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16658      isAllOnes(N1.getOperand(1)))
16659    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16660
16661  return SDValue();
16662}
16663
16664/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16665static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16666                                  TargetLowering::DAGCombinerInfo &DCI,
16667                                  const X86Subtarget *Subtarget) {
16668  LoadSDNode *Ld = cast<LoadSDNode>(N);
16669  EVT RegVT = Ld->getValueType(0);
16670  EVT MemVT = Ld->getMemoryVT();
16671  DebugLoc dl = Ld->getDebugLoc();
16672  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16673  unsigned RegSz = RegVT.getSizeInBits();
16674
16675  // On Sandybridge unaligned 256bit loads are inefficient.
16676  ISD::LoadExtType Ext = Ld->getExtensionType();
16677  unsigned Alignment = Ld->getAlignment();
16678  bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16679  if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16680      !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16681    unsigned NumElems = RegVT.getVectorNumElements();
16682    if (NumElems < 2)
16683      return SDValue();
16684
16685    SDValue Ptr = Ld->getBasePtr();
16686    SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16687
16688    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16689                                  NumElems/2);
16690    SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16691                                Ld->getPointerInfo(), Ld->isVolatile(),
16692                                Ld->isNonTemporal(), Ld->isInvariant(),
16693                                Alignment);
16694    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16695    SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16696                                Ld->getPointerInfo(), Ld->isVolatile(),
16697                                Ld->isNonTemporal(), Ld->isInvariant(),
16698                                std::min(16U, Alignment));
16699    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16700                             Load1.getValue(1),
16701                             Load2.getValue(1));
16702
16703    SDValue NewVec = DAG.getUNDEF(RegVT);
16704    NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16705    NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16706    return DCI.CombineTo(N, NewVec, TF, true);
16707  }
16708
16709  // If this is a vector EXT Load then attempt to optimize it using a
16710  // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16711  // expansion is still better than scalar code.
16712  // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16713  // emit a shuffle and a arithmetic shift.
16714  // TODO: It is possible to support ZExt by zeroing the undef values
16715  // during the shuffle phase or after the shuffle.
16716  if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16717      (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16718    assert(MemVT != RegVT && "Cannot extend to the same type");
16719    assert(MemVT.isVector() && "Must load a vector from memory");
16720
16721    unsigned NumElems = RegVT.getVectorNumElements();
16722    unsigned MemSz = MemVT.getSizeInBits();
16723    assert(RegSz > MemSz && "Register size must be greater than the mem size");
16724
16725    if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16726      return SDValue();
16727
16728    // All sizes must be a power of two.
16729    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16730      return SDValue();
16731
16732    // Attempt to load the original value using scalar loads.
16733    // Find the largest scalar type that divides the total loaded size.
16734    MVT SclrLoadTy = MVT::i8;
16735    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16736         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16737      MVT Tp = (MVT::SimpleValueType)tp;
16738      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16739        SclrLoadTy = Tp;
16740      }
16741    }
16742
16743    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16744    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16745        (64 <= MemSz))
16746      SclrLoadTy = MVT::f64;
16747
16748    // Calculate the number of scalar loads that we need to perform
16749    // in order to load our vector from memory.
16750    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16751    if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16752      return SDValue();
16753
16754    unsigned loadRegZize = RegSz;
16755    if (Ext == ISD::SEXTLOAD && RegSz == 256)
16756      loadRegZize /= 2;
16757
16758    // Represent our vector as a sequence of elements which are the
16759    // largest scalar that we can load.
16760    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16761      loadRegZize/SclrLoadTy.getSizeInBits());
16762
16763    // Represent the data using the same element type that is stored in
16764    // memory. In practice, we ''widen'' MemVT.
16765    EVT WideVecVT =
16766          EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16767                       loadRegZize/MemVT.getScalarType().getSizeInBits());
16768
16769    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16770      "Invalid vector type");
16771
16772    // We can't shuffle using an illegal type.
16773    if (!TLI.isTypeLegal(WideVecVT))
16774      return SDValue();
16775
16776    SmallVector<SDValue, 8> Chains;
16777    SDValue Ptr = Ld->getBasePtr();
16778    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16779                                        TLI.getPointerTy());
16780    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16781
16782    for (unsigned i = 0; i < NumLoads; ++i) {
16783      // Perform a single load.
16784      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16785                                       Ptr, Ld->getPointerInfo(),
16786                                       Ld->isVolatile(), Ld->isNonTemporal(),
16787                                       Ld->isInvariant(), Ld->getAlignment());
16788      Chains.push_back(ScalarLoad.getValue(1));
16789      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16790      // another round of DAGCombining.
16791      if (i == 0)
16792        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16793      else
16794        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16795                          ScalarLoad, DAG.getIntPtrConstant(i));
16796
16797      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16798    }
16799
16800    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16801                               Chains.size());
16802
16803    // Bitcast the loaded value to a vector of the original element type, in
16804    // the size of the target vector type.
16805    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16806    unsigned SizeRatio = RegSz/MemSz;
16807
16808    if (Ext == ISD::SEXTLOAD) {
16809      // If we have SSE4.1 we can directly emit a VSEXT node.
16810      if (Subtarget->hasSSE41()) {
16811        SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16812        return DCI.CombineTo(N, Sext, TF, true);
16813      }
16814
16815      // Otherwise we'll shuffle the small elements in the high bits of the
16816      // larger type and perform an arithmetic shift. If the shift is not legal
16817      // it's better to scalarize.
16818      if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16819        return SDValue();
16820
16821      // Redistribute the loaded elements into the different locations.
16822      SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16823      for (unsigned i = 0; i != NumElems; ++i)
16824        ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16825
16826      SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16827                                           DAG.getUNDEF(WideVecVT),
16828                                           &ShuffleVec[0]);
16829
16830      Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16831
16832      // Build the arithmetic shift.
16833      unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16834                     MemVT.getVectorElementType().getSizeInBits();
16835      Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16836                          DAG.getConstant(Amt, RegVT));
16837
16838      return DCI.CombineTo(N, Shuff, TF, true);
16839    }
16840
16841    // Redistribute the loaded elements into the different locations.
16842    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16843    for (unsigned i = 0; i != NumElems; ++i)
16844      ShuffleVec[i*SizeRatio] = i;
16845
16846    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16847                                         DAG.getUNDEF(WideVecVT),
16848                                         &ShuffleVec[0]);
16849
16850    // Bitcast to the requested type.
16851    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16852    // Replace the original load with the new sequence
16853    // and return the new chain.
16854    return DCI.CombineTo(N, Shuff, TF, true);
16855  }
16856
16857  return SDValue();
16858}
16859
16860/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16861static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16862                                   const X86Subtarget *Subtarget) {
16863  StoreSDNode *St = cast<StoreSDNode>(N);
16864  EVT VT = St->getValue().getValueType();
16865  EVT StVT = St->getMemoryVT();
16866  DebugLoc dl = St->getDebugLoc();
16867  SDValue StoredVal = St->getOperand(1);
16868  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16869
16870  // If we are saving a concatenation of two XMM registers, perform two stores.
16871  // On Sandy Bridge, 256-bit memory operations are executed by two
16872  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16873  // memory  operation.
16874  unsigned Alignment = St->getAlignment();
16875  bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16876  if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16877      StVT == VT && !IsAligned) {
16878    unsigned NumElems = VT.getVectorNumElements();
16879    if (NumElems < 2)
16880      return SDValue();
16881
16882    SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16883    SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16884
16885    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16886    SDValue Ptr0 = St->getBasePtr();
16887    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16888
16889    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16890                                St->getPointerInfo(), St->isVolatile(),
16891                                St->isNonTemporal(), Alignment);
16892    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16893                                St->getPointerInfo(), St->isVolatile(),
16894                                St->isNonTemporal(),
16895                                std::min(16U, Alignment));
16896    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16897  }
16898
16899  // Optimize trunc store (of multiple scalars) to shuffle and store.
16900  // First, pack all of the elements in one place. Next, store to memory
16901  // in fewer chunks.
16902  if (St->isTruncatingStore() && VT.isVector()) {
16903    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16904    unsigned NumElems = VT.getVectorNumElements();
16905    assert(StVT != VT && "Cannot truncate to the same type");
16906    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16907    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16908
16909    // From, To sizes and ElemCount must be pow of two
16910    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16911    // We are going to use the original vector elt for storing.
16912    // Accumulated smaller vector elements must be a multiple of the store size.
16913    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16914
16915    unsigned SizeRatio  = FromSz / ToSz;
16916
16917    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16918
16919    // Create a type on which we perform the shuffle
16920    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16921            StVT.getScalarType(), NumElems*SizeRatio);
16922
16923    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16924
16925    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16926    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16927    for (unsigned i = 0; i != NumElems; ++i)
16928      ShuffleVec[i] = i * SizeRatio;
16929
16930    // Can't shuffle using an illegal type.
16931    if (!TLI.isTypeLegal(WideVecVT))
16932      return SDValue();
16933
16934    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16935                                         DAG.getUNDEF(WideVecVT),
16936                                         &ShuffleVec[0]);
16937    // At this point all of the data is stored at the bottom of the
16938    // register. We now need to save it to mem.
16939
16940    // Find the largest store unit
16941    MVT StoreType = MVT::i8;
16942    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16943         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16944      MVT Tp = (MVT::SimpleValueType)tp;
16945      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16946        StoreType = Tp;
16947    }
16948
16949    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16950    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16951        (64 <= NumElems * ToSz))
16952      StoreType = MVT::f64;
16953
16954    // Bitcast the original vector into a vector of store-size units
16955    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16956            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16957    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16958    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16959    SmallVector<SDValue, 8> Chains;
16960    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16961                                        TLI.getPointerTy());
16962    SDValue Ptr = St->getBasePtr();
16963
16964    // Perform one or more big stores into memory.
16965    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16966      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16967                                   StoreType, ShuffWide,
16968                                   DAG.getIntPtrConstant(i));
16969      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16970                                St->getPointerInfo(), St->isVolatile(),
16971                                St->isNonTemporal(), St->getAlignment());
16972      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16973      Chains.push_back(Ch);
16974    }
16975
16976    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16977                               Chains.size());
16978  }
16979
16980  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16981  // the FP state in cases where an emms may be missing.
16982  // A preferable solution to the general problem is to figure out the right
16983  // places to insert EMMS.  This qualifies as a quick hack.
16984
16985  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16986  if (VT.getSizeInBits() != 64)
16987    return SDValue();
16988
16989  const Function *F = DAG.getMachineFunction().getFunction();
16990  bool NoImplicitFloatOps = F->getAttributes().
16991    hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16992  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16993                     && Subtarget->hasSSE2();
16994  if ((VT.isVector() ||
16995       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16996      isa<LoadSDNode>(St->getValue()) &&
16997      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16998      St->getChain().hasOneUse() && !St->isVolatile()) {
16999    SDNode* LdVal = St->getValue().getNode();
17000    LoadSDNode *Ld = 0;
17001    int TokenFactorIndex = -1;
17002    SmallVector<SDValue, 8> Ops;
17003    SDNode* ChainVal = St->getChain().getNode();
17004    // Must be a store of a load.  We currently handle two cases:  the load
17005    // is a direct child, and it's under an intervening TokenFactor.  It is
17006    // possible to dig deeper under nested TokenFactors.
17007    if (ChainVal == LdVal)
17008      Ld = cast<LoadSDNode>(St->getChain());
17009    else if (St->getValue().hasOneUse() &&
17010             ChainVal->getOpcode() == ISD::TokenFactor) {
17011      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17012        if (ChainVal->getOperand(i).getNode() == LdVal) {
17013          TokenFactorIndex = i;
17014          Ld = cast<LoadSDNode>(St->getValue());
17015        } else
17016          Ops.push_back(ChainVal->getOperand(i));
17017      }
17018    }
17019
17020    if (!Ld || !ISD::isNormalLoad(Ld))
17021      return SDValue();
17022
17023    // If this is not the MMX case, i.e. we are just turning i64 load/store
17024    // into f64 load/store, avoid the transformation if there are multiple
17025    // uses of the loaded value.
17026    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17027      return SDValue();
17028
17029    DebugLoc LdDL = Ld->getDebugLoc();
17030    DebugLoc StDL = N->getDebugLoc();
17031    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17032    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17033    // pair instead.
17034    if (Subtarget->is64Bit() || F64IsLegal) {
17035      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17036      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17037                                  Ld->getPointerInfo(), Ld->isVolatile(),
17038                                  Ld->isNonTemporal(), Ld->isInvariant(),
17039                                  Ld->getAlignment());
17040      SDValue NewChain = NewLd.getValue(1);
17041      if (TokenFactorIndex != -1) {
17042        Ops.push_back(NewChain);
17043        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17044                               Ops.size());
17045      }
17046      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17047                          St->getPointerInfo(),
17048                          St->isVolatile(), St->isNonTemporal(),
17049                          St->getAlignment());
17050    }
17051
17052    // Otherwise, lower to two pairs of 32-bit loads / stores.
17053    SDValue LoAddr = Ld->getBasePtr();
17054    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17055                                 DAG.getConstant(4, MVT::i32));
17056
17057    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17058                               Ld->getPointerInfo(),
17059                               Ld->isVolatile(), Ld->isNonTemporal(),
17060                               Ld->isInvariant(), Ld->getAlignment());
17061    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17062                               Ld->getPointerInfo().getWithOffset(4),
17063                               Ld->isVolatile(), Ld->isNonTemporal(),
17064                               Ld->isInvariant(),
17065                               MinAlign(Ld->getAlignment(), 4));
17066
17067    SDValue NewChain = LoLd.getValue(1);
17068    if (TokenFactorIndex != -1) {
17069      Ops.push_back(LoLd);
17070      Ops.push_back(HiLd);
17071      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17072                             Ops.size());
17073    }
17074
17075    LoAddr = St->getBasePtr();
17076    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17077                         DAG.getConstant(4, MVT::i32));
17078
17079    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17080                                St->getPointerInfo(),
17081                                St->isVolatile(), St->isNonTemporal(),
17082                                St->getAlignment());
17083    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17084                                St->getPointerInfo().getWithOffset(4),
17085                                St->isVolatile(),
17086                                St->isNonTemporal(),
17087                                MinAlign(St->getAlignment(), 4));
17088    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17089  }
17090  return SDValue();
17091}
17092
17093/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17094/// and return the operands for the horizontal operation in LHS and RHS.  A
17095/// horizontal operation performs the binary operation on successive elements
17096/// of its first operand, then on successive elements of its second operand,
17097/// returning the resulting values in a vector.  For example, if
17098///   A = < float a0, float a1, float a2, float a3 >
17099/// and
17100///   B = < float b0, float b1, float b2, float b3 >
17101/// then the result of doing a horizontal operation on A and B is
17102///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17103/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17104/// A horizontal-op B, for some already available A and B, and if so then LHS is
17105/// set to A, RHS to B, and the routine returns 'true'.
17106/// Note that the binary operation should have the property that if one of the
17107/// operands is UNDEF then the result is UNDEF.
17108static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17109  // Look for the following pattern: if
17110  //   A = < float a0, float a1, float a2, float a3 >
17111  //   B = < float b0, float b1, float b2, float b3 >
17112  // and
17113  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17114  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17115  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17116  // which is A horizontal-op B.
17117
17118  // At least one of the operands should be a vector shuffle.
17119  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17120      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17121    return false;
17122
17123  EVT VT = LHS.getValueType();
17124
17125  assert((VT.is128BitVector() || VT.is256BitVector()) &&
17126         "Unsupported vector type for horizontal add/sub");
17127
17128  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17129  // operate independently on 128-bit lanes.
17130  unsigned NumElts = VT.getVectorNumElements();
17131  unsigned NumLanes = VT.getSizeInBits()/128;
17132  unsigned NumLaneElts = NumElts / NumLanes;
17133  assert((NumLaneElts % 2 == 0) &&
17134         "Vector type should have an even number of elements in each lane");
17135  unsigned HalfLaneElts = NumLaneElts/2;
17136
17137  // View LHS in the form
17138  //   LHS = VECTOR_SHUFFLE A, B, LMask
17139  // If LHS is not a shuffle then pretend it is the shuffle
17140  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17141  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17142  // type VT.
17143  SDValue A, B;
17144  SmallVector<int, 16> LMask(NumElts);
17145  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17146    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17147      A = LHS.getOperand(0);
17148    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17149      B = LHS.getOperand(1);
17150    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17151    std::copy(Mask.begin(), Mask.end(), LMask.begin());
17152  } else {
17153    if (LHS.getOpcode() != ISD::UNDEF)
17154      A = LHS;
17155    for (unsigned i = 0; i != NumElts; ++i)
17156      LMask[i] = i;
17157  }
17158
17159  // Likewise, view RHS in the form
17160  //   RHS = VECTOR_SHUFFLE C, D, RMask
17161  SDValue C, D;
17162  SmallVector<int, 16> RMask(NumElts);
17163  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17164    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17165      C = RHS.getOperand(0);
17166    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17167      D = RHS.getOperand(1);
17168    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17169    std::copy(Mask.begin(), Mask.end(), RMask.begin());
17170  } else {
17171    if (RHS.getOpcode() != ISD::UNDEF)
17172      C = RHS;
17173    for (unsigned i = 0; i != NumElts; ++i)
17174      RMask[i] = i;
17175  }
17176
17177  // Check that the shuffles are both shuffling the same vectors.
17178  if (!(A == C && B == D) && !(A == D && B == C))
17179    return false;
17180
17181  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17182  if (!A.getNode() && !B.getNode())
17183    return false;
17184
17185  // If A and B occur in reverse order in RHS, then "swap" them (which means
17186  // rewriting the mask).
17187  if (A != C)
17188    CommuteVectorShuffleMask(RMask, NumElts);
17189
17190  // At this point LHS and RHS are equivalent to
17191  //   LHS = VECTOR_SHUFFLE A, B, LMask
17192  //   RHS = VECTOR_SHUFFLE A, B, RMask
17193  // Check that the masks correspond to performing a horizontal operation.
17194  for (unsigned i = 0; i != NumElts; ++i) {
17195    int LIdx = LMask[i], RIdx = RMask[i];
17196
17197    // Ignore any UNDEF components.
17198    if (LIdx < 0 || RIdx < 0 ||
17199        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17200        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17201      continue;
17202
17203    // Check that successive elements are being operated on.  If not, this is
17204    // not a horizontal operation.
17205    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17206    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17207    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17208    if (!(LIdx == Index && RIdx == Index + 1) &&
17209        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17210      return false;
17211  }
17212
17213  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17214  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17215  return true;
17216}
17217
17218/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17219static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17220                                  const X86Subtarget *Subtarget) {
17221  EVT VT = N->getValueType(0);
17222  SDValue LHS = N->getOperand(0);
17223  SDValue RHS = N->getOperand(1);
17224
17225  // Try to synthesize horizontal adds from adds of shuffles.
17226  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17227       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17228      isHorizontalBinOp(LHS, RHS, true))
17229    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17230  return SDValue();
17231}
17232
17233/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17234static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17235                                  const X86Subtarget *Subtarget) {
17236  EVT VT = N->getValueType(0);
17237  SDValue LHS = N->getOperand(0);
17238  SDValue RHS = N->getOperand(1);
17239
17240  // Try to synthesize horizontal subs from subs of shuffles.
17241  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17242       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17243      isHorizontalBinOp(LHS, RHS, false))
17244    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17245  return SDValue();
17246}
17247
17248/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17249/// X86ISD::FXOR nodes.
17250static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17251  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17252  // F[X]OR(0.0, x) -> x
17253  // F[X]OR(x, 0.0) -> x
17254  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17255    if (C->getValueAPF().isPosZero())
17256      return N->getOperand(1);
17257  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17258    if (C->getValueAPF().isPosZero())
17259      return N->getOperand(0);
17260  return SDValue();
17261}
17262
17263/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17264/// X86ISD::FMAX nodes.
17265static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17266  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17267
17268  // Only perform optimizations if UnsafeMath is used.
17269  if (!DAG.getTarget().Options.UnsafeFPMath)
17270    return SDValue();
17271
17272  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17273  // into FMINC and FMAXC, which are Commutative operations.
17274  unsigned NewOp = 0;
17275  switch (N->getOpcode()) {
17276    default: llvm_unreachable("unknown opcode");
17277    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17278    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17279  }
17280
17281  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17282                     N->getOperand(0), N->getOperand(1));
17283}
17284
17285/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17286static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17287  // FAND(0.0, x) -> 0.0
17288  // FAND(x, 0.0) -> 0.0
17289  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17290    if (C->getValueAPF().isPosZero())
17291      return N->getOperand(0);
17292  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17293    if (C->getValueAPF().isPosZero())
17294      return N->getOperand(1);
17295  return SDValue();
17296}
17297
17298static SDValue PerformBTCombine(SDNode *N,
17299                                SelectionDAG &DAG,
17300                                TargetLowering::DAGCombinerInfo &DCI) {
17301  // BT ignores high bits in the bit index operand.
17302  SDValue Op1 = N->getOperand(1);
17303  if (Op1.hasOneUse()) {
17304    unsigned BitWidth = Op1.getValueSizeInBits();
17305    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17306    APInt KnownZero, KnownOne;
17307    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17308                                          !DCI.isBeforeLegalizeOps());
17309    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17310    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17311        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17312      DCI.CommitTargetLoweringOpt(TLO);
17313  }
17314  return SDValue();
17315}
17316
17317static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17318  SDValue Op = N->getOperand(0);
17319  if (Op.getOpcode() == ISD::BITCAST)
17320    Op = Op.getOperand(0);
17321  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17322  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17323      VT.getVectorElementType().getSizeInBits() ==
17324      OpVT.getVectorElementType().getSizeInBits()) {
17325    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17326  }
17327  return SDValue();
17328}
17329
17330static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17331                                               const X86Subtarget *Subtarget) {
17332  EVT VT = N->getValueType(0);
17333  if (!VT.isVector())
17334    return SDValue();
17335
17336  SDValue N0 = N->getOperand(0);
17337  SDValue N1 = N->getOperand(1);
17338  EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17339  DebugLoc dl = N->getDebugLoc();
17340
17341  // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17342  // both SSE and AVX2 since there is no sign-extended shift right
17343  // operation on a vector with 64-bit elements.
17344  //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17345  // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17346  if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17347      N0.getOpcode() == ISD::SIGN_EXTEND)) {
17348    SDValue N00 = N0.getOperand(0);
17349
17350    // EXTLOAD has a better solution on AVX2,
17351    // it may be replaced with X86ISD::VSEXT node.
17352    if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17353      if (!ISD::isNormalLoad(N00.getNode()))
17354        return SDValue();
17355
17356    if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17357        SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17358                                  N00, N1);
17359      return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17360    }
17361  }
17362  return SDValue();
17363}
17364
17365static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17366                                  TargetLowering::DAGCombinerInfo &DCI,
17367                                  const X86Subtarget *Subtarget) {
17368  if (!DCI.isBeforeLegalizeOps())
17369    return SDValue();
17370
17371  if (!Subtarget->hasFp256())
17372    return SDValue();
17373
17374  EVT VT = N->getValueType(0);
17375  if (VT.isVector() && VT.getSizeInBits() == 256) {
17376    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17377    if (R.getNode())
17378      return R;
17379  }
17380
17381  return SDValue();
17382}
17383
17384static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17385                                 const X86Subtarget* Subtarget) {
17386  DebugLoc dl = N->getDebugLoc();
17387  EVT VT = N->getValueType(0);
17388
17389  // Let legalize expand this if it isn't a legal type yet.
17390  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17391    return SDValue();
17392
17393  EVT ScalarVT = VT.getScalarType();
17394  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17395      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17396    return SDValue();
17397
17398  SDValue A = N->getOperand(0);
17399  SDValue B = N->getOperand(1);
17400  SDValue C = N->getOperand(2);
17401
17402  bool NegA = (A.getOpcode() == ISD::FNEG);
17403  bool NegB = (B.getOpcode() == ISD::FNEG);
17404  bool NegC = (C.getOpcode() == ISD::FNEG);
17405
17406  // Negative multiplication when NegA xor NegB
17407  bool NegMul = (NegA != NegB);
17408  if (NegA)
17409    A = A.getOperand(0);
17410  if (NegB)
17411    B = B.getOperand(0);
17412  if (NegC)
17413    C = C.getOperand(0);
17414
17415  unsigned Opcode;
17416  if (!NegMul)
17417    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17418  else
17419    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17420
17421  return DAG.getNode(Opcode, dl, VT, A, B, C);
17422}
17423
17424static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17425                                  TargetLowering::DAGCombinerInfo &DCI,
17426                                  const X86Subtarget *Subtarget) {
17427  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17428  //           (and (i32 x86isd::setcc_carry), 1)
17429  // This eliminates the zext. This transformation is necessary because
17430  // ISD::SETCC is always legalized to i8.
17431  DebugLoc dl = N->getDebugLoc();
17432  SDValue N0 = N->getOperand(0);
17433  EVT VT = N->getValueType(0);
17434
17435  if (N0.getOpcode() == ISD::AND &&
17436      N0.hasOneUse() &&
17437      N0.getOperand(0).hasOneUse()) {
17438    SDValue N00 = N0.getOperand(0);
17439    if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17440      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17441      if (!C || C->getZExtValue() != 1)
17442        return SDValue();
17443      return DAG.getNode(ISD::AND, dl, VT,
17444                         DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17445                                     N00.getOperand(0), N00.getOperand(1)),
17446                         DAG.getConstant(1, VT));
17447    }
17448  }
17449
17450  if (VT.is256BitVector()) {
17451    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17452    if (R.getNode())
17453      return R;
17454  }
17455
17456  return SDValue();
17457}
17458
17459// Optimize x == -y --> x+y == 0
17460//          x != -y --> x+y != 0
17461static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17462  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17463  SDValue LHS = N->getOperand(0);
17464  SDValue RHS = N->getOperand(1);
17465
17466  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17467    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17468      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17469        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17470                                   LHS.getValueType(), RHS, LHS.getOperand(1));
17471        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17472                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17473      }
17474  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17475    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17476      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17477        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17478                                   RHS.getValueType(), LHS, RHS.getOperand(1));
17479        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17480                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17481      }
17482  return SDValue();
17483}
17484
17485// Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17486// as "sbb reg,reg", since it can be extended without zext and produces
17487// an all-ones bit which is more useful than 0/1 in some cases.
17488static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17489  return DAG.getNode(ISD::AND, DL, MVT::i8,
17490                     DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17491                                 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17492                     DAG.getConstant(1, MVT::i8));
17493}
17494
17495// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17496static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17497                                   TargetLowering::DAGCombinerInfo &DCI,
17498                                   const X86Subtarget *Subtarget) {
17499  DebugLoc DL = N->getDebugLoc();
17500  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17501  SDValue EFLAGS = N->getOperand(1);
17502
17503  if (CC == X86::COND_A) {
17504    // Try to convert COND_A into COND_B in an attempt to facilitate
17505    // materializing "setb reg".
17506    //
17507    // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17508    // cannot take an immediate as its first operand.
17509    //
17510    if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17511        EFLAGS.getValueType().isInteger() &&
17512        !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17513      SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17514                                   EFLAGS.getNode()->getVTList(),
17515                                   EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17516      SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17517      return MaterializeSETB(DL, NewEFLAGS, DAG);
17518    }
17519  }
17520
17521  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17522  // a zext and produces an all-ones bit which is more useful than 0/1 in some
17523  // cases.
17524  if (CC == X86::COND_B)
17525    return MaterializeSETB(DL, EFLAGS, DAG);
17526
17527  SDValue Flags;
17528
17529  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17530  if (Flags.getNode()) {
17531    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17532    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17533  }
17534
17535  return SDValue();
17536}
17537
17538// Optimize branch condition evaluation.
17539//
17540static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17541                                    TargetLowering::DAGCombinerInfo &DCI,
17542                                    const X86Subtarget *Subtarget) {
17543  DebugLoc DL = N->getDebugLoc();
17544  SDValue Chain = N->getOperand(0);
17545  SDValue Dest = N->getOperand(1);
17546  SDValue EFLAGS = N->getOperand(3);
17547  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17548
17549  SDValue Flags;
17550
17551  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17552  if (Flags.getNode()) {
17553    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17554    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17555                       Flags);
17556  }
17557
17558  return SDValue();
17559}
17560
17561static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17562                                        const X86TargetLowering *XTLI) {
17563  SDValue Op0 = N->getOperand(0);
17564  EVT InVT = Op0->getValueType(0);
17565
17566  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17567  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17568    DebugLoc dl = N->getDebugLoc();
17569    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17570    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17571    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17572  }
17573
17574  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17575  // a 32-bit target where SSE doesn't support i64->FP operations.
17576  if (Op0.getOpcode() == ISD::LOAD) {
17577    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17578    EVT VT = Ld->getValueType(0);
17579    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17580        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17581        !XTLI->getSubtarget()->is64Bit() &&
17582        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17583      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17584                                          Ld->getChain(), Op0, DAG);
17585      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17586      return FILDChain;
17587    }
17588  }
17589  return SDValue();
17590}
17591
17592// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17593static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17594                                 X86TargetLowering::DAGCombinerInfo &DCI) {
17595  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17596  // the result is either zero or one (depending on the input carry bit).
17597  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17598  if (X86::isZeroNode(N->getOperand(0)) &&
17599      X86::isZeroNode(N->getOperand(1)) &&
17600      // We don't have a good way to replace an EFLAGS use, so only do this when
17601      // dead right now.
17602      SDValue(N, 1).use_empty()) {
17603    DebugLoc DL = N->getDebugLoc();
17604    EVT VT = N->getValueType(0);
17605    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17606    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17607                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17608                                           DAG.getConstant(X86::COND_B,MVT::i8),
17609                                           N->getOperand(2)),
17610                               DAG.getConstant(1, VT));
17611    return DCI.CombineTo(N, Res1, CarryOut);
17612  }
17613
17614  return SDValue();
17615}
17616
17617// fold (add Y, (sete  X, 0)) -> adc  0, Y
17618//      (add Y, (setne X, 0)) -> sbb -1, Y
17619//      (sub (sete  X, 0), Y) -> sbb  0, Y
17620//      (sub (setne X, 0), Y) -> adc -1, Y
17621static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17622  DebugLoc DL = N->getDebugLoc();
17623
17624  // Look through ZExts.
17625  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17626  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17627    return SDValue();
17628
17629  SDValue SetCC = Ext.getOperand(0);
17630  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17631    return SDValue();
17632
17633  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17634  if (CC != X86::COND_E && CC != X86::COND_NE)
17635    return SDValue();
17636
17637  SDValue Cmp = SetCC.getOperand(1);
17638  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17639      !X86::isZeroNode(Cmp.getOperand(1)) ||
17640      !Cmp.getOperand(0).getValueType().isInteger())
17641    return SDValue();
17642
17643  SDValue CmpOp0 = Cmp.getOperand(0);
17644  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17645                               DAG.getConstant(1, CmpOp0.getValueType()));
17646
17647  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17648  if (CC == X86::COND_NE)
17649    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17650                       DL, OtherVal.getValueType(), OtherVal,
17651                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17652  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17653                     DL, OtherVal.getValueType(), OtherVal,
17654                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17655}
17656
17657/// PerformADDCombine - Do target-specific dag combines on integer adds.
17658static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17659                                 const X86Subtarget *Subtarget) {
17660  EVT VT = N->getValueType(0);
17661  SDValue Op0 = N->getOperand(0);
17662  SDValue Op1 = N->getOperand(1);
17663
17664  // Try to synthesize horizontal adds from adds of shuffles.
17665  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17666       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17667      isHorizontalBinOp(Op0, Op1, true))
17668    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17669
17670  return OptimizeConditionalInDecrement(N, DAG);
17671}
17672
17673static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17674                                 const X86Subtarget *Subtarget) {
17675  SDValue Op0 = N->getOperand(0);
17676  SDValue Op1 = N->getOperand(1);
17677
17678  // X86 can't encode an immediate LHS of a sub. See if we can push the
17679  // negation into a preceding instruction.
17680  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17681    // If the RHS of the sub is a XOR with one use and a constant, invert the
17682    // immediate. Then add one to the LHS of the sub so we can turn
17683    // X-Y -> X+~Y+1, saving one register.
17684    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17685        isa<ConstantSDNode>(Op1.getOperand(1))) {
17686      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17687      EVT VT = Op0.getValueType();
17688      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17689                                   Op1.getOperand(0),
17690                                   DAG.getConstant(~XorC, VT));
17691      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17692                         DAG.getConstant(C->getAPIntValue()+1, VT));
17693    }
17694  }
17695
17696  // Try to synthesize horizontal adds from adds of shuffles.
17697  EVT VT = N->getValueType(0);
17698  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17699       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17700      isHorizontalBinOp(Op0, Op1, true))
17701    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17702
17703  return OptimizeConditionalInDecrement(N, DAG);
17704}
17705
17706/// performVZEXTCombine - Performs build vector combines
17707static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17708                                        TargetLowering::DAGCombinerInfo &DCI,
17709                                        const X86Subtarget *Subtarget) {
17710  // (vzext (bitcast (vzext (x)) -> (vzext x)
17711  SDValue In = N->getOperand(0);
17712  while (In.getOpcode() == ISD::BITCAST)
17713    In = In.getOperand(0);
17714
17715  if (In.getOpcode() != X86ISD::VZEXT)
17716    return SDValue();
17717
17718  return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17719                     In.getOperand(0));
17720}
17721
17722SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17723                                             DAGCombinerInfo &DCI) const {
17724  SelectionDAG &DAG = DCI.DAG;
17725  switch (N->getOpcode()) {
17726  default: break;
17727  case ISD::EXTRACT_VECTOR_ELT:
17728    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17729  case ISD::VSELECT:
17730  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17731  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17732  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17733  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17734  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17735  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17736  case ISD::SHL:
17737  case ISD::SRA:
17738  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17739  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17740  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17741  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17742  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17743  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17744  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17745  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17746  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17747  case X86ISD::FXOR:
17748  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17749  case X86ISD::FMIN:
17750  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17751  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17752  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17753  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17754  case ISD::ANY_EXTEND:
17755  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17756  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17757  case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17758  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17759  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17760  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17761  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17762  case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17763  case X86ISD::SHUFP:       // Handle all target specific shuffles
17764  case X86ISD::PALIGNR:
17765  case X86ISD::UNPCKH:
17766  case X86ISD::UNPCKL:
17767  case X86ISD::MOVHLPS:
17768  case X86ISD::MOVLHPS:
17769  case X86ISD::PSHUFD:
17770  case X86ISD::PSHUFHW:
17771  case X86ISD::PSHUFLW:
17772  case X86ISD::MOVSS:
17773  case X86ISD::MOVSD:
17774  case X86ISD::VPERMILP:
17775  case X86ISD::VPERM2X128:
17776  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17777  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17778  }
17779
17780  return SDValue();
17781}
17782
17783/// isTypeDesirableForOp - Return true if the target has native support for
17784/// the specified value type and it is 'desirable' to use the type for the
17785/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17786/// instruction encodings are longer and some i16 instructions are slow.
17787bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17788  if (!isTypeLegal(VT))
17789    return false;
17790  if (VT != MVT::i16)
17791    return true;
17792
17793  switch (Opc) {
17794  default:
17795    return true;
17796  case ISD::LOAD:
17797  case ISD::SIGN_EXTEND:
17798  case ISD::ZERO_EXTEND:
17799  case ISD::ANY_EXTEND:
17800  case ISD::SHL:
17801  case ISD::SRL:
17802  case ISD::SUB:
17803  case ISD::ADD:
17804  case ISD::MUL:
17805  case ISD::AND:
17806  case ISD::OR:
17807  case ISD::XOR:
17808    return false;
17809  }
17810}
17811
17812/// IsDesirableToPromoteOp - This method query the target whether it is
17813/// beneficial for dag combiner to promote the specified node. If true, it
17814/// should return the desired promotion type by reference.
17815bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17816  EVT VT = Op.getValueType();
17817  if (VT != MVT::i16)
17818    return false;
17819
17820  bool Promote = false;
17821  bool Commute = false;
17822  switch (Op.getOpcode()) {
17823  default: break;
17824  case ISD::LOAD: {
17825    LoadSDNode *LD = cast<LoadSDNode>(Op);
17826    // If the non-extending load has a single use and it's not live out, then it
17827    // might be folded.
17828    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17829                                                     Op.hasOneUse()*/) {
17830      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17831             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17832        // The only case where we'd want to promote LOAD (rather then it being
17833        // promoted as an operand is when it's only use is liveout.
17834        if (UI->getOpcode() != ISD::CopyToReg)
17835          return false;
17836      }
17837    }
17838    Promote = true;
17839    break;
17840  }
17841  case ISD::SIGN_EXTEND:
17842  case ISD::ZERO_EXTEND:
17843  case ISD::ANY_EXTEND:
17844    Promote = true;
17845    break;
17846  case ISD::SHL:
17847  case ISD::SRL: {
17848    SDValue N0 = Op.getOperand(0);
17849    // Look out for (store (shl (load), x)).
17850    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17851      return false;
17852    Promote = true;
17853    break;
17854  }
17855  case ISD::ADD:
17856  case ISD::MUL:
17857  case ISD::AND:
17858  case ISD::OR:
17859  case ISD::XOR:
17860    Commute = true;
17861    // fallthrough
17862  case ISD::SUB: {
17863    SDValue N0 = Op.getOperand(0);
17864    SDValue N1 = Op.getOperand(1);
17865    if (!Commute && MayFoldLoad(N1))
17866      return false;
17867    // Avoid disabling potential load folding opportunities.
17868    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17869      return false;
17870    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17871      return false;
17872    Promote = true;
17873  }
17874  }
17875
17876  PVT = MVT::i32;
17877  return Promote;
17878}
17879
17880//===----------------------------------------------------------------------===//
17881//                           X86 Inline Assembly Support
17882//===----------------------------------------------------------------------===//
17883
17884namespace {
17885  // Helper to match a string separated by whitespace.
17886  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17887    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17888
17889    for (unsigned i = 0, e = args.size(); i != e; ++i) {
17890      StringRef piece(*args[i]);
17891      if (!s.startswith(piece)) // Check if the piece matches.
17892        return false;
17893
17894      s = s.substr(piece.size());
17895      StringRef::size_type pos = s.find_first_not_of(" \t");
17896      if (pos == 0) // We matched a prefix.
17897        return false;
17898
17899      s = s.substr(pos);
17900    }
17901
17902    return s.empty();
17903  }
17904  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17905}
17906
17907bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17908  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17909
17910  std::string AsmStr = IA->getAsmString();
17911
17912  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17913  if (!Ty || Ty->getBitWidth() % 16 != 0)
17914    return false;
17915
17916  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17917  SmallVector<StringRef, 4> AsmPieces;
17918  SplitString(AsmStr, AsmPieces, ";\n");
17919
17920  switch (AsmPieces.size()) {
17921  default: return false;
17922  case 1:
17923    // FIXME: this should verify that we are targeting a 486 or better.  If not,
17924    // we will turn this bswap into something that will be lowered to logical
17925    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17926    // lower so don't worry about this.
17927    // bswap $0
17928    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17929        matchAsm(AsmPieces[0], "bswapl", "$0") ||
17930        matchAsm(AsmPieces[0], "bswapq", "$0") ||
17931        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17932        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17933        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17934      // No need to check constraints, nothing other than the equivalent of
17935      // "=r,0" would be valid here.
17936      return IntrinsicLowering::LowerToByteSwap(CI);
17937    }
17938
17939    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17940    if (CI->getType()->isIntegerTy(16) &&
17941        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17942        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17943         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17944      AsmPieces.clear();
17945      const std::string &ConstraintsStr = IA->getConstraintString();
17946      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17947      array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17948      if (AsmPieces.size() == 4 &&
17949          AsmPieces[0] == "~{cc}" &&
17950          AsmPieces[1] == "~{dirflag}" &&
17951          AsmPieces[2] == "~{flags}" &&
17952          AsmPieces[3] == "~{fpsr}")
17953      return IntrinsicLowering::LowerToByteSwap(CI);
17954    }
17955    break;
17956  case 3:
17957    if (CI->getType()->isIntegerTy(32) &&
17958        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17959        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17960        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17961        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17962      AsmPieces.clear();
17963      const std::string &ConstraintsStr = IA->getConstraintString();
17964      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17965      array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17966      if (AsmPieces.size() == 4 &&
17967          AsmPieces[0] == "~{cc}" &&
17968          AsmPieces[1] == "~{dirflag}" &&
17969          AsmPieces[2] == "~{flags}" &&
17970          AsmPieces[3] == "~{fpsr}")
17971        return IntrinsicLowering::LowerToByteSwap(CI);
17972    }
17973
17974    if (CI->getType()->isIntegerTy(64)) {
17975      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17976      if (Constraints.size() >= 2 &&
17977          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17978          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17979        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17980        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17981            matchAsm(AsmPieces[1], "bswap", "%edx") &&
17982            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17983          return IntrinsicLowering::LowerToByteSwap(CI);
17984      }
17985    }
17986    break;
17987  }
17988  return false;
17989}
17990
17991/// getConstraintType - Given a constraint letter, return the type of
17992/// constraint it is for this target.
17993X86TargetLowering::ConstraintType
17994X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17995  if (Constraint.size() == 1) {
17996    switch (Constraint[0]) {
17997    case 'R':
17998    case 'q':
17999    case 'Q':
18000    case 'f':
18001    case 't':
18002    case 'u':
18003    case 'y':
18004    case 'x':
18005    case 'Y':
18006    case 'l':
18007      return C_RegisterClass;
18008    case 'a':
18009    case 'b':
18010    case 'c':
18011    case 'd':
18012    case 'S':
18013    case 'D':
18014    case 'A':
18015      return C_Register;
18016    case 'I':
18017    case 'J':
18018    case 'K':
18019    case 'L':
18020    case 'M':
18021    case 'N':
18022    case 'G':
18023    case 'C':
18024    case 'e':
18025    case 'Z':
18026      return C_Other;
18027    default:
18028      break;
18029    }
18030  }
18031  return TargetLowering::getConstraintType(Constraint);
18032}
18033
18034/// Examine constraint type and operand type and determine a weight value.
18035/// This object must already have been set up with the operand type
18036/// and the current alternative constraint selected.
18037TargetLowering::ConstraintWeight
18038  X86TargetLowering::getSingleConstraintMatchWeight(
18039    AsmOperandInfo &info, const char *constraint) const {
18040  ConstraintWeight weight = CW_Invalid;
18041  Value *CallOperandVal = info.CallOperandVal;
18042    // If we don't have a value, we can't do a match,
18043    // but allow it at the lowest weight.
18044  if (CallOperandVal == NULL)
18045    return CW_Default;
18046  Type *type = CallOperandVal->getType();
18047  // Look at the constraint type.
18048  switch (*constraint) {
18049  default:
18050    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18051  case 'R':
18052  case 'q':
18053  case 'Q':
18054  case 'a':
18055  case 'b':
18056  case 'c':
18057  case 'd':
18058  case 'S':
18059  case 'D':
18060  case 'A':
18061    if (CallOperandVal->getType()->isIntegerTy())
18062      weight = CW_SpecificReg;
18063    break;
18064  case 'f':
18065  case 't':
18066  case 'u':
18067    if (type->isFloatingPointTy())
18068      weight = CW_SpecificReg;
18069    break;
18070  case 'y':
18071    if (type->isX86_MMXTy() && Subtarget->hasMMX())
18072      weight = CW_SpecificReg;
18073    break;
18074  case 'x':
18075  case 'Y':
18076    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18077        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18078      weight = CW_Register;
18079    break;
18080  case 'I':
18081    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18082      if (C->getZExtValue() <= 31)
18083        weight = CW_Constant;
18084    }
18085    break;
18086  case 'J':
18087    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18088      if (C->getZExtValue() <= 63)
18089        weight = CW_Constant;
18090    }
18091    break;
18092  case 'K':
18093    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18094      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18095        weight = CW_Constant;
18096    }
18097    break;
18098  case 'L':
18099    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18100      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18101        weight = CW_Constant;
18102    }
18103    break;
18104  case 'M':
18105    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18106      if (C->getZExtValue() <= 3)
18107        weight = CW_Constant;
18108    }
18109    break;
18110  case 'N':
18111    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18112      if (C->getZExtValue() <= 0xff)
18113        weight = CW_Constant;
18114    }
18115    break;
18116  case 'G':
18117  case 'C':
18118    if (dyn_cast<ConstantFP>(CallOperandVal)) {
18119      weight = CW_Constant;
18120    }
18121    break;
18122  case 'e':
18123    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18124      if ((C->getSExtValue() >= -0x80000000LL) &&
18125          (C->getSExtValue() <= 0x7fffffffLL))
18126        weight = CW_Constant;
18127    }
18128    break;
18129  case 'Z':
18130    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18131      if (C->getZExtValue() <= 0xffffffff)
18132        weight = CW_Constant;
18133    }
18134    break;
18135  }
18136  return weight;
18137}
18138
18139/// LowerXConstraint - try to replace an X constraint, which matches anything,
18140/// with another that has more specific requirements based on the type of the
18141/// corresponding operand.
18142const char *X86TargetLowering::
18143LowerXConstraint(EVT ConstraintVT) const {
18144  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18145  // 'f' like normal targets.
18146  if (ConstraintVT.isFloatingPoint()) {
18147    if (Subtarget->hasSSE2())
18148      return "Y";
18149    if (Subtarget->hasSSE1())
18150      return "x";
18151  }
18152
18153  return TargetLowering::LowerXConstraint(ConstraintVT);
18154}
18155
18156/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18157/// vector.  If it is invalid, don't add anything to Ops.
18158void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18159                                                     std::string &Constraint,
18160                                                     std::vector<SDValue>&Ops,
18161                                                     SelectionDAG &DAG) const {
18162  SDValue Result(0, 0);
18163
18164  // Only support length 1 constraints for now.
18165  if (Constraint.length() > 1) return;
18166
18167  char ConstraintLetter = Constraint[0];
18168  switch (ConstraintLetter) {
18169  default: break;
18170  case 'I':
18171    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18172      if (C->getZExtValue() <= 31) {
18173        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18174        break;
18175      }
18176    }
18177    return;
18178  case 'J':
18179    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18180      if (C->getZExtValue() <= 63) {
18181        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18182        break;
18183      }
18184    }
18185    return;
18186  case 'K':
18187    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18188      if (isInt<8>(C->getSExtValue())) {
18189        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18190        break;
18191      }
18192    }
18193    return;
18194  case 'N':
18195    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18196      if (C->getZExtValue() <= 255) {
18197        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18198        break;
18199      }
18200    }
18201    return;
18202  case 'e': {
18203    // 32-bit signed value
18204    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18205      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18206                                           C->getSExtValue())) {
18207        // Widen to 64 bits here to get it sign extended.
18208        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18209        break;
18210      }
18211    // FIXME gcc accepts some relocatable values here too, but only in certain
18212    // memory models; it's complicated.
18213    }
18214    return;
18215  }
18216  case 'Z': {
18217    // 32-bit unsigned value
18218    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18219      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18220                                           C->getZExtValue())) {
18221        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18222        break;
18223      }
18224    }
18225    // FIXME gcc accepts some relocatable values here too, but only in certain
18226    // memory models; it's complicated.
18227    return;
18228  }
18229  case 'i': {
18230    // Literal immediates are always ok.
18231    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18232      // Widen to 64 bits here to get it sign extended.
18233      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18234      break;
18235    }
18236
18237    // In any sort of PIC mode addresses need to be computed at runtime by
18238    // adding in a register or some sort of table lookup.  These can't
18239    // be used as immediates.
18240    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18241      return;
18242
18243    // If we are in non-pic codegen mode, we allow the address of a global (with
18244    // an optional displacement) to be used with 'i'.
18245    GlobalAddressSDNode *GA = 0;
18246    int64_t Offset = 0;
18247
18248    // Match either (GA), (GA+C), (GA+C1+C2), etc.
18249    while (1) {
18250      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18251        Offset += GA->getOffset();
18252        break;
18253      } else if (Op.getOpcode() == ISD::ADD) {
18254        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18255          Offset += C->getZExtValue();
18256          Op = Op.getOperand(0);
18257          continue;
18258        }
18259      } else if (Op.getOpcode() == ISD::SUB) {
18260        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18261          Offset += -C->getZExtValue();
18262          Op = Op.getOperand(0);
18263          continue;
18264        }
18265      }
18266
18267      // Otherwise, this isn't something we can handle, reject it.
18268      return;
18269    }
18270
18271    const GlobalValue *GV = GA->getGlobal();
18272    // If we require an extra load to get this address, as in PIC mode, we
18273    // can't accept it.
18274    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18275                                                        getTargetMachine())))
18276      return;
18277
18278    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18279                                        GA->getValueType(0), Offset);
18280    break;
18281  }
18282  }
18283
18284  if (Result.getNode()) {
18285    Ops.push_back(Result);
18286    return;
18287  }
18288  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18289}
18290
18291std::pair<unsigned, const TargetRegisterClass*>
18292X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18293                                                EVT VT) const {
18294  // First, see if this is a constraint that directly corresponds to an LLVM
18295  // register class.
18296  if (Constraint.size() == 1) {
18297    // GCC Constraint Letters
18298    switch (Constraint[0]) {
18299    default: break;
18300      // TODO: Slight differences here in allocation order and leaving
18301      // RIP in the class. Do they matter any more here than they do
18302      // in the normal allocation?
18303    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18304      if (Subtarget->is64Bit()) {
18305        if (VT == MVT::i32 || VT == MVT::f32)
18306          return std::make_pair(0U, &X86::GR32RegClass);
18307        if (VT == MVT::i16)
18308          return std::make_pair(0U, &X86::GR16RegClass);
18309        if (VT == MVT::i8 || VT == MVT::i1)
18310          return std::make_pair(0U, &X86::GR8RegClass);
18311        if (VT == MVT::i64 || VT == MVT::f64)
18312          return std::make_pair(0U, &X86::GR64RegClass);
18313        break;
18314      }
18315      // 32-bit fallthrough
18316    case 'Q':   // Q_REGS
18317      if (VT == MVT::i32 || VT == MVT::f32)
18318        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18319      if (VT == MVT::i16)
18320        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18321      if (VT == MVT::i8 || VT == MVT::i1)
18322        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18323      if (VT == MVT::i64)
18324        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18325      break;
18326    case 'r':   // GENERAL_REGS
18327    case 'l':   // INDEX_REGS
18328      if (VT == MVT::i8 || VT == MVT::i1)
18329        return std::make_pair(0U, &X86::GR8RegClass);
18330      if (VT == MVT::i16)
18331        return std::make_pair(0U, &X86::GR16RegClass);
18332      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18333        return std::make_pair(0U, &X86::GR32RegClass);
18334      return std::make_pair(0U, &X86::GR64RegClass);
18335    case 'R':   // LEGACY_REGS
18336      if (VT == MVT::i8 || VT == MVT::i1)
18337        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18338      if (VT == MVT::i16)
18339        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18340      if (VT == MVT::i32 || !Subtarget->is64Bit())
18341        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18342      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18343    case 'f':  // FP Stack registers.
18344      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18345      // value to the correct fpstack register class.
18346      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18347        return std::make_pair(0U, &X86::RFP32RegClass);
18348      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18349        return std::make_pair(0U, &X86::RFP64RegClass);
18350      return std::make_pair(0U, &X86::RFP80RegClass);
18351    case 'y':   // MMX_REGS if MMX allowed.
18352      if (!Subtarget->hasMMX()) break;
18353      return std::make_pair(0U, &X86::VR64RegClass);
18354    case 'Y':   // SSE_REGS if SSE2 allowed
18355      if (!Subtarget->hasSSE2()) break;
18356      // FALL THROUGH.
18357    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18358      if (!Subtarget->hasSSE1()) break;
18359
18360      switch (VT.getSimpleVT().SimpleTy) {
18361      default: break;
18362      // Scalar SSE types.
18363      case MVT::f32:
18364      case MVT::i32:
18365        return std::make_pair(0U, &X86::FR32RegClass);
18366      case MVT::f64:
18367      case MVT::i64:
18368        return std::make_pair(0U, &X86::FR64RegClass);
18369      // Vector types.
18370      case MVT::v16i8:
18371      case MVT::v8i16:
18372      case MVT::v4i32:
18373      case MVT::v2i64:
18374      case MVT::v4f32:
18375      case MVT::v2f64:
18376        return std::make_pair(0U, &X86::VR128RegClass);
18377      // AVX types.
18378      case MVT::v32i8:
18379      case MVT::v16i16:
18380      case MVT::v8i32:
18381      case MVT::v4i64:
18382      case MVT::v8f32:
18383      case MVT::v4f64:
18384        return std::make_pair(0U, &X86::VR256RegClass);
18385      }
18386      break;
18387    }
18388  }
18389
18390  // Use the default implementation in TargetLowering to convert the register
18391  // constraint into a member of a register class.
18392  std::pair<unsigned, const TargetRegisterClass*> Res;
18393  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18394
18395  // Not found as a standard register?
18396  if (Res.second == 0) {
18397    // Map st(0) -> st(7) -> ST0
18398    if (Constraint.size() == 7 && Constraint[0] == '{' &&
18399        tolower(Constraint[1]) == 's' &&
18400        tolower(Constraint[2]) == 't' &&
18401        Constraint[3] == '(' &&
18402        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18403        Constraint[5] == ')' &&
18404        Constraint[6] == '}') {
18405
18406      Res.first = X86::ST0+Constraint[4]-'0';
18407      Res.second = &X86::RFP80RegClass;
18408      return Res;
18409    }
18410
18411    // GCC allows "st(0)" to be called just plain "st".
18412    if (StringRef("{st}").equals_lower(Constraint)) {
18413      Res.first = X86::ST0;
18414      Res.second = &X86::RFP80RegClass;
18415      return Res;
18416    }
18417
18418    // flags -> EFLAGS
18419    if (StringRef("{flags}").equals_lower(Constraint)) {
18420      Res.first = X86::EFLAGS;
18421      Res.second = &X86::CCRRegClass;
18422      return Res;
18423    }
18424
18425    // 'A' means EAX + EDX.
18426    if (Constraint == "A") {
18427      Res.first = X86::EAX;
18428      Res.second = &X86::GR32_ADRegClass;
18429      return Res;
18430    }
18431    return Res;
18432  }
18433
18434  // Otherwise, check to see if this is a register class of the wrong value
18435  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18436  // turn into {ax},{dx}.
18437  if (Res.second->hasType(VT))
18438    return Res;   // Correct type already, nothing to do.
18439
18440  // All of the single-register GCC register classes map their values onto
18441  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18442  // really want an 8-bit or 32-bit register, map to the appropriate register
18443  // class and return the appropriate register.
18444  if (Res.second == &X86::GR16RegClass) {
18445    if (VT == MVT::i8 || VT == MVT::i1) {
18446      unsigned DestReg = 0;
18447      switch (Res.first) {
18448      default: break;
18449      case X86::AX: DestReg = X86::AL; break;
18450      case X86::DX: DestReg = X86::DL; break;
18451      case X86::CX: DestReg = X86::CL; break;
18452      case X86::BX: DestReg = X86::BL; break;
18453      }
18454      if (DestReg) {
18455        Res.first = DestReg;
18456        Res.second = &X86::GR8RegClass;
18457      }
18458    } else if (VT == MVT::i32 || VT == MVT::f32) {
18459      unsigned DestReg = 0;
18460      switch (Res.first) {
18461      default: break;
18462      case X86::AX: DestReg = X86::EAX; break;
18463      case X86::DX: DestReg = X86::EDX; break;
18464      case X86::CX: DestReg = X86::ECX; break;
18465      case X86::BX: DestReg = X86::EBX; break;
18466      case X86::SI: DestReg = X86::ESI; break;
18467      case X86::DI: DestReg = X86::EDI; break;
18468      case X86::BP: DestReg = X86::EBP; break;
18469      case X86::SP: DestReg = X86::ESP; break;
18470      }
18471      if (DestReg) {
18472        Res.first = DestReg;
18473        Res.second = &X86::GR32RegClass;
18474      }
18475    } else if (VT == MVT::i64 || VT == MVT::f64) {
18476      unsigned DestReg = 0;
18477      switch (Res.first) {
18478      default: break;
18479      case X86::AX: DestReg = X86::RAX; break;
18480      case X86::DX: DestReg = X86::RDX; break;
18481      case X86::CX: DestReg = X86::RCX; break;
18482      case X86::BX: DestReg = X86::RBX; break;
18483      case X86::SI: DestReg = X86::RSI; break;
18484      case X86::DI: DestReg = X86::RDI; break;
18485      case X86::BP: DestReg = X86::RBP; break;
18486      case X86::SP: DestReg = X86::RSP; break;
18487      }
18488      if (DestReg) {
18489        Res.first = DestReg;
18490        Res.second = &X86::GR64RegClass;
18491      }
18492    }
18493  } else if (Res.second == &X86::FR32RegClass ||
18494             Res.second == &X86::FR64RegClass ||
18495             Res.second == &X86::VR128RegClass) {
18496    // Handle references to XMM physical registers that got mapped into the
18497    // wrong class.  This can happen with constraints like {xmm0} where the
18498    // target independent register mapper will just pick the first match it can
18499    // find, ignoring the required type.
18500
18501    if (VT == MVT::f32 || VT == MVT::i32)
18502      Res.second = &X86::FR32RegClass;
18503    else if (VT == MVT::f64 || VT == MVT::i64)
18504      Res.second = &X86::FR64RegClass;
18505    else if (X86::VR128RegClass.hasType(VT))
18506      Res.second = &X86::VR128RegClass;
18507    else if (X86::VR256RegClass.hasType(VT))
18508      Res.second = &X86::VR256RegClass;
18509  }
18510
18511  return Res;
18512}
18513