X86ISelLowering.cpp revision 0ee17006b1b65204ab95360b98d04304bf206c59
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  RegInfo = TM.getRegisterInfo();
167  TD = getDataLayout();
168
169  resetOperationActions();
170}
171
172void X86TargetLowering::resetOperationActions() {
173  const TargetMachine &TM = getTargetMachine();
174  static bool FirstTimeThrough = true;
175
176  // If none of the target options have changed, then we don't need to reset the
177  // operation actions.
178  if (!FirstTimeThrough && TO == TM.Options) return;
179
180  if (!FirstTimeThrough) {
181    // Reinitialize the actions.
182    initActions();
183    FirstTimeThrough = false;
184  }
185
186  TO = TM.Options;
187
188  // Set up the TargetLowering object.
189  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
190
191  // X86 is weird, it always uses i8 for shift amounts and setcc results.
192  setBooleanContents(ZeroOrOneBooleanContent);
193  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
194  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
195
196  // For 64-bit since we have so many registers use the ILP scheduler, for
197  // 32-bit code use the register pressure specific scheduling.
198  // For Atom, always use ILP scheduling.
199  if (Subtarget->isAtom())
200    setSchedulingPreference(Sched::ILP);
201  else if (Subtarget->is64Bit())
202    setSchedulingPreference(Sched::ILP);
203  else
204    setSchedulingPreference(Sched::RegPressure);
205  setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
206
207  // Bypass expensive divides on Atom when compiling with O2
208  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
209    addBypassSlowDiv(32, 8);
210    if (Subtarget->is64Bit())
211      addBypassSlowDiv(64, 16);
212  }
213
214  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
215    // Setup Windows compiler runtime calls.
216    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
217    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
218    setLibcallName(RTLIB::SREM_I64, "_allrem");
219    setLibcallName(RTLIB::UREM_I64, "_aullrem");
220    setLibcallName(RTLIB::MUL_I64, "_allmul");
221    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
222    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
223    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
224    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
225    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
226
227    // The _ftol2 runtime function has an unusual calling conv, which
228    // is modeled by a special pseudo-instruction.
229    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
230    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
231    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
232    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
233  }
234
235  if (Subtarget->isTargetDarwin()) {
236    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
237    setUseUnderscoreSetJmp(false);
238    setUseUnderscoreLongJmp(false);
239  } else if (Subtarget->isTargetMingw()) {
240    // MS runtime is weird: it exports _setjmp, but longjmp!
241    setUseUnderscoreSetJmp(true);
242    setUseUnderscoreLongJmp(false);
243  } else {
244    setUseUnderscoreSetJmp(true);
245    setUseUnderscoreLongJmp(true);
246  }
247
248  // Set up the register classes.
249  addRegisterClass(MVT::i8, &X86::GR8RegClass);
250  addRegisterClass(MVT::i16, &X86::GR16RegClass);
251  addRegisterClass(MVT::i32, &X86::GR32RegClass);
252  if (Subtarget->is64Bit())
253    addRegisterClass(MVT::i64, &X86::GR64RegClass);
254
255  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
256
257  // We don't accept any truncstore of integer registers.
258  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
259  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
260  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
261  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
262  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
263  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
264
265  // SETOEQ and SETUNE require checking two conditions.
266  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
267  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
268  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
269  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
270  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
271  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
272
273  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
274  // operation.
275  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
276  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
277  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
278
279  if (Subtarget->is64Bit()) {
280    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
281    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
282  } else if (!TM.Options.UseSoftFloat) {
283    // We have an algorithm for SSE2->double, and we turn this into a
284    // 64-bit FILD followed by conditional FADD for other targets.
285    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
286    // We have an algorithm for SSE2, and we turn this into a 64-bit
287    // FILD for other targets.
288    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
289  }
290
291  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
292  // this operation.
293  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
294  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
295
296  if (!TM.Options.UseSoftFloat) {
297    // SSE has no i16 to fp conversion, only i32
298    if (X86ScalarSSEf32) {
299      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
300      // f32 and f64 cases are Legal, f80 case is not
301      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
302    } else {
303      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
304      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
305    }
306  } else {
307    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
308    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
309  }
310
311  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
312  // are Legal, f80 is custom lowered.
313  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
314  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
315
316  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
317  // this operation.
318  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
319  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
320
321  if (X86ScalarSSEf32) {
322    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
323    // f32 and f64 cases are Legal, f80 case is not
324    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
325  } else {
326    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
327    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
328  }
329
330  // Handle FP_TO_UINT by promoting the destination to a larger signed
331  // conversion.
332  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
333  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
334  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
335
336  if (Subtarget->is64Bit()) {
337    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
338    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
339  } else if (!TM.Options.UseSoftFloat) {
340    // Since AVX is a superset of SSE3, only check for SSE here.
341    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
342      // Expand FP_TO_UINT into a select.
343      // FIXME: We would like to use a Custom expander here eventually to do
344      // the optimal thing for SSE vs. the default expansion in the legalizer.
345      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
346    else
347      // With SSE3 we can use fisttpll to convert to a signed i64; without
348      // SSE, we're stuck with a fistpll.
349      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
350  }
351
352  if (isTargetFTOL()) {
353    // Use the _ftol2 runtime function, which has a pseudo-instruction
354    // to handle its weird calling convention.
355    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
356  }
357
358  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
359  if (!X86ScalarSSEf64) {
360    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
361    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
362    if (Subtarget->is64Bit()) {
363      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
364      // Without SSE, i64->f64 goes through memory.
365      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
366    }
367  }
368
369  // Scalar integer divide and remainder are lowered to use operations that
370  // produce two results, to match the available instructions. This exposes
371  // the two-result form to trivial CSE, which is able to combine x/y and x%y
372  // into a single instruction.
373  //
374  // Scalar integer multiply-high is also lowered to use two-result
375  // operations, to match the available instructions. However, plain multiply
376  // (low) operations are left as Legal, as there are single-result
377  // instructions for this in x86. Using the two-result multiply instructions
378  // when both high and low results are needed must be arranged by dagcombine.
379  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
380    MVT VT = IntVTs[i];
381    setOperationAction(ISD::MULHS, VT, Expand);
382    setOperationAction(ISD::MULHU, VT, Expand);
383    setOperationAction(ISD::SDIV, VT, Expand);
384    setOperationAction(ISD::UDIV, VT, Expand);
385    setOperationAction(ISD::SREM, VT, Expand);
386    setOperationAction(ISD::UREM, VT, Expand);
387
388    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
389    setOperationAction(ISD::ADDC, VT, Custom);
390    setOperationAction(ISD::ADDE, VT, Custom);
391    setOperationAction(ISD::SUBC, VT, Custom);
392    setOperationAction(ISD::SUBE, VT, Custom);
393  }
394
395  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
396  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
397  setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
398  setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
399  setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
400  setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
401  setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
402  setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
403  setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
404  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
405  if (Subtarget->is64Bit())
406    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
407  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
408  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
409  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
410  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
411  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
412  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
413  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
414  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
415
416  // Promote the i8 variants and force them on up to i32 which has a shorter
417  // encoding.
418  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
419  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
420  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
421  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
422  if (Subtarget->hasBMI()) {
423    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
424    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
425    if (Subtarget->is64Bit())
426      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
427  } else {
428    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
429    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
430    if (Subtarget->is64Bit())
431      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
432  }
433
434  if (Subtarget->hasLZCNT()) {
435    // When promoting the i8 variants, force them to i32 for a shorter
436    // encoding.
437    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
438    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
439    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
440    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
441    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
442    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
443    if (Subtarget->is64Bit())
444      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
445  } else {
446    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
447    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
448    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
449    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
450    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
451    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
452    if (Subtarget->is64Bit()) {
453      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
454      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
455    }
456  }
457
458  if (Subtarget->hasPOPCNT()) {
459    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
460  } else {
461    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
462    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
463    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
464    if (Subtarget->is64Bit())
465      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
466  }
467
468  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
469  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
470
471  // These should be promoted to a larger select which is supported.
472  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
473  // X86 wants to expand cmov itself.
474  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
475  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
476  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
477  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
478  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
479  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
480  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
481  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
482  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
483  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
484  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
485  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
486  if (Subtarget->is64Bit()) {
487    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
488    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
489  }
490  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
491  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
492  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
493  // support continuation, user-level threading, and etc.. As a result, no
494  // other SjLj exception interfaces are implemented and please don't build
495  // your own exception handling based on them.
496  // LLVM/Clang supports zero-cost DWARF exception handling.
497  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
498  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
499
500  // Darwin ABI issue.
501  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
502  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
503  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
504  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
505  if (Subtarget->is64Bit())
506    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
507  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
508  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
509  if (Subtarget->is64Bit()) {
510    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
511    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
512    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
513    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
514    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
515  }
516  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
517  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
518  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
519  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
520  if (Subtarget->is64Bit()) {
521    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
522    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
523    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
524  }
525
526  if (Subtarget->hasSSE1())
527    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
528
529  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
530  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
531
532  // On X86 and X86-64, atomic operations are lowered to locked instructions.
533  // Locked instructions, in turn, have implicit fence semantics (all memory
534  // operations are flushed before issuing the locked instruction, and they
535  // are not buffered), so we can fold away the common pattern of
536  // fence-atomic-fence.
537  setShouldFoldAtomicFences(true);
538
539  // Expand certain atomics
540  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
541    MVT VT = IntVTs[i];
542    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
543    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
544    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
545  }
546
547  if (!Subtarget->is64Bit()) {
548    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
549    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
550    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
551    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
552    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
553    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
554    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
555    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
556    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
557    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
558    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
559    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
560  }
561
562  if (Subtarget->hasCmpxchg16b()) {
563    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
564  }
565
566  // FIXME - use subtarget debug flags
567  if (!Subtarget->isTargetDarwin() &&
568      !Subtarget->isTargetELF() &&
569      !Subtarget->isTargetCygMing()) {
570    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
571  }
572
573  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
574  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
575  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
576  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
577  if (Subtarget->is64Bit()) {
578    setExceptionPointerRegister(X86::RAX);
579    setExceptionSelectorRegister(X86::RDX);
580  } else {
581    setExceptionPointerRegister(X86::EAX);
582    setExceptionSelectorRegister(X86::EDX);
583  }
584  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
585  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
586
587  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
588  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
589
590  setOperationAction(ISD::TRAP, MVT::Other, Legal);
591  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
592
593  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
594  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
595  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
596  if (Subtarget->is64Bit()) {
597    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
598    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
599  } else {
600    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
601    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
602  }
603
604  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
605  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
606
607  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
608    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
609                       MVT::i64 : MVT::i32, Custom);
610  else if (TM.Options.EnableSegmentedStacks)
611    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
612                       MVT::i64 : MVT::i32, Custom);
613  else
614    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
615                       MVT::i64 : MVT::i32, Expand);
616
617  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
618    // f32 and f64 use SSE.
619    // Set up the FP register classes.
620    addRegisterClass(MVT::f32, &X86::FR32RegClass);
621    addRegisterClass(MVT::f64, &X86::FR64RegClass);
622
623    // Use ANDPD to simulate FABS.
624    setOperationAction(ISD::FABS , MVT::f64, Custom);
625    setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627    // Use XORP to simulate FNEG.
628    setOperationAction(ISD::FNEG , MVT::f64, Custom);
629    setOperationAction(ISD::FNEG , MVT::f32, Custom);
630
631    // Use ANDPD and ORPD to simulate FCOPYSIGN.
632    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
633    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635    // Lower this to FGETSIGNx86 plus an AND.
636    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
637    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
638
639    // We don't support sin/cos/fmod
640    setOperationAction(ISD::FSIN   , MVT::f64, Expand);
641    setOperationAction(ISD::FCOS   , MVT::f64, Expand);
642    setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
643    setOperationAction(ISD::FSIN   , MVT::f32, Expand);
644    setOperationAction(ISD::FCOS   , MVT::f32, Expand);
645    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
646
647    // Expand FP immediates into loads from the stack, except for the special
648    // cases we handle.
649    addLegalFPImmediate(APFloat(+0.0)); // xorpd
650    addLegalFPImmediate(APFloat(+0.0f)); // xorps
651  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
652    // Use SSE for f32, x87 for f64.
653    // Set up the FP register classes.
654    addRegisterClass(MVT::f32, &X86::FR32RegClass);
655    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
656
657    // Use ANDPS to simulate FABS.
658    setOperationAction(ISD::FABS , MVT::f32, Custom);
659
660    // Use XORP to simulate FNEG.
661    setOperationAction(ISD::FNEG , MVT::f32, Custom);
662
663    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
664
665    // Use ANDPS and ORPS to simulate FCOPYSIGN.
666    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
667    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
668
669    // We don't support sin/cos/fmod
670    setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671    setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674    // Special cases we handle for FP constants.
675    addLegalFPImmediate(APFloat(+0.0f)); // xorps
676    addLegalFPImmediate(APFloat(+0.0)); // FLD0
677    addLegalFPImmediate(APFloat(+1.0)); // FLD1
678    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
679    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
680
681    if (!TM.Options.UnsafeFPMath) {
682      setOperationAction(ISD::FSIN   , MVT::f64, Expand);
683      setOperationAction(ISD::FCOS   , MVT::f64, Expand);
684      setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
685    }
686  } else if (!TM.Options.UseSoftFloat) {
687    // f32 and f64 in x87.
688    // Set up the FP register classes.
689    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
690    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
691
692    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
693    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
694    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
696
697    if (!TM.Options.UnsafeFPMath) {
698      setOperationAction(ISD::FSIN   , MVT::f64, Expand);
699      setOperationAction(ISD::FSIN   , MVT::f32, Expand);
700      setOperationAction(ISD::FCOS   , MVT::f64, Expand);
701      setOperationAction(ISD::FCOS   , MVT::f32, Expand);
702      setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
703      setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704    }
705    addLegalFPImmediate(APFloat(+0.0)); // FLD0
706    addLegalFPImmediate(APFloat(+1.0)); // FLD1
707    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
710    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
711    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
712    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
713  }
714
715  // We don't support FMA.
716  setOperationAction(ISD::FMA, MVT::f64, Expand);
717  setOperationAction(ISD::FMA, MVT::f32, Expand);
718
719  // Long double always uses X87.
720  if (!TM.Options.UseSoftFloat) {
721    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
722    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
723    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
724    {
725      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
726      addLegalFPImmediate(TmpFlt);  // FLD0
727      TmpFlt.changeSign();
728      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
729
730      bool ignored;
731      APFloat TmpFlt2(+1.0);
732      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
733                      &ignored);
734      addLegalFPImmediate(TmpFlt2);  // FLD1
735      TmpFlt2.changeSign();
736      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
737    }
738
739    if (!TM.Options.UnsafeFPMath) {
740      setOperationAction(ISD::FSIN   , MVT::f80, Expand);
741      setOperationAction(ISD::FCOS   , MVT::f80, Expand);
742      setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
743    }
744
745    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
746    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
747    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
748    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
749    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
750    setOperationAction(ISD::FMA, MVT::f80, Expand);
751  }
752
753  // Always use a library call for pow.
754  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
755  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
756  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
757
758  setOperationAction(ISD::FLOG, MVT::f80, Expand);
759  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
760  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
761  setOperationAction(ISD::FEXP, MVT::f80, Expand);
762  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
763
764  // First set operation action for all vector types to either promote
765  // (for widening) or expand (for scalarization). Then we will selectively
766  // turn on ones that can be effectively codegen'd.
767  for (int i = MVT::FIRST_VECTOR_VALUETYPE;
768           i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
769    MVT VT = (MVT::SimpleValueType)i;
770    setOperationAction(ISD::ADD , VT, Expand);
771    setOperationAction(ISD::SUB , VT, Expand);
772    setOperationAction(ISD::FADD, VT, Expand);
773    setOperationAction(ISD::FNEG, VT, Expand);
774    setOperationAction(ISD::FSUB, VT, Expand);
775    setOperationAction(ISD::MUL , VT, Expand);
776    setOperationAction(ISD::FMUL, VT, Expand);
777    setOperationAction(ISD::SDIV, VT, Expand);
778    setOperationAction(ISD::UDIV, VT, Expand);
779    setOperationAction(ISD::FDIV, VT, Expand);
780    setOperationAction(ISD::SREM, VT, Expand);
781    setOperationAction(ISD::UREM, VT, Expand);
782    setOperationAction(ISD::LOAD, VT, Expand);
783    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
784    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
785    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
786    setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
787    setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
788    setOperationAction(ISD::FABS, VT, Expand);
789    setOperationAction(ISD::FSIN, VT, Expand);
790    setOperationAction(ISD::FSINCOS, VT, Expand);
791    setOperationAction(ISD::FCOS, VT, Expand);
792    setOperationAction(ISD::FSINCOS, VT, Expand);
793    setOperationAction(ISD::FREM, VT, Expand);
794    setOperationAction(ISD::FMA,  VT, Expand);
795    setOperationAction(ISD::FPOWI, VT, Expand);
796    setOperationAction(ISD::FSQRT, VT, Expand);
797    setOperationAction(ISD::FCOPYSIGN, VT, Expand);
798    setOperationAction(ISD::FFLOOR, VT, Expand);
799    setOperationAction(ISD::FCEIL, VT, Expand);
800    setOperationAction(ISD::FTRUNC, VT, Expand);
801    setOperationAction(ISD::FRINT, VT, Expand);
802    setOperationAction(ISD::FNEARBYINT, VT, Expand);
803    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
804    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
805    setOperationAction(ISD::SDIVREM, VT, Expand);
806    setOperationAction(ISD::UDIVREM, VT, Expand);
807    setOperationAction(ISD::FPOW, VT, Expand);
808    setOperationAction(ISD::CTPOP, VT, Expand);
809    setOperationAction(ISD::CTTZ, VT, Expand);
810    setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
811    setOperationAction(ISD::CTLZ, VT, Expand);
812    setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
813    setOperationAction(ISD::SHL, VT, Expand);
814    setOperationAction(ISD::SRA, VT, Expand);
815    setOperationAction(ISD::SRL, VT, Expand);
816    setOperationAction(ISD::ROTL, VT, Expand);
817    setOperationAction(ISD::ROTR, VT, Expand);
818    setOperationAction(ISD::BSWAP, VT, Expand);
819    setOperationAction(ISD::SETCC, VT, Expand);
820    setOperationAction(ISD::FLOG, VT, Expand);
821    setOperationAction(ISD::FLOG2, VT, Expand);
822    setOperationAction(ISD::FLOG10, VT, Expand);
823    setOperationAction(ISD::FEXP, VT, Expand);
824    setOperationAction(ISD::FEXP2, VT, Expand);
825    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
826    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
827    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
828    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
829    setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
830    setOperationAction(ISD::TRUNCATE, VT, Expand);
831    setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
832    setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
833    setOperationAction(ISD::ANY_EXTEND, VT, Expand);
834    setOperationAction(ISD::VSELECT, VT, Expand);
835    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
836             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
837      setTruncStoreAction(VT,
838                          (MVT::SimpleValueType)InnerVT, Expand);
839    setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
840    setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
841    setLoadExtAction(ISD::EXTLOAD, VT, Expand);
842  }
843
844  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
845  // with -msoft-float, disable use of MMX as well.
846  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
847    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
848    // No operations on x86mmx supported, everything uses intrinsics.
849  }
850
851  // MMX-sized vectors (other than x86mmx) are expected to be expanded
852  // into smaller operations.
853  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
854  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
855  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
856  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
857  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
858  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
859  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
860  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
861  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
862  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
863  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
864  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
865  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
866  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
867  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
868  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
869  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
870  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
871  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
872  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
873  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
874  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
875  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
876  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
877  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
878  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
879  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
880  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
881  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
882
883  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
884    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
885
886    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
887    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
888    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
889    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
890    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
891    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
892    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
893    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
894    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
895    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
896    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
897    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
898  }
899
900  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
901    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
902
903    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
904    // registers cannot be used even for integer operations.
905    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
906    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
907    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
908    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
909
910    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
911    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
912    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
913    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
914    setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
915    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
916    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
917    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
918    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
919    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
920    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
921    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
922    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
923    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
924    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
925    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
926    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
927    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
928
929    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
930    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
931    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
932    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
933
934    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
935    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
936    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
941    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
942      MVT VT = (MVT::SimpleValueType)i;
943      // Do not attempt to custom lower non-power-of-2 vectors
944      if (!isPowerOf2_32(VT.getVectorNumElements()))
945        continue;
946      // Do not attempt to custom lower non-128-bit vectors
947      if (!VT.is128BitVector())
948        continue;
949      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
950      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
951      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
952    }
953
954    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
955    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
956    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
957    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
958    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
959    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
960
961    if (Subtarget->is64Bit()) {
962      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
963      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
964    }
965
966    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
967    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
968      MVT VT = (MVT::SimpleValueType)i;
969
970      // Do not attempt to promote non-128-bit vectors
971      if (!VT.is128BitVector())
972        continue;
973
974      setOperationAction(ISD::AND,    VT, Promote);
975      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
976      setOperationAction(ISD::OR,     VT, Promote);
977      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
978      setOperationAction(ISD::XOR,    VT, Promote);
979      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
980      setOperationAction(ISD::LOAD,   VT, Promote);
981      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
982      setOperationAction(ISD::SELECT, VT, Promote);
983      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
984    }
985
986    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
987
988    // Custom lower v2i64 and v2f64 selects.
989    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
990    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
991    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
992    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
993
994    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
995    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
996
997    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
998    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
999    // As there is no 64-bit GPR available, we need build a special custom
1000    // sequence to convert from v2i32 to v2f32.
1001    if (!Subtarget->is64Bit())
1002      setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1003
1004    setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1005    setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1006
1007    setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1008  }
1009
1010  if (Subtarget->hasSSE41()) {
1011    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1012    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1013    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1014    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1015    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1016    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1017    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1018    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1019    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1020    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1021
1022    setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1023    setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1024    setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1025    setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1026    setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1027    setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1028    setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1029    setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1030    setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1031    setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1032
1033    // FIXME: Do we need to handle scalar-to-vector here?
1034    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1035
1036    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1037    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1038    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1039    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1040    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1041
1042    // i8 and i16 vectors are custom , because the source register and source
1043    // source memory operand types are not the same width.  f32 vectors are
1044    // custom since the immediate controlling the insert encodes additional
1045    // information.
1046    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1047    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1048    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1049    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1050
1051    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1052    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1053    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1054    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1055
1056    // FIXME: these should be Legal but thats only for the case where
1057    // the index is constant.  For now custom expand to deal with that.
1058    if (Subtarget->is64Bit()) {
1059      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1060      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1061    }
1062  }
1063
1064  if (Subtarget->hasSSE2()) {
1065    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1066    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1067
1068    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1069    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1070
1071    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1072    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1073
1074    // In the customized shift lowering, the legal cases in AVX2 will be
1075    // recognized.
1076    setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1077    setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1078
1079    setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1080    setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1081
1082    setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1083
1084    setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1085    setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1086  }
1087
1088  if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1089    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1090    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1091    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1092    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1093    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1094    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1095
1096    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1097    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1098    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1099
1100    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1101    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1102    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1103    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1104    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1105    setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1106    setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1107    setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1108    setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1109    setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1110    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1111    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1112
1113    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1114    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1115    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1116    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1117    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1118    setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1119    setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1120    setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1121    setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1122    setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1123    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1124    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1125
1126    setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1127    setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1128
1129    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1130
1131    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1132    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1133    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1134    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1135
1136    setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1137    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1138    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1139
1140    setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1141
1142    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1143    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1144
1145    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1146    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1147
1148    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1149    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1150
1151    setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1152
1153    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1154    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1155    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1156    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1157
1158    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1159    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1160    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1161
1162    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1163    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1164    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1165    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1166
1167    setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1168    setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1169    setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1170    setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1171    setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1172    setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1173
1174    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1175      setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1176      setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1177      setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1178      setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1179      setOperationAction(ISD::FMA,             MVT::f32, Legal);
1180      setOperationAction(ISD::FMA,             MVT::f64, Legal);
1181    }
1182
1183    if (Subtarget->hasInt256()) {
1184      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1185      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1186      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1187      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1188
1189      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1190      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1191      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1192      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1193
1194      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1195      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1196      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1197      // Don't lower v32i8 because there is no 128-bit byte mul
1198
1199      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1200
1201      setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1202    } else {
1203      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1204      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1205      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1206      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1207
1208      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1209      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1210      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1211      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1212
1213      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1214      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1215      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1216      // Don't lower v32i8 because there is no 128-bit byte mul
1217    }
1218
1219    // In the customized shift lowering, the legal cases in AVX2 will be
1220    // recognized.
1221    setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1222    setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1223
1224    setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1225    setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1226
1227    setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1228
1229    // Custom lower several nodes for 256-bit types.
1230    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1231             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1232      MVT VT = (MVT::SimpleValueType)i;
1233
1234      // Extract subvector is special because the value type
1235      // (result) is 128-bit but the source is 256-bit wide.
1236      if (VT.is128BitVector())
1237        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1238
1239      // Do not attempt to custom lower other non-256-bit vectors
1240      if (!VT.is256BitVector())
1241        continue;
1242
1243      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1244      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1245      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1246      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1248      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1249      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1250    }
1251
1252    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254      MVT VT = (MVT::SimpleValueType)i;
1255
1256      // Do not attempt to promote non-256-bit vectors
1257      if (!VT.is256BitVector())
1258        continue;
1259
1260      setOperationAction(ISD::AND,    VT, Promote);
1261      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1262      setOperationAction(ISD::OR,     VT, Promote);
1263      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1264      setOperationAction(ISD::XOR,    VT, Promote);
1265      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1266      setOperationAction(ISD::LOAD,   VT, Promote);
1267      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1268      setOperationAction(ISD::SELECT, VT, Promote);
1269      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1270    }
1271  }
1272
1273  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1274  // of this type with custom code.
1275  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1276           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1277    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1278                       Custom);
1279  }
1280
1281  // We want to custom lower some of our intrinsics.
1282  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1283  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1284
1285  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1286  // handle type legalization for these operations here.
1287  //
1288  // FIXME: We really should do custom legalization for addition and
1289  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1290  // than generic legalization for 64-bit multiplication-with-overflow, though.
1291  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1292    // Add/Sub/Mul with overflow operations are custom lowered.
1293    MVT VT = IntVTs[i];
1294    setOperationAction(ISD::SADDO, VT, Custom);
1295    setOperationAction(ISD::UADDO, VT, Custom);
1296    setOperationAction(ISD::SSUBO, VT, Custom);
1297    setOperationAction(ISD::USUBO, VT, Custom);
1298    setOperationAction(ISD::SMULO, VT, Custom);
1299    setOperationAction(ISD::UMULO, VT, Custom);
1300  }
1301
1302  // There are no 8-bit 3-address imul/mul instructions
1303  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1304  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1305
1306  if (!Subtarget->is64Bit()) {
1307    // These libcalls are not available in 32-bit.
1308    setLibcallName(RTLIB::SHL_I128, 0);
1309    setLibcallName(RTLIB::SRL_I128, 0);
1310    setLibcallName(RTLIB::SRA_I128, 0);
1311  }
1312
1313  // Combine sin / cos into one node or libcall if possible.
1314  if (Subtarget->hasSinCos()) {
1315    setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1316    setLibcallName(RTLIB::SINCOS_F64, "sincos");
1317    if (Subtarget->isTargetDarwin()) {
1318      // For MacOSX, we don't want to the normal expansion of a libcall to
1319      // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1320      // traffic.
1321      setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1322      setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1323    }
1324  }
1325
1326  // We have target-specific dag combine patterns for the following nodes:
1327  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1328  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1329  setTargetDAGCombine(ISD::VSELECT);
1330  setTargetDAGCombine(ISD::SELECT);
1331  setTargetDAGCombine(ISD::SHL);
1332  setTargetDAGCombine(ISD::SRA);
1333  setTargetDAGCombine(ISD::SRL);
1334  setTargetDAGCombine(ISD::OR);
1335  setTargetDAGCombine(ISD::AND);
1336  setTargetDAGCombine(ISD::ADD);
1337  setTargetDAGCombine(ISD::FADD);
1338  setTargetDAGCombine(ISD::FSUB);
1339  setTargetDAGCombine(ISD::FMA);
1340  setTargetDAGCombine(ISD::SUB);
1341  setTargetDAGCombine(ISD::LOAD);
1342  setTargetDAGCombine(ISD::STORE);
1343  setTargetDAGCombine(ISD::ZERO_EXTEND);
1344  setTargetDAGCombine(ISD::ANY_EXTEND);
1345  setTargetDAGCombine(ISD::SIGN_EXTEND);
1346  setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1347  setTargetDAGCombine(ISD::TRUNCATE);
1348  setTargetDAGCombine(ISD::SINT_TO_FP);
1349  setTargetDAGCombine(ISD::SETCC);
1350  if (Subtarget->is64Bit())
1351    setTargetDAGCombine(ISD::MUL);
1352  setTargetDAGCombine(ISD::XOR);
1353
1354  computeRegisterProperties();
1355
1356  // On Darwin, -Os means optimize for size without hurting performance,
1357  // do not reduce the limit.
1358  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1359  MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1360  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1361  MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1362  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1363  MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1364  setPrefLoopAlignment(4); // 2^4 bytes.
1365
1366  // Predictable cmov don't hurt on atom because it's in-order.
1367  PredictableSelectIsExpensive = !Subtarget->isAtom();
1368
1369  setPrefFunctionAlignment(4); // 2^4 bytes.
1370}
1371
1372EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1373  if (!VT.isVector()) return MVT::i8;
1374  return VT.changeVectorElementTypeToInteger();
1375}
1376
1377/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1378/// the desired ByVal argument alignment.
1379static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1380  if (MaxAlign == 16)
1381    return;
1382  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1383    if (VTy->getBitWidth() == 128)
1384      MaxAlign = 16;
1385  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1386    unsigned EltAlign = 0;
1387    getMaxByValAlign(ATy->getElementType(), EltAlign);
1388    if (EltAlign > MaxAlign)
1389      MaxAlign = EltAlign;
1390  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1391    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1392      unsigned EltAlign = 0;
1393      getMaxByValAlign(STy->getElementType(i), EltAlign);
1394      if (EltAlign > MaxAlign)
1395        MaxAlign = EltAlign;
1396      if (MaxAlign == 16)
1397        break;
1398    }
1399  }
1400}
1401
1402/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1403/// function arguments in the caller parameter area. For X86, aggregates
1404/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1405/// are at 4-byte boundaries.
1406unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1407  if (Subtarget->is64Bit()) {
1408    // Max of 8 and alignment of type.
1409    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1410    if (TyAlign > 8)
1411      return TyAlign;
1412    return 8;
1413  }
1414
1415  unsigned Align = 4;
1416  if (Subtarget->hasSSE1())
1417    getMaxByValAlign(Ty, Align);
1418  return Align;
1419}
1420
1421/// getOptimalMemOpType - Returns the target specific optimal type for load
1422/// and store operations as a result of memset, memcpy, and memmove
1423/// lowering. If DstAlign is zero that means it's safe to destination
1424/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1425/// means there isn't a need to check it against alignment requirement,
1426/// probably because the source does not need to be loaded. If 'IsMemset' is
1427/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1428/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1429/// source is constant so it does not need to be loaded.
1430/// It returns EVT::Other if the type should be determined using generic
1431/// target-independent logic.
1432EVT
1433X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1434                                       unsigned DstAlign, unsigned SrcAlign,
1435                                       bool IsMemset, bool ZeroMemset,
1436                                       bool MemcpyStrSrc,
1437                                       MachineFunction &MF) const {
1438  const Function *F = MF.getFunction();
1439  if ((!IsMemset || ZeroMemset) &&
1440      !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1441                                       Attribute::NoImplicitFloat)) {
1442    if (Size >= 16 &&
1443        (Subtarget->isUnalignedMemAccessFast() ||
1444         ((DstAlign == 0 || DstAlign >= 16) &&
1445          (SrcAlign == 0 || SrcAlign >= 16)))) {
1446      if (Size >= 32) {
1447        if (Subtarget->hasInt256())
1448          return MVT::v8i32;
1449        if (Subtarget->hasFp256())
1450          return MVT::v8f32;
1451      }
1452      if (Subtarget->hasSSE2())
1453        return MVT::v4i32;
1454      if (Subtarget->hasSSE1())
1455        return MVT::v4f32;
1456    } else if (!MemcpyStrSrc && Size >= 8 &&
1457               !Subtarget->is64Bit() &&
1458               Subtarget->hasSSE2()) {
1459      // Do not use f64 to lower memcpy if source is string constant. It's
1460      // better to use i32 to avoid the loads.
1461      return MVT::f64;
1462    }
1463  }
1464  if (Subtarget->is64Bit() && Size >= 8)
1465    return MVT::i64;
1466  return MVT::i32;
1467}
1468
1469bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1470  if (VT == MVT::f32)
1471    return X86ScalarSSEf32;
1472  else if (VT == MVT::f64)
1473    return X86ScalarSSEf64;
1474  return true;
1475}
1476
1477bool
1478X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1479  if (Fast)
1480    *Fast = Subtarget->isUnalignedMemAccessFast();
1481  return true;
1482}
1483
1484/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1485/// current function.  The returned value is a member of the
1486/// MachineJumpTableInfo::JTEntryKind enum.
1487unsigned X86TargetLowering::getJumpTableEncoding() const {
1488  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1489  // symbol.
1490  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1491      Subtarget->isPICStyleGOT())
1492    return MachineJumpTableInfo::EK_Custom32;
1493
1494  // Otherwise, use the normal jump table encoding heuristics.
1495  return TargetLowering::getJumpTableEncoding();
1496}
1497
1498const MCExpr *
1499X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1500                                             const MachineBasicBlock *MBB,
1501                                             unsigned uid,MCContext &Ctx) const{
1502  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1503         Subtarget->isPICStyleGOT());
1504  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1505  // entries.
1506  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1507                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1508}
1509
1510/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1511/// jumptable.
1512SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1513                                                    SelectionDAG &DAG) const {
1514  if (!Subtarget->is64Bit())
1515    // This doesn't have DebugLoc associated with it, but is not really the
1516    // same as a Register.
1517    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1518  return Table;
1519}
1520
1521/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1522/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1523/// MCExpr.
1524const MCExpr *X86TargetLowering::
1525getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1526                             MCContext &Ctx) const {
1527  // X86-64 uses RIP relative addressing based on the jump table label.
1528  if (Subtarget->isPICStyleRIPRel())
1529    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1530
1531  // Otherwise, the reference is relative to the PIC base.
1532  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1533}
1534
1535// FIXME: Why this routine is here? Move to RegInfo!
1536std::pair<const TargetRegisterClass*, uint8_t>
1537X86TargetLowering::findRepresentativeClass(MVT VT) const{
1538  const TargetRegisterClass *RRC = 0;
1539  uint8_t Cost = 1;
1540  switch (VT.SimpleTy) {
1541  default:
1542    return TargetLowering::findRepresentativeClass(VT);
1543  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1544    RRC = Subtarget->is64Bit() ?
1545      (const TargetRegisterClass*)&X86::GR64RegClass :
1546      (const TargetRegisterClass*)&X86::GR32RegClass;
1547    break;
1548  case MVT::x86mmx:
1549    RRC = &X86::VR64RegClass;
1550    break;
1551  case MVT::f32: case MVT::f64:
1552  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1553  case MVT::v4f32: case MVT::v2f64:
1554  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1555  case MVT::v4f64:
1556    RRC = &X86::VR128RegClass;
1557    break;
1558  }
1559  return std::make_pair(RRC, Cost);
1560}
1561
1562bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1563                                               unsigned &Offset) const {
1564  if (!Subtarget->isTargetLinux())
1565    return false;
1566
1567  if (Subtarget->is64Bit()) {
1568    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1569    Offset = 0x28;
1570    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1571      AddressSpace = 256;
1572    else
1573      AddressSpace = 257;
1574  } else {
1575    // %gs:0x14 on i386
1576    Offset = 0x14;
1577    AddressSpace = 256;
1578  }
1579  return true;
1580}
1581
1582//===----------------------------------------------------------------------===//
1583//               Return Value Calling Convention Implementation
1584//===----------------------------------------------------------------------===//
1585
1586#include "X86GenCallingConv.inc"
1587
1588bool
1589X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1590                                  MachineFunction &MF, bool isVarArg,
1591                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1592                        LLVMContext &Context) const {
1593  SmallVector<CCValAssign, 16> RVLocs;
1594  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1595                 RVLocs, Context);
1596  return CCInfo.CheckReturn(Outs, RetCC_X86);
1597}
1598
1599SDValue
1600X86TargetLowering::LowerReturn(SDValue Chain,
1601                               CallingConv::ID CallConv, bool isVarArg,
1602                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1603                               const SmallVectorImpl<SDValue> &OutVals,
1604                               DebugLoc dl, SelectionDAG &DAG) const {
1605  MachineFunction &MF = DAG.getMachineFunction();
1606  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1607
1608  SmallVector<CCValAssign, 16> RVLocs;
1609  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1610                 RVLocs, *DAG.getContext());
1611  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1612
1613  SDValue Flag;
1614  SmallVector<SDValue, 6> RetOps;
1615  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1616  // Operand #1 = Bytes To Pop
1617  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1618                   MVT::i16));
1619
1620  // Copy the result values into the output registers.
1621  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1622    CCValAssign &VA = RVLocs[i];
1623    assert(VA.isRegLoc() && "Can only return in registers!");
1624    SDValue ValToCopy = OutVals[i];
1625    EVT ValVT = ValToCopy.getValueType();
1626
1627    // Promote values to the appropriate types
1628    if (VA.getLocInfo() == CCValAssign::SExt)
1629      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1630    else if (VA.getLocInfo() == CCValAssign::ZExt)
1631      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1632    else if (VA.getLocInfo() == CCValAssign::AExt)
1633      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1634    else if (VA.getLocInfo() == CCValAssign::BCvt)
1635      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1636
1637    // If this is x86-64, and we disabled SSE, we can't return FP values,
1638    // or SSE or MMX vectors.
1639    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1640         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1641          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1642      report_fatal_error("SSE register return with SSE disabled");
1643    }
1644    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1645    // llvm-gcc has never done it right and no one has noticed, so this
1646    // should be OK for now.
1647    if (ValVT == MVT::f64 &&
1648        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1649      report_fatal_error("SSE2 register return with SSE2 disabled");
1650
1651    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1652    // the RET instruction and handled by the FP Stackifier.
1653    if (VA.getLocReg() == X86::ST0 ||
1654        VA.getLocReg() == X86::ST1) {
1655      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1656      // change the value to the FP stack register class.
1657      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1658        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1659      RetOps.push_back(ValToCopy);
1660      // Don't emit a copytoreg.
1661      continue;
1662    }
1663
1664    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1665    // which is returned in RAX / RDX.
1666    if (Subtarget->is64Bit()) {
1667      if (ValVT == MVT::x86mmx) {
1668        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1669          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1670          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1671                                  ValToCopy);
1672          // If we don't have SSE2 available, convert to v4f32 so the generated
1673          // register is legal.
1674          if (!Subtarget->hasSSE2())
1675            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1676        }
1677      }
1678    }
1679
1680    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1681    Flag = Chain.getValue(1);
1682    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1683  }
1684
1685  // The x86-64 ABIs require that for returning structs by value we copy
1686  // the sret argument into %rax/%eax (depending on ABI) for the return.
1687  // Win32 requires us to put the sret argument to %eax as well.
1688  // We saved the argument into a virtual register in the entry block,
1689  // so now we copy the value out and into %rax/%eax.
1690  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1691      (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1692    MachineFunction &MF = DAG.getMachineFunction();
1693    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1694    unsigned Reg = FuncInfo->getSRetReturnReg();
1695    assert(Reg &&
1696           "SRetReturnReg should have been set in LowerFormalArguments().");
1697    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1698
1699    unsigned RetValReg
1700        = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1701          X86::RAX : X86::EAX;
1702    Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1703    Flag = Chain.getValue(1);
1704
1705    // RAX/EAX now acts like a return value.
1706    RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1707  }
1708
1709  RetOps[0] = Chain;  // Update chain.
1710
1711  // Add the flag if we have it.
1712  if (Flag.getNode())
1713    RetOps.push_back(Flag);
1714
1715  return DAG.getNode(X86ISD::RET_FLAG, dl,
1716                     MVT::Other, &RetOps[0], RetOps.size());
1717}
1718
1719bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1720  if (N->getNumValues() != 1)
1721    return false;
1722  if (!N->hasNUsesOfValue(1, 0))
1723    return false;
1724
1725  SDValue TCChain = Chain;
1726  SDNode *Copy = *N->use_begin();
1727  if (Copy->getOpcode() == ISD::CopyToReg) {
1728    // If the copy has a glue operand, we conservatively assume it isn't safe to
1729    // perform a tail call.
1730    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1731      return false;
1732    TCChain = Copy->getOperand(0);
1733  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1734    return false;
1735
1736  bool HasRet = false;
1737  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1738       UI != UE; ++UI) {
1739    if (UI->getOpcode() != X86ISD::RET_FLAG)
1740      return false;
1741    HasRet = true;
1742  }
1743
1744  if (!HasRet)
1745    return false;
1746
1747  Chain = TCChain;
1748  return true;
1749}
1750
1751MVT
1752X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1753                                            ISD::NodeType ExtendKind) const {
1754  MVT ReturnMVT;
1755  // TODO: Is this also valid on 32-bit?
1756  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1757    ReturnMVT = MVT::i8;
1758  else
1759    ReturnMVT = MVT::i32;
1760
1761  MVT MinVT = getRegisterType(ReturnMVT);
1762  return VT.bitsLT(MinVT) ? MinVT : VT;
1763}
1764
1765/// LowerCallResult - Lower the result values of a call into the
1766/// appropriate copies out of appropriate physical registers.
1767///
1768SDValue
1769X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1770                                   CallingConv::ID CallConv, bool isVarArg,
1771                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1772                                   DebugLoc dl, SelectionDAG &DAG,
1773                                   SmallVectorImpl<SDValue> &InVals) const {
1774
1775  // Assign locations to each value returned by this call.
1776  SmallVector<CCValAssign, 16> RVLocs;
1777  bool Is64Bit = Subtarget->is64Bit();
1778  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1779                 getTargetMachine(), RVLocs, *DAG.getContext());
1780  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1781
1782  // Copy all of the result registers out of their specified physreg.
1783  for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1784    CCValAssign &VA = RVLocs[i];
1785    EVT CopyVT = VA.getValVT();
1786
1787    // If this is x86-64, and we disabled SSE, we can't return FP values
1788    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1789        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1790      report_fatal_error("SSE register return with SSE disabled");
1791    }
1792
1793    SDValue Val;
1794
1795    // If this is a call to a function that returns an fp value on the floating
1796    // point stack, we must guarantee the value is popped from the stack, so
1797    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1798    // if the return value is not used. We use the FpPOP_RETVAL instruction
1799    // instead.
1800    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1801      // If we prefer to use the value in xmm registers, copy it out as f80 and
1802      // use a truncate to move it from fp stack reg to xmm reg.
1803      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1804      SDValue Ops[] = { Chain, InFlag };
1805      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1806                                         MVT::Other, MVT::Glue, Ops,
1807                                         array_lengthof(Ops)), 1);
1808      Val = Chain.getValue(0);
1809
1810      // Round the f80 to the right size, which also moves it to the appropriate
1811      // xmm register.
1812      if (CopyVT != VA.getValVT())
1813        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1814                          // This truncation won't change the value.
1815                          DAG.getIntPtrConstant(1));
1816    } else {
1817      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1818                                 CopyVT, InFlag).getValue(1);
1819      Val = Chain.getValue(0);
1820    }
1821    InFlag = Chain.getValue(2);
1822    InVals.push_back(Val);
1823  }
1824
1825  return Chain;
1826}
1827
1828//===----------------------------------------------------------------------===//
1829//                C & StdCall & Fast Calling Convention implementation
1830//===----------------------------------------------------------------------===//
1831//  StdCall calling convention seems to be standard for many Windows' API
1832//  routines and around. It differs from C calling convention just a little:
1833//  callee should clean up the stack, not caller. Symbols should be also
1834//  decorated in some fancy way :) It doesn't support any vector arguments.
1835//  For info on fast calling convention see Fast Calling Convention (tail call)
1836//  implementation LowerX86_32FastCCCallTo.
1837
1838/// CallIsStructReturn - Determines whether a call uses struct return
1839/// semantics.
1840enum StructReturnType {
1841  NotStructReturn,
1842  RegStructReturn,
1843  StackStructReturn
1844};
1845static StructReturnType
1846callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1847  if (Outs.empty())
1848    return NotStructReturn;
1849
1850  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1851  if (!Flags.isSRet())
1852    return NotStructReturn;
1853  if (Flags.isInReg())
1854    return RegStructReturn;
1855  return StackStructReturn;
1856}
1857
1858/// ArgsAreStructReturn - Determines whether a function uses struct
1859/// return semantics.
1860static StructReturnType
1861argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1862  if (Ins.empty())
1863    return NotStructReturn;
1864
1865  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1866  if (!Flags.isSRet())
1867    return NotStructReturn;
1868  if (Flags.isInReg())
1869    return RegStructReturn;
1870  return StackStructReturn;
1871}
1872
1873/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1874/// by "Src" to address "Dst" with size and alignment information specified by
1875/// the specific parameter attribute. The copy will be passed as a byval
1876/// function parameter.
1877static SDValue
1878CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1879                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1880                          DebugLoc dl) {
1881  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1882
1883  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1884                       /*isVolatile*/false, /*AlwaysInline=*/true,
1885                       MachinePointerInfo(), MachinePointerInfo());
1886}
1887
1888/// IsTailCallConvention - Return true if the calling convention is one that
1889/// supports tail call optimization.
1890static bool IsTailCallConvention(CallingConv::ID CC) {
1891  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1892          CC == CallingConv::HiPE);
1893}
1894
1895bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1896  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1897    return false;
1898
1899  CallSite CS(CI);
1900  CallingConv::ID CalleeCC = CS.getCallingConv();
1901  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1902    return false;
1903
1904  return true;
1905}
1906
1907/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1908/// a tailcall target by changing its ABI.
1909static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1910                                   bool GuaranteedTailCallOpt) {
1911  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1912}
1913
1914SDValue
1915X86TargetLowering::LowerMemArgument(SDValue Chain,
1916                                    CallingConv::ID CallConv,
1917                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1918                                    DebugLoc dl, SelectionDAG &DAG,
1919                                    const CCValAssign &VA,
1920                                    MachineFrameInfo *MFI,
1921                                    unsigned i) const {
1922  // Create the nodes corresponding to a load from this parameter slot.
1923  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1924  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1925                              getTargetMachine().Options.GuaranteedTailCallOpt);
1926  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1927  EVT ValVT;
1928
1929  // If value is passed by pointer we have address passed instead of the value
1930  // itself.
1931  if (VA.getLocInfo() == CCValAssign::Indirect)
1932    ValVT = VA.getLocVT();
1933  else
1934    ValVT = VA.getValVT();
1935
1936  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1937  // changed with more analysis.
1938  // In case of tail call optimization mark all arguments mutable. Since they
1939  // could be overwritten by lowering of arguments in case of a tail call.
1940  if (Flags.isByVal()) {
1941    unsigned Bytes = Flags.getByValSize();
1942    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1943    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1944    return DAG.getFrameIndex(FI, getPointerTy());
1945  } else {
1946    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1947                                    VA.getLocMemOffset(), isImmutable);
1948    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1949    return DAG.getLoad(ValVT, dl, Chain, FIN,
1950                       MachinePointerInfo::getFixedStack(FI),
1951                       false, false, false, 0);
1952  }
1953}
1954
1955SDValue
1956X86TargetLowering::LowerFormalArguments(SDValue Chain,
1957                                        CallingConv::ID CallConv,
1958                                        bool isVarArg,
1959                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1960                                        DebugLoc dl,
1961                                        SelectionDAG &DAG,
1962                                        SmallVectorImpl<SDValue> &InVals)
1963                                          const {
1964  MachineFunction &MF = DAG.getMachineFunction();
1965  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1966
1967  const Function* Fn = MF.getFunction();
1968  if (Fn->hasExternalLinkage() &&
1969      Subtarget->isTargetCygMing() &&
1970      Fn->getName() == "main")
1971    FuncInfo->setForceFramePointer(true);
1972
1973  MachineFrameInfo *MFI = MF.getFrameInfo();
1974  bool Is64Bit = Subtarget->is64Bit();
1975  bool IsWindows = Subtarget->isTargetWindows();
1976  bool IsWin64 = Subtarget->isTargetWin64();
1977
1978  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1979         "Var args not supported with calling convention fastcc, ghc or hipe");
1980
1981  // Assign locations to all of the incoming arguments.
1982  SmallVector<CCValAssign, 16> ArgLocs;
1983  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1984                 ArgLocs, *DAG.getContext());
1985
1986  // Allocate shadow area for Win64
1987  if (IsWin64) {
1988    CCInfo.AllocateStack(32, 8);
1989  }
1990
1991  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1992
1993  unsigned LastVal = ~0U;
1994  SDValue ArgValue;
1995  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1996    CCValAssign &VA = ArgLocs[i];
1997    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1998    // places.
1999    assert(VA.getValNo() != LastVal &&
2000           "Don't support value assigned to multiple locs yet");
2001    (void)LastVal;
2002    LastVal = VA.getValNo();
2003
2004    if (VA.isRegLoc()) {
2005      EVT RegVT = VA.getLocVT();
2006      const TargetRegisterClass *RC;
2007      if (RegVT == MVT::i32)
2008        RC = &X86::GR32RegClass;
2009      else if (Is64Bit && RegVT == MVT::i64)
2010        RC = &X86::GR64RegClass;
2011      else if (RegVT == MVT::f32)
2012        RC = &X86::FR32RegClass;
2013      else if (RegVT == MVT::f64)
2014        RC = &X86::FR64RegClass;
2015      else if (RegVT.is256BitVector())
2016        RC = &X86::VR256RegClass;
2017      else if (RegVT.is128BitVector())
2018        RC = &X86::VR128RegClass;
2019      else if (RegVT == MVT::x86mmx)
2020        RC = &X86::VR64RegClass;
2021      else
2022        llvm_unreachable("Unknown argument type!");
2023
2024      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2025      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2026
2027      // If this is an 8 or 16-bit value, it is really passed promoted to 32
2028      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2029      // right size.
2030      if (VA.getLocInfo() == CCValAssign::SExt)
2031        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2032                               DAG.getValueType(VA.getValVT()));
2033      else if (VA.getLocInfo() == CCValAssign::ZExt)
2034        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2035                               DAG.getValueType(VA.getValVT()));
2036      else if (VA.getLocInfo() == CCValAssign::BCvt)
2037        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2038
2039      if (VA.isExtInLoc()) {
2040        // Handle MMX values passed in XMM regs.
2041        if (RegVT.isVector())
2042          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2043        else
2044          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2045      }
2046    } else {
2047      assert(VA.isMemLoc());
2048      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2049    }
2050
2051    // If value is passed via pointer - do a load.
2052    if (VA.getLocInfo() == CCValAssign::Indirect)
2053      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2054                             MachinePointerInfo(), false, false, false, 0);
2055
2056    InVals.push_back(ArgValue);
2057  }
2058
2059  // The x86-64 ABIs require that for returning structs by value we copy
2060  // the sret argument into %rax/%eax (depending on ABI) for the return.
2061  // Win32 requires us to put the sret argument to %eax as well.
2062  // Save the argument into a virtual register so that we can access it
2063  // from the return points.
2064  if (MF.getFunction()->hasStructRetAttr() &&
2065      (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2066    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2067    unsigned Reg = FuncInfo->getSRetReturnReg();
2068    if (!Reg) {
2069      MVT PtrTy = getPointerTy();
2070      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2071      FuncInfo->setSRetReturnReg(Reg);
2072    }
2073    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2074    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2075  }
2076
2077  unsigned StackSize = CCInfo.getNextStackOffset();
2078  // Align stack specially for tail calls.
2079  if (FuncIsMadeTailCallSafe(CallConv,
2080                             MF.getTarget().Options.GuaranteedTailCallOpt))
2081    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2082
2083  // If the function takes variable number of arguments, make a frame index for
2084  // the start of the first vararg value... for expansion of llvm.va_start.
2085  if (isVarArg) {
2086    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2087                    CallConv != CallingConv::X86_ThisCall)) {
2088      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2089    }
2090    if (Is64Bit) {
2091      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2092
2093      // FIXME: We should really autogenerate these arrays
2094      static const uint16_t GPR64ArgRegsWin64[] = {
2095        X86::RCX, X86::RDX, X86::R8,  X86::R9
2096      };
2097      static const uint16_t GPR64ArgRegs64Bit[] = {
2098        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2099      };
2100      static const uint16_t XMMArgRegs64Bit[] = {
2101        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2102        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2103      };
2104      const uint16_t *GPR64ArgRegs;
2105      unsigned NumXMMRegs = 0;
2106
2107      if (IsWin64) {
2108        // The XMM registers which might contain var arg parameters are shadowed
2109        // in their paired GPR.  So we only need to save the GPR to their home
2110        // slots.
2111        TotalNumIntRegs = 4;
2112        GPR64ArgRegs = GPR64ArgRegsWin64;
2113      } else {
2114        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2115        GPR64ArgRegs = GPR64ArgRegs64Bit;
2116
2117        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2118                                                TotalNumXMMRegs);
2119      }
2120      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2121                                                       TotalNumIntRegs);
2122
2123      bool NoImplicitFloatOps = Fn->getAttributes().
2124        hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2125      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2126             "SSE register cannot be used when SSE is disabled!");
2127      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2128               NoImplicitFloatOps) &&
2129             "SSE register cannot be used when SSE is disabled!");
2130      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2131          !Subtarget->hasSSE1())
2132        // Kernel mode asks for SSE to be disabled, so don't push them
2133        // on the stack.
2134        TotalNumXMMRegs = 0;
2135
2136      if (IsWin64) {
2137        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2138        // Get to the caller-allocated home save location.  Add 8 to account
2139        // for the return address.
2140        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2141        FuncInfo->setRegSaveFrameIndex(
2142          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2143        // Fixup to set vararg frame on shadow area (4 x i64).
2144        if (NumIntRegs < 4)
2145          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2146      } else {
2147        // For X86-64, if there are vararg parameters that are passed via
2148        // registers, then we must store them to their spots on the stack so
2149        // they may be loaded by deferencing the result of va_next.
2150        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2151        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2152        FuncInfo->setRegSaveFrameIndex(
2153          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2154                               false));
2155      }
2156
2157      // Store the integer parameter registers.
2158      SmallVector<SDValue, 8> MemOps;
2159      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2160                                        getPointerTy());
2161      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2162      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2163        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2164                                  DAG.getIntPtrConstant(Offset));
2165        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2166                                     &X86::GR64RegClass);
2167        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2168        SDValue Store =
2169          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2170                       MachinePointerInfo::getFixedStack(
2171                         FuncInfo->getRegSaveFrameIndex(), Offset),
2172                       false, false, 0);
2173        MemOps.push_back(Store);
2174        Offset += 8;
2175      }
2176
2177      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2178        // Now store the XMM (fp + vector) parameter registers.
2179        SmallVector<SDValue, 11> SaveXMMOps;
2180        SaveXMMOps.push_back(Chain);
2181
2182        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2183        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2184        SaveXMMOps.push_back(ALVal);
2185
2186        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2187                               FuncInfo->getRegSaveFrameIndex()));
2188        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2189                               FuncInfo->getVarArgsFPOffset()));
2190
2191        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2192          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2193                                       &X86::VR128RegClass);
2194          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2195          SaveXMMOps.push_back(Val);
2196        }
2197        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2198                                     MVT::Other,
2199                                     &SaveXMMOps[0], SaveXMMOps.size()));
2200      }
2201
2202      if (!MemOps.empty())
2203        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2204                            &MemOps[0], MemOps.size());
2205    }
2206  }
2207
2208  // Some CCs need callee pop.
2209  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2210                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2211    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2212  } else {
2213    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2214    // If this is an sret function, the return should pop the hidden pointer.
2215    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2216        argsAreStructReturn(Ins) == StackStructReturn)
2217      FuncInfo->setBytesToPopOnReturn(4);
2218  }
2219
2220  if (!Is64Bit) {
2221    // RegSaveFrameIndex is X86-64 only.
2222    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2223    if (CallConv == CallingConv::X86_FastCall ||
2224        CallConv == CallingConv::X86_ThisCall)
2225      // fastcc functions can't have varargs.
2226      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2227  }
2228
2229  FuncInfo->setArgumentStackSize(StackSize);
2230
2231  return Chain;
2232}
2233
2234SDValue
2235X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2236                                    SDValue StackPtr, SDValue Arg,
2237                                    DebugLoc dl, SelectionDAG &DAG,
2238                                    const CCValAssign &VA,
2239                                    ISD::ArgFlagsTy Flags) const {
2240  unsigned LocMemOffset = VA.getLocMemOffset();
2241  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2242  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2243  if (Flags.isByVal())
2244    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2245
2246  return DAG.getStore(Chain, dl, Arg, PtrOff,
2247                      MachinePointerInfo::getStack(LocMemOffset),
2248                      false, false, 0);
2249}
2250
2251/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2252/// optimization is performed and it is required.
2253SDValue
2254X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2255                                           SDValue &OutRetAddr, SDValue Chain,
2256                                           bool IsTailCall, bool Is64Bit,
2257                                           int FPDiff, DebugLoc dl) const {
2258  // Adjust the Return address stack slot.
2259  EVT VT = getPointerTy();
2260  OutRetAddr = getReturnAddressFrameIndex(DAG);
2261
2262  // Load the "old" Return address.
2263  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2264                           false, false, false, 0);
2265  return SDValue(OutRetAddr.getNode(), 1);
2266}
2267
2268/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2269/// optimization is performed and it is required (FPDiff!=0).
2270static SDValue
2271EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2272                         SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2273                         unsigned SlotSize, int FPDiff, DebugLoc dl) {
2274  // Store the return address to the appropriate stack slot.
2275  if (!FPDiff) return Chain;
2276  // Calculate the new stack slot for the return address.
2277  int NewReturnAddrFI =
2278    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2279  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2280  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2281                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2282                       false, false, 0);
2283  return Chain;
2284}
2285
2286SDValue
2287X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2288                             SmallVectorImpl<SDValue> &InVals) const {
2289  SelectionDAG &DAG                     = CLI.DAG;
2290  DebugLoc &dl                          = CLI.DL;
2291  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2292  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2293  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2294  SDValue Chain                         = CLI.Chain;
2295  SDValue Callee                        = CLI.Callee;
2296  CallingConv::ID CallConv              = CLI.CallConv;
2297  bool &isTailCall                      = CLI.IsTailCall;
2298  bool isVarArg                         = CLI.IsVarArg;
2299
2300  MachineFunction &MF = DAG.getMachineFunction();
2301  bool Is64Bit        = Subtarget->is64Bit();
2302  bool IsWin64        = Subtarget->isTargetWin64();
2303  bool IsWindows      = Subtarget->isTargetWindows();
2304  StructReturnType SR = callIsStructReturn(Outs);
2305  bool IsSibcall      = false;
2306
2307  if (MF.getTarget().Options.DisableTailCalls)
2308    isTailCall = false;
2309
2310  if (isTailCall) {
2311    // Check if it's really possible to do a tail call.
2312    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2313                    isVarArg, SR != NotStructReturn,
2314                    MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2315                    Outs, OutVals, Ins, DAG);
2316
2317    // Sibcalls are automatically detected tailcalls which do not require
2318    // ABI changes.
2319    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2320      IsSibcall = true;
2321
2322    if (isTailCall)
2323      ++NumTailCalls;
2324  }
2325
2326  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2327         "Var args not supported with calling convention fastcc, ghc or hipe");
2328
2329  // Analyze operands of the call, assigning locations to each operand.
2330  SmallVector<CCValAssign, 16> ArgLocs;
2331  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2332                 ArgLocs, *DAG.getContext());
2333
2334  // Allocate shadow area for Win64
2335  if (IsWin64) {
2336    CCInfo.AllocateStack(32, 8);
2337  }
2338
2339  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2340
2341  // Get a count of how many bytes are to be pushed on the stack.
2342  unsigned NumBytes = CCInfo.getNextStackOffset();
2343  if (IsSibcall)
2344    // This is a sibcall. The memory operands are available in caller's
2345    // own caller's stack.
2346    NumBytes = 0;
2347  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2348           IsTailCallConvention(CallConv))
2349    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2350
2351  int FPDiff = 0;
2352  if (isTailCall && !IsSibcall) {
2353    // Lower arguments at fp - stackoffset + fpdiff.
2354    X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2355    unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2356
2357    FPDiff = NumBytesCallerPushed - NumBytes;
2358
2359    // Set the delta of movement of the returnaddr stackslot.
2360    // But only set if delta is greater than previous delta.
2361    if (FPDiff < X86Info->getTCReturnAddrDelta())
2362      X86Info->setTCReturnAddrDelta(FPDiff);
2363  }
2364
2365  if (!IsSibcall)
2366    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2367
2368  SDValue RetAddrFrIdx;
2369  // Load return address for tail calls.
2370  if (isTailCall && FPDiff)
2371    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2372                                    Is64Bit, FPDiff, dl);
2373
2374  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2375  SmallVector<SDValue, 8> MemOpChains;
2376  SDValue StackPtr;
2377
2378  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2379  // of tail call optimization arguments are handle later.
2380  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381    CCValAssign &VA = ArgLocs[i];
2382    EVT RegVT = VA.getLocVT();
2383    SDValue Arg = OutVals[i];
2384    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2385    bool isByVal = Flags.isByVal();
2386
2387    // Promote the value if needed.
2388    switch (VA.getLocInfo()) {
2389    default: llvm_unreachable("Unknown loc info!");
2390    case CCValAssign::Full: break;
2391    case CCValAssign::SExt:
2392      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2393      break;
2394    case CCValAssign::ZExt:
2395      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2396      break;
2397    case CCValAssign::AExt:
2398      if (RegVT.is128BitVector()) {
2399        // Special case: passing MMX values in XMM registers.
2400        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2401        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2402        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2403      } else
2404        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2405      break;
2406    case CCValAssign::BCvt:
2407      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2408      break;
2409    case CCValAssign::Indirect: {
2410      // Store the argument.
2411      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2412      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2413      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2414                           MachinePointerInfo::getFixedStack(FI),
2415                           false, false, 0);
2416      Arg = SpillSlot;
2417      break;
2418    }
2419    }
2420
2421    if (VA.isRegLoc()) {
2422      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2423      if (isVarArg && IsWin64) {
2424        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2425        // shadow reg if callee is a varargs function.
2426        unsigned ShadowReg = 0;
2427        switch (VA.getLocReg()) {
2428        case X86::XMM0: ShadowReg = X86::RCX; break;
2429        case X86::XMM1: ShadowReg = X86::RDX; break;
2430        case X86::XMM2: ShadowReg = X86::R8; break;
2431        case X86::XMM3: ShadowReg = X86::R9; break;
2432        }
2433        if (ShadowReg)
2434          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2435      }
2436    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2437      assert(VA.isMemLoc());
2438      if (StackPtr.getNode() == 0)
2439        StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2440                                      getPointerTy());
2441      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2442                                             dl, DAG, VA, Flags));
2443    }
2444  }
2445
2446  if (!MemOpChains.empty())
2447    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2448                        &MemOpChains[0], MemOpChains.size());
2449
2450  if (Subtarget->isPICStyleGOT()) {
2451    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2452    // GOT pointer.
2453    if (!isTailCall) {
2454      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2455               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2456    } else {
2457      // If we are tail calling and generating PIC/GOT style code load the
2458      // address of the callee into ECX. The value in ecx is used as target of
2459      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2460      // for tail calls on PIC/GOT architectures. Normally we would just put the
2461      // address of GOT into ebx and then call target@PLT. But for tail calls
2462      // ebx would be restored (since ebx is callee saved) before jumping to the
2463      // target@PLT.
2464
2465      // Note: The actual moving to ECX is done further down.
2466      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2467      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2468          !G->getGlobal()->hasProtectedVisibility())
2469        Callee = LowerGlobalAddress(Callee, DAG);
2470      else if (isa<ExternalSymbolSDNode>(Callee))
2471        Callee = LowerExternalSymbol(Callee, DAG);
2472    }
2473  }
2474
2475  if (Is64Bit && isVarArg && !IsWin64) {
2476    // From AMD64 ABI document:
2477    // For calls that may call functions that use varargs or stdargs
2478    // (prototype-less calls or calls to functions containing ellipsis (...) in
2479    // the declaration) %al is used as hidden argument to specify the number
2480    // of SSE registers used. The contents of %al do not need to match exactly
2481    // the number of registers, but must be an ubound on the number of SSE
2482    // registers used and is in the range 0 - 8 inclusive.
2483
2484    // Count the number of XMM registers allocated.
2485    static const uint16_t XMMArgRegs[] = {
2486      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2487      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2488    };
2489    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2490    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2491           && "SSE registers cannot be used when SSE is disabled");
2492
2493    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2494                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2495  }
2496
2497  // For tail calls lower the arguments to the 'real' stack slot.
2498  if (isTailCall) {
2499    // Force all the incoming stack arguments to be loaded from the stack
2500    // before any new outgoing arguments are stored to the stack, because the
2501    // outgoing stack slots may alias the incoming argument stack slots, and
2502    // the alias isn't otherwise explicit. This is slightly more conservative
2503    // than necessary, because it means that each store effectively depends
2504    // on every argument instead of just those arguments it would clobber.
2505    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2506
2507    SmallVector<SDValue, 8> MemOpChains2;
2508    SDValue FIN;
2509    int FI = 0;
2510    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2511      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2512        CCValAssign &VA = ArgLocs[i];
2513        if (VA.isRegLoc())
2514          continue;
2515        assert(VA.isMemLoc());
2516        SDValue Arg = OutVals[i];
2517        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2518        // Create frame index.
2519        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2520        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2521        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2522        FIN = DAG.getFrameIndex(FI, getPointerTy());
2523
2524        if (Flags.isByVal()) {
2525          // Copy relative to framepointer.
2526          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2527          if (StackPtr.getNode() == 0)
2528            StackPtr = DAG.getCopyFromReg(Chain, dl,
2529                                          RegInfo->getStackRegister(),
2530                                          getPointerTy());
2531          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2532
2533          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2534                                                           ArgChain,
2535                                                           Flags, DAG, dl));
2536        } else {
2537          // Store relative to framepointer.
2538          MemOpChains2.push_back(
2539            DAG.getStore(ArgChain, dl, Arg, FIN,
2540                         MachinePointerInfo::getFixedStack(FI),
2541                         false, false, 0));
2542        }
2543      }
2544    }
2545
2546    if (!MemOpChains2.empty())
2547      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2548                          &MemOpChains2[0], MemOpChains2.size());
2549
2550    // Store the return address to the appropriate stack slot.
2551    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2552                                     getPointerTy(), RegInfo->getSlotSize(),
2553                                     FPDiff, dl);
2554  }
2555
2556  // Build a sequence of copy-to-reg nodes chained together with token chain
2557  // and flag operands which copy the outgoing args into registers.
2558  SDValue InFlag;
2559  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2560    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2561                             RegsToPass[i].second, InFlag);
2562    InFlag = Chain.getValue(1);
2563  }
2564
2565  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2566    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2567    // In the 64-bit large code model, we have to make all calls
2568    // through a register, since the call instruction's 32-bit
2569    // pc-relative offset may not be large enough to hold the whole
2570    // address.
2571  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2572    // If the callee is a GlobalAddress node (quite common, every direct call
2573    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2574    // it.
2575
2576    // We should use extra load for direct calls to dllimported functions in
2577    // non-JIT mode.
2578    const GlobalValue *GV = G->getGlobal();
2579    if (!GV->hasDLLImportLinkage()) {
2580      unsigned char OpFlags = 0;
2581      bool ExtraLoad = false;
2582      unsigned WrapperKind = ISD::DELETED_NODE;
2583
2584      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2585      // external symbols most go through the PLT in PIC mode.  If the symbol
2586      // has hidden or protected visibility, or if it is static or local, then
2587      // we don't need to use the PLT - we can directly call it.
2588      if (Subtarget->isTargetELF() &&
2589          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2590          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2591        OpFlags = X86II::MO_PLT;
2592      } else if (Subtarget->isPICStyleStubAny() &&
2593                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2594                 (!Subtarget->getTargetTriple().isMacOSX() ||
2595                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2596        // PC-relative references to external symbols should go through $stub,
2597        // unless we're building with the leopard linker or later, which
2598        // automatically synthesizes these stubs.
2599        OpFlags = X86II::MO_DARWIN_STUB;
2600      } else if (Subtarget->isPICStyleRIPRel() &&
2601                 isa<Function>(GV) &&
2602                 cast<Function>(GV)->getAttributes().
2603                   hasAttribute(AttributeSet::FunctionIndex,
2604                                Attribute::NonLazyBind)) {
2605        // If the function is marked as non-lazy, generate an indirect call
2606        // which loads from the GOT directly. This avoids runtime overhead
2607        // at the cost of eager binding (and one extra byte of encoding).
2608        OpFlags = X86II::MO_GOTPCREL;
2609        WrapperKind = X86ISD::WrapperRIP;
2610        ExtraLoad = true;
2611      }
2612
2613      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2614                                          G->getOffset(), OpFlags);
2615
2616      // Add a wrapper if needed.
2617      if (WrapperKind != ISD::DELETED_NODE)
2618        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2619      // Add extra indirection if needed.
2620      if (ExtraLoad)
2621        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2622                             MachinePointerInfo::getGOT(),
2623                             false, false, false, 0);
2624    }
2625  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2626    unsigned char OpFlags = 0;
2627
2628    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2629    // external symbols should go through the PLT.
2630    if (Subtarget->isTargetELF() &&
2631        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2632      OpFlags = X86II::MO_PLT;
2633    } else if (Subtarget->isPICStyleStubAny() &&
2634               (!Subtarget->getTargetTriple().isMacOSX() ||
2635                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2636      // PC-relative references to external symbols should go through $stub,
2637      // unless we're building with the leopard linker or later, which
2638      // automatically synthesizes these stubs.
2639      OpFlags = X86II::MO_DARWIN_STUB;
2640    }
2641
2642    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2643                                         OpFlags);
2644  }
2645
2646  // Returns a chain & a flag for retval copy to use.
2647  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2648  SmallVector<SDValue, 8> Ops;
2649
2650  if (!IsSibcall && isTailCall) {
2651    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2652                           DAG.getIntPtrConstant(0, true), InFlag);
2653    InFlag = Chain.getValue(1);
2654  }
2655
2656  Ops.push_back(Chain);
2657  Ops.push_back(Callee);
2658
2659  if (isTailCall)
2660    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2661
2662  // Add argument registers to the end of the list so that they are known live
2663  // into the call.
2664  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2665    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2666                                  RegsToPass[i].second.getValueType()));
2667
2668  // Add a register mask operand representing the call-preserved registers.
2669  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2670  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2671  assert(Mask && "Missing call preserved mask for calling convention");
2672  Ops.push_back(DAG.getRegisterMask(Mask));
2673
2674  if (InFlag.getNode())
2675    Ops.push_back(InFlag);
2676
2677  if (isTailCall) {
2678    // We used to do:
2679    //// If this is the first return lowered for this function, add the regs
2680    //// to the liveout set for the function.
2681    // This isn't right, although it's probably harmless on x86; liveouts
2682    // should be computed from returns not tail calls.  Consider a void
2683    // function making a tail call to a function returning int.
2684    return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2685  }
2686
2687  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2688  InFlag = Chain.getValue(1);
2689
2690  // Create the CALLSEQ_END node.
2691  unsigned NumBytesForCalleeToPush;
2692  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2693                       getTargetMachine().Options.GuaranteedTailCallOpt))
2694    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2695  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2696           SR == StackStructReturn)
2697    // If this is a call to a struct-return function, the callee
2698    // pops the hidden struct pointer, so we have to push it back.
2699    // This is common for Darwin/X86, Linux & Mingw32 targets.
2700    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2701    NumBytesForCalleeToPush = 4;
2702  else
2703    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2704
2705  // Returns a flag for retval copy to use.
2706  if (!IsSibcall) {
2707    Chain = DAG.getCALLSEQ_END(Chain,
2708                               DAG.getIntPtrConstant(NumBytes, true),
2709                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2710                                                     true),
2711                               InFlag);
2712    InFlag = Chain.getValue(1);
2713  }
2714
2715  // Handle result values, copying them out of physregs into vregs that we
2716  // return.
2717  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2718                         Ins, dl, DAG, InVals);
2719}
2720
2721//===----------------------------------------------------------------------===//
2722//                Fast Calling Convention (tail call) implementation
2723//===----------------------------------------------------------------------===//
2724
2725//  Like std call, callee cleans arguments, convention except that ECX is
2726//  reserved for storing the tail called function address. Only 2 registers are
2727//  free for argument passing (inreg). Tail call optimization is performed
2728//  provided:
2729//                * tailcallopt is enabled
2730//                * caller/callee are fastcc
2731//  On X86_64 architecture with GOT-style position independent code only local
2732//  (within module) calls are supported at the moment.
2733//  To keep the stack aligned according to platform abi the function
2734//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2735//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2736//  If a tail called function callee has more arguments than the caller the
2737//  caller needs to make sure that there is room to move the RETADDR to. This is
2738//  achieved by reserving an area the size of the argument delta right after the
2739//  original REtADDR, but before the saved framepointer or the spilled registers
2740//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2741//  stack layout:
2742//    arg1
2743//    arg2
2744//    RETADDR
2745//    [ new RETADDR
2746//      move area ]
2747//    (possible EBP)
2748//    ESI
2749//    EDI
2750//    local1 ..
2751
2752/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2753/// for a 16 byte align requirement.
2754unsigned
2755X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2756                                               SelectionDAG& DAG) const {
2757  MachineFunction &MF = DAG.getMachineFunction();
2758  const TargetMachine &TM = MF.getTarget();
2759  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2760  unsigned StackAlignment = TFI.getStackAlignment();
2761  uint64_t AlignMask = StackAlignment - 1;
2762  int64_t Offset = StackSize;
2763  unsigned SlotSize = RegInfo->getSlotSize();
2764  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2765    // Number smaller than 12 so just add the difference.
2766    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2767  } else {
2768    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2769    Offset = ((~AlignMask) & Offset) + StackAlignment +
2770      (StackAlignment-SlotSize);
2771  }
2772  return Offset;
2773}
2774
2775/// MatchingStackOffset - Return true if the given stack call argument is
2776/// already available in the same position (relatively) of the caller's
2777/// incoming argument stack.
2778static
2779bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2780                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2781                         const X86InstrInfo *TII) {
2782  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2783  int FI = INT_MAX;
2784  if (Arg.getOpcode() == ISD::CopyFromReg) {
2785    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2786    if (!TargetRegisterInfo::isVirtualRegister(VR))
2787      return false;
2788    MachineInstr *Def = MRI->getVRegDef(VR);
2789    if (!Def)
2790      return false;
2791    if (!Flags.isByVal()) {
2792      if (!TII->isLoadFromStackSlot(Def, FI))
2793        return false;
2794    } else {
2795      unsigned Opcode = Def->getOpcode();
2796      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2797          Def->getOperand(1).isFI()) {
2798        FI = Def->getOperand(1).getIndex();
2799        Bytes = Flags.getByValSize();
2800      } else
2801        return false;
2802    }
2803  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2804    if (Flags.isByVal())
2805      // ByVal argument is passed in as a pointer but it's now being
2806      // dereferenced. e.g.
2807      // define @foo(%struct.X* %A) {
2808      //   tail call @bar(%struct.X* byval %A)
2809      // }
2810      return false;
2811    SDValue Ptr = Ld->getBasePtr();
2812    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2813    if (!FINode)
2814      return false;
2815    FI = FINode->getIndex();
2816  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2817    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2818    FI = FINode->getIndex();
2819    Bytes = Flags.getByValSize();
2820  } else
2821    return false;
2822
2823  assert(FI != INT_MAX);
2824  if (!MFI->isFixedObjectIndex(FI))
2825    return false;
2826  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2827}
2828
2829/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2830/// for tail call optimization. Targets which want to do tail call
2831/// optimization should implement this function.
2832bool
2833X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2834                                                     CallingConv::ID CalleeCC,
2835                                                     bool isVarArg,
2836                                                     bool isCalleeStructRet,
2837                                                     bool isCallerStructRet,
2838                                                     Type *RetTy,
2839                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2840                                    const SmallVectorImpl<SDValue> &OutVals,
2841                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2842                                                     SelectionDAG &DAG) const {
2843  if (!IsTailCallConvention(CalleeCC) &&
2844      CalleeCC != CallingConv::C)
2845    return false;
2846
2847  // If -tailcallopt is specified, make fastcc functions tail-callable.
2848  const MachineFunction &MF = DAG.getMachineFunction();
2849  const Function *CallerF = DAG.getMachineFunction().getFunction();
2850
2851  // If the function return type is x86_fp80 and the callee return type is not,
2852  // then the FP_EXTEND of the call result is not a nop. It's not safe to
2853  // perform a tailcall optimization here.
2854  if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2855    return false;
2856
2857  CallingConv::ID CallerCC = CallerF->getCallingConv();
2858  bool CCMatch = CallerCC == CalleeCC;
2859
2860  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2861    if (IsTailCallConvention(CalleeCC) && CCMatch)
2862      return true;
2863    return false;
2864  }
2865
2866  // Look for obvious safe cases to perform tail call optimization that do not
2867  // require ABI changes. This is what gcc calls sibcall.
2868
2869  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2870  // emit a special epilogue.
2871  if (RegInfo->needsStackRealignment(MF))
2872    return false;
2873
2874  // Also avoid sibcall optimization if either caller or callee uses struct
2875  // return semantics.
2876  if (isCalleeStructRet || isCallerStructRet)
2877    return false;
2878
2879  // An stdcall caller is expected to clean up its arguments; the callee
2880  // isn't going to do that.
2881  if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2882    return false;
2883
2884  // Do not sibcall optimize vararg calls unless all arguments are passed via
2885  // registers.
2886  if (isVarArg && !Outs.empty()) {
2887
2888    // Optimizing for varargs on Win64 is unlikely to be safe without
2889    // additional testing.
2890    if (Subtarget->isTargetWin64())
2891      return false;
2892
2893    SmallVector<CCValAssign, 16> ArgLocs;
2894    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2895                   getTargetMachine(), ArgLocs, *DAG.getContext());
2896
2897    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2898    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2899      if (!ArgLocs[i].isRegLoc())
2900        return false;
2901  }
2902
2903  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2904  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2905  // this into a sibcall.
2906  bool Unused = false;
2907  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2908    if (!Ins[i].Used) {
2909      Unused = true;
2910      break;
2911    }
2912  }
2913  if (Unused) {
2914    SmallVector<CCValAssign, 16> RVLocs;
2915    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2916                   getTargetMachine(), RVLocs, *DAG.getContext());
2917    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2918    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2919      CCValAssign &VA = RVLocs[i];
2920      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2921        return false;
2922    }
2923  }
2924
2925  // If the calling conventions do not match, then we'd better make sure the
2926  // results are returned in the same way as what the caller expects.
2927  if (!CCMatch) {
2928    SmallVector<CCValAssign, 16> RVLocs1;
2929    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2930                    getTargetMachine(), RVLocs1, *DAG.getContext());
2931    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2932
2933    SmallVector<CCValAssign, 16> RVLocs2;
2934    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2935                    getTargetMachine(), RVLocs2, *DAG.getContext());
2936    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2937
2938    if (RVLocs1.size() != RVLocs2.size())
2939      return false;
2940    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2941      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2942        return false;
2943      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2944        return false;
2945      if (RVLocs1[i].isRegLoc()) {
2946        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2947          return false;
2948      } else {
2949        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2950          return false;
2951      }
2952    }
2953  }
2954
2955  // If the callee takes no arguments then go on to check the results of the
2956  // call.
2957  if (!Outs.empty()) {
2958    // Check if stack adjustment is needed. For now, do not do this if any
2959    // argument is passed on the stack.
2960    SmallVector<CCValAssign, 16> ArgLocs;
2961    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2962                   getTargetMachine(), ArgLocs, *DAG.getContext());
2963
2964    // Allocate shadow area for Win64
2965    if (Subtarget->isTargetWin64()) {
2966      CCInfo.AllocateStack(32, 8);
2967    }
2968
2969    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2970    if (CCInfo.getNextStackOffset()) {
2971      MachineFunction &MF = DAG.getMachineFunction();
2972      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2973        return false;
2974
2975      // Check if the arguments are already laid out in the right way as
2976      // the caller's fixed stack objects.
2977      MachineFrameInfo *MFI = MF.getFrameInfo();
2978      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2979      const X86InstrInfo *TII =
2980        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2981      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2982        CCValAssign &VA = ArgLocs[i];
2983        SDValue Arg = OutVals[i];
2984        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2985        if (VA.getLocInfo() == CCValAssign::Indirect)
2986          return false;
2987        if (!VA.isRegLoc()) {
2988          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2989                                   MFI, MRI, TII))
2990            return false;
2991        }
2992      }
2993    }
2994
2995    // If the tailcall address may be in a register, then make sure it's
2996    // possible to register allocate for it. In 32-bit, the call address can
2997    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2998    // callee-saved registers are restored. These happen to be the same
2999    // registers used to pass 'inreg' arguments so watch out for those.
3000    if (!Subtarget->is64Bit() &&
3001        ((!isa<GlobalAddressSDNode>(Callee) &&
3002          !isa<ExternalSymbolSDNode>(Callee)) ||
3003         getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3004      unsigned NumInRegs = 0;
3005      // In PIC we need an extra register to formulate the address computation
3006      // for the callee.
3007      unsigned MaxInRegs =
3008          (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3009
3010      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3011        CCValAssign &VA = ArgLocs[i];
3012        if (!VA.isRegLoc())
3013          continue;
3014        unsigned Reg = VA.getLocReg();
3015        switch (Reg) {
3016        default: break;
3017        case X86::EAX: case X86::EDX: case X86::ECX:
3018          if (++NumInRegs == MaxInRegs)
3019            return false;
3020          break;
3021        }
3022      }
3023    }
3024  }
3025
3026  return true;
3027}
3028
3029FastISel *
3030X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3031                                  const TargetLibraryInfo *libInfo) const {
3032  return X86::createFastISel(funcInfo, libInfo);
3033}
3034
3035//===----------------------------------------------------------------------===//
3036//                           Other Lowering Hooks
3037//===----------------------------------------------------------------------===//
3038
3039static bool MayFoldLoad(SDValue Op) {
3040  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3041}
3042
3043static bool MayFoldIntoStore(SDValue Op) {
3044  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3045}
3046
3047static bool isTargetShuffle(unsigned Opcode) {
3048  switch(Opcode) {
3049  default: return false;
3050  case X86ISD::PSHUFD:
3051  case X86ISD::PSHUFHW:
3052  case X86ISD::PSHUFLW:
3053  case X86ISD::SHUFP:
3054  case X86ISD::PALIGNR:
3055  case X86ISD::MOVLHPS:
3056  case X86ISD::MOVLHPD:
3057  case X86ISD::MOVHLPS:
3058  case X86ISD::MOVLPS:
3059  case X86ISD::MOVLPD:
3060  case X86ISD::MOVSHDUP:
3061  case X86ISD::MOVSLDUP:
3062  case X86ISD::MOVDDUP:
3063  case X86ISD::MOVSS:
3064  case X86ISD::MOVSD:
3065  case X86ISD::UNPCKL:
3066  case X86ISD::UNPCKH:
3067  case X86ISD::VPERMILP:
3068  case X86ISD::VPERM2X128:
3069  case X86ISD::VPERMI:
3070    return true;
3071  }
3072}
3073
3074static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3075                                    SDValue V1, SelectionDAG &DAG) {
3076  switch(Opc) {
3077  default: llvm_unreachable("Unknown x86 shuffle node");
3078  case X86ISD::MOVSHDUP:
3079  case X86ISD::MOVSLDUP:
3080  case X86ISD::MOVDDUP:
3081    return DAG.getNode(Opc, dl, VT, V1);
3082  }
3083}
3084
3085static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3086                                    SDValue V1, unsigned TargetMask,
3087                                    SelectionDAG &DAG) {
3088  switch(Opc) {
3089  default: llvm_unreachable("Unknown x86 shuffle node");
3090  case X86ISD::PSHUFD:
3091  case X86ISD::PSHUFHW:
3092  case X86ISD::PSHUFLW:
3093  case X86ISD::VPERMILP:
3094  case X86ISD::VPERMI:
3095    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3096  }
3097}
3098
3099static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3100                                    SDValue V1, SDValue V2, unsigned TargetMask,
3101                                    SelectionDAG &DAG) {
3102  switch(Opc) {
3103  default: llvm_unreachable("Unknown x86 shuffle node");
3104  case X86ISD::PALIGNR:
3105  case X86ISD::SHUFP:
3106  case X86ISD::VPERM2X128:
3107    return DAG.getNode(Opc, dl, VT, V1, V2,
3108                       DAG.getConstant(TargetMask, MVT::i8));
3109  }
3110}
3111
3112static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3113                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
3114  switch(Opc) {
3115  default: llvm_unreachable("Unknown x86 shuffle node");
3116  case X86ISD::MOVLHPS:
3117  case X86ISD::MOVLHPD:
3118  case X86ISD::MOVHLPS:
3119  case X86ISD::MOVLPS:
3120  case X86ISD::MOVLPD:
3121  case X86ISD::MOVSS:
3122  case X86ISD::MOVSD:
3123  case X86ISD::UNPCKL:
3124  case X86ISD::UNPCKH:
3125    return DAG.getNode(Opc, dl, VT, V1, V2);
3126  }
3127}
3128
3129SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3130  MachineFunction &MF = DAG.getMachineFunction();
3131  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3132  int ReturnAddrIndex = FuncInfo->getRAIndex();
3133
3134  if (ReturnAddrIndex == 0) {
3135    // Set up a frame object for the return address.
3136    unsigned SlotSize = RegInfo->getSlotSize();
3137    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3138                                                           false);
3139    FuncInfo->setRAIndex(ReturnAddrIndex);
3140  }
3141
3142  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3143}
3144
3145bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3146                                       bool hasSymbolicDisplacement) {
3147  // Offset should fit into 32 bit immediate field.
3148  if (!isInt<32>(Offset))
3149    return false;
3150
3151  // If we don't have a symbolic displacement - we don't have any extra
3152  // restrictions.
3153  if (!hasSymbolicDisplacement)
3154    return true;
3155
3156  // FIXME: Some tweaks might be needed for medium code model.
3157  if (M != CodeModel::Small && M != CodeModel::Kernel)
3158    return false;
3159
3160  // For small code model we assume that latest object is 16MB before end of 31
3161  // bits boundary. We may also accept pretty large negative constants knowing
3162  // that all objects are in the positive half of address space.
3163  if (M == CodeModel::Small && Offset < 16*1024*1024)
3164    return true;
3165
3166  // For kernel code model we know that all object resist in the negative half
3167  // of 32bits address space. We may not accept negative offsets, since they may
3168  // be just off and we may accept pretty large positive ones.
3169  if (M == CodeModel::Kernel && Offset > 0)
3170    return true;
3171
3172  return false;
3173}
3174
3175/// isCalleePop - Determines whether the callee is required to pop its
3176/// own arguments. Callee pop is necessary to support tail calls.
3177bool X86::isCalleePop(CallingConv::ID CallingConv,
3178                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3179  if (IsVarArg)
3180    return false;
3181
3182  switch (CallingConv) {
3183  default:
3184    return false;
3185  case CallingConv::X86_StdCall:
3186    return !is64Bit;
3187  case CallingConv::X86_FastCall:
3188    return !is64Bit;
3189  case CallingConv::X86_ThisCall:
3190    return !is64Bit;
3191  case CallingConv::Fast:
3192    return TailCallOpt;
3193  case CallingConv::GHC:
3194    return TailCallOpt;
3195  case CallingConv::HiPE:
3196    return TailCallOpt;
3197  }
3198}
3199
3200/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3201/// specific condition code, returning the condition code and the LHS/RHS of the
3202/// comparison to make.
3203static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3204                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3205  if (!isFP) {
3206    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3207      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3208        // X > -1   -> X == 0, jump !sign.
3209        RHS = DAG.getConstant(0, RHS.getValueType());
3210        return X86::COND_NS;
3211      }
3212      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3213        // X < 0   -> X == 0, jump on sign.
3214        return X86::COND_S;
3215      }
3216      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3217        // X < 1   -> X <= 0
3218        RHS = DAG.getConstant(0, RHS.getValueType());
3219        return X86::COND_LE;
3220      }
3221    }
3222
3223    switch (SetCCOpcode) {
3224    default: llvm_unreachable("Invalid integer condition!");
3225    case ISD::SETEQ:  return X86::COND_E;
3226    case ISD::SETGT:  return X86::COND_G;
3227    case ISD::SETGE:  return X86::COND_GE;
3228    case ISD::SETLT:  return X86::COND_L;
3229    case ISD::SETLE:  return X86::COND_LE;
3230    case ISD::SETNE:  return X86::COND_NE;
3231    case ISD::SETULT: return X86::COND_B;
3232    case ISD::SETUGT: return X86::COND_A;
3233    case ISD::SETULE: return X86::COND_BE;
3234    case ISD::SETUGE: return X86::COND_AE;
3235    }
3236  }
3237
3238  // First determine if it is required or is profitable to flip the operands.
3239
3240  // If LHS is a foldable load, but RHS is not, flip the condition.
3241  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3242      !ISD::isNON_EXTLoad(RHS.getNode())) {
3243    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3244    std::swap(LHS, RHS);
3245  }
3246
3247  switch (SetCCOpcode) {
3248  default: break;
3249  case ISD::SETOLT:
3250  case ISD::SETOLE:
3251  case ISD::SETUGT:
3252  case ISD::SETUGE:
3253    std::swap(LHS, RHS);
3254    break;
3255  }
3256
3257  // On a floating point condition, the flags are set as follows:
3258  // ZF  PF  CF   op
3259  //  0 | 0 | 0 | X > Y
3260  //  0 | 0 | 1 | X < Y
3261  //  1 | 0 | 0 | X == Y
3262  //  1 | 1 | 1 | unordered
3263  switch (SetCCOpcode) {
3264  default: llvm_unreachable("Condcode should be pre-legalized away");
3265  case ISD::SETUEQ:
3266  case ISD::SETEQ:   return X86::COND_E;
3267  case ISD::SETOLT:              // flipped
3268  case ISD::SETOGT:
3269  case ISD::SETGT:   return X86::COND_A;
3270  case ISD::SETOLE:              // flipped
3271  case ISD::SETOGE:
3272  case ISD::SETGE:   return X86::COND_AE;
3273  case ISD::SETUGT:              // flipped
3274  case ISD::SETULT:
3275  case ISD::SETLT:   return X86::COND_B;
3276  case ISD::SETUGE:              // flipped
3277  case ISD::SETULE:
3278  case ISD::SETLE:   return X86::COND_BE;
3279  case ISD::SETONE:
3280  case ISD::SETNE:   return X86::COND_NE;
3281  case ISD::SETUO:   return X86::COND_P;
3282  case ISD::SETO:    return X86::COND_NP;
3283  case ISD::SETOEQ:
3284  case ISD::SETUNE:  return X86::COND_INVALID;
3285  }
3286}
3287
3288/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3289/// code. Current x86 isa includes the following FP cmov instructions:
3290/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3291static bool hasFPCMov(unsigned X86CC) {
3292  switch (X86CC) {
3293  default:
3294    return false;
3295  case X86::COND_B:
3296  case X86::COND_BE:
3297  case X86::COND_E:
3298  case X86::COND_P:
3299  case X86::COND_A:
3300  case X86::COND_AE:
3301  case X86::COND_NE:
3302  case X86::COND_NP:
3303    return true;
3304  }
3305}
3306
3307/// isFPImmLegal - Returns true if the target can instruction select the
3308/// specified FP immediate natively. If false, the legalizer will
3309/// materialize the FP immediate as a load from a constant pool.
3310bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3311  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3312    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3313      return true;
3314  }
3315  return false;
3316}
3317
3318/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3319/// the specified range (L, H].
3320static bool isUndefOrInRange(int Val, int Low, int Hi) {
3321  return (Val < 0) || (Val >= Low && Val < Hi);
3322}
3323
3324/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3325/// specified value.
3326static bool isUndefOrEqual(int Val, int CmpVal) {
3327  return (Val < 0 || Val == CmpVal);
3328}
3329
3330/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3331/// from position Pos and ending in Pos+Size, falls within the specified
3332/// sequential range (L, L+Pos]. or is undef.
3333static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3334                                       unsigned Pos, unsigned Size, int Low) {
3335  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3336    if (!isUndefOrEqual(Mask[i], Low))
3337      return false;
3338  return true;
3339}
3340
3341/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3342/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3343/// the second operand.
3344static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3345  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3346    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3347  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3348    return (Mask[0] < 2 && Mask[1] < 2);
3349  return false;
3350}
3351
3352/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3353/// is suitable for input to PSHUFHW.
3354static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3355  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3356    return false;
3357
3358  // Lower quadword copied in order or undef.
3359  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3360    return false;
3361
3362  // Upper quadword shuffled.
3363  for (unsigned i = 4; i != 8; ++i)
3364    if (!isUndefOrInRange(Mask[i], 4, 8))
3365      return false;
3366
3367  if (VT == MVT::v16i16) {
3368    // Lower quadword copied in order or undef.
3369    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3370      return false;
3371
3372    // Upper quadword shuffled.
3373    for (unsigned i = 12; i != 16; ++i)
3374      if (!isUndefOrInRange(Mask[i], 12, 16))
3375        return false;
3376  }
3377
3378  return true;
3379}
3380
3381/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3382/// is suitable for input to PSHUFLW.
3383static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3384  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3385    return false;
3386
3387  // Upper quadword copied in order.
3388  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3389    return false;
3390
3391  // Lower quadword shuffled.
3392  for (unsigned i = 0; i != 4; ++i)
3393    if (!isUndefOrInRange(Mask[i], 0, 4))
3394      return false;
3395
3396  if (VT == MVT::v16i16) {
3397    // Upper quadword copied in order.
3398    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3399      return false;
3400
3401    // Lower quadword shuffled.
3402    for (unsigned i = 8; i != 12; ++i)
3403      if (!isUndefOrInRange(Mask[i], 8, 12))
3404        return false;
3405  }
3406
3407  return true;
3408}
3409
3410/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3411/// is suitable for input to PALIGNR.
3412static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3413                          const X86Subtarget *Subtarget) {
3414  if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3415      (VT.is256BitVector() && !Subtarget->hasInt256()))
3416    return false;
3417
3418  unsigned NumElts = VT.getVectorNumElements();
3419  unsigned NumLanes = VT.getSizeInBits()/128;
3420  unsigned NumLaneElts = NumElts/NumLanes;
3421
3422  // Do not handle 64-bit element shuffles with palignr.
3423  if (NumLaneElts == 2)
3424    return false;
3425
3426  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3427    unsigned i;
3428    for (i = 0; i != NumLaneElts; ++i) {
3429      if (Mask[i+l] >= 0)
3430        break;
3431    }
3432
3433    // Lane is all undef, go to next lane
3434    if (i == NumLaneElts)
3435      continue;
3436
3437    int Start = Mask[i+l];
3438
3439    // Make sure its in this lane in one of the sources
3440    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3441        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3442      return false;
3443
3444    // If not lane 0, then we must match lane 0
3445    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3446      return false;
3447
3448    // Correct second source to be contiguous with first source
3449    if (Start >= (int)NumElts)
3450      Start -= NumElts - NumLaneElts;
3451
3452    // Make sure we're shifting in the right direction.
3453    if (Start <= (int)(i+l))
3454      return false;
3455
3456    Start -= i;
3457
3458    // Check the rest of the elements to see if they are consecutive.
3459    for (++i; i != NumLaneElts; ++i) {
3460      int Idx = Mask[i+l];
3461
3462      // Make sure its in this lane
3463      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3464          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3465        return false;
3466
3467      // If not lane 0, then we must match lane 0
3468      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3469        return false;
3470
3471      if (Idx >= (int)NumElts)
3472        Idx -= NumElts - NumLaneElts;
3473
3474      if (!isUndefOrEqual(Idx, Start+i))
3475        return false;
3476
3477    }
3478  }
3479
3480  return true;
3481}
3482
3483/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3484/// the two vector operands have swapped position.
3485static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3486                                     unsigned NumElems) {
3487  for (unsigned i = 0; i != NumElems; ++i) {
3488    int idx = Mask[i];
3489    if (idx < 0)
3490      continue;
3491    else if (idx < (int)NumElems)
3492      Mask[i] = idx + NumElems;
3493    else
3494      Mask[i] = idx - NumElems;
3495  }
3496}
3497
3498/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3499/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3500/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3501/// reverse of what x86 shuffles want.
3502static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3503                        bool Commuted = false) {
3504  if (!HasFp256 && VT.is256BitVector())
3505    return false;
3506
3507  unsigned NumElems = VT.getVectorNumElements();
3508  unsigned NumLanes = VT.getSizeInBits()/128;
3509  unsigned NumLaneElems = NumElems/NumLanes;
3510
3511  if (NumLaneElems != 2 && NumLaneElems != 4)
3512    return false;
3513
3514  // VSHUFPSY divides the resulting vector into 4 chunks.
3515  // The sources are also splitted into 4 chunks, and each destination
3516  // chunk must come from a different source chunk.
3517  //
3518  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3519  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3520  //
3521  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3522  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3523  //
3524  // VSHUFPDY divides the resulting vector into 4 chunks.
3525  // The sources are also splitted into 4 chunks, and each destination
3526  // chunk must come from a different source chunk.
3527  //
3528  //  SRC1 =>      X3       X2       X1       X0
3529  //  SRC2 =>      Y3       Y2       Y1       Y0
3530  //
3531  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3532  //
3533  unsigned HalfLaneElems = NumLaneElems/2;
3534  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3535    for (unsigned i = 0; i != NumLaneElems; ++i) {
3536      int Idx = Mask[i+l];
3537      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3538      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3539        return false;
3540      // For VSHUFPSY, the mask of the second half must be the same as the
3541      // first but with the appropriate offsets. This works in the same way as
3542      // VPERMILPS works with masks.
3543      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3544        continue;
3545      if (!isUndefOrEqual(Idx, Mask[i]+l))
3546        return false;
3547    }
3548  }
3549
3550  return true;
3551}
3552
3553/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3554/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3555static bool isMOVHLPSMask(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  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3565  return isUndefOrEqual(Mask[0], 6) &&
3566         isUndefOrEqual(Mask[1], 7) &&
3567         isUndefOrEqual(Mask[2], 2) &&
3568         isUndefOrEqual(Mask[3], 3);
3569}
3570
3571/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3572/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3573/// <2, 3, 2, 3>
3574static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3575  if (!VT.is128BitVector())
3576    return false;
3577
3578  unsigned NumElems = VT.getVectorNumElements();
3579
3580  if (NumElems != 4)
3581    return false;
3582
3583  return isUndefOrEqual(Mask[0], 2) &&
3584         isUndefOrEqual(Mask[1], 3) &&
3585         isUndefOrEqual(Mask[2], 2) &&
3586         isUndefOrEqual(Mask[3], 3);
3587}
3588
3589/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3590/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3591static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3592  if (!VT.is128BitVector())
3593    return false;
3594
3595  unsigned NumElems = VT.getVectorNumElements();
3596
3597  if (NumElems != 2 && NumElems != 4)
3598    return false;
3599
3600  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3601    if (!isUndefOrEqual(Mask[i], i + NumElems))
3602      return false;
3603
3604  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3605    if (!isUndefOrEqual(Mask[i], i))
3606      return false;
3607
3608  return true;
3609}
3610
3611/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3612/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3613static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3614  if (!VT.is128BitVector())
3615    return false;
3616
3617  unsigned NumElems = VT.getVectorNumElements();
3618
3619  if (NumElems != 2 && NumElems != 4)
3620    return false;
3621
3622  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3623    if (!isUndefOrEqual(Mask[i], i))
3624      return false;
3625
3626  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3627    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3628      return false;
3629
3630  return true;
3631}
3632
3633//
3634// Some special combinations that can be optimized.
3635//
3636static
3637SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3638                               SelectionDAG &DAG) {
3639  MVT VT = SVOp->getValueType(0).getSimpleVT();
3640  DebugLoc dl = SVOp->getDebugLoc();
3641
3642  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3643    return SDValue();
3644
3645  ArrayRef<int> Mask = SVOp->getMask();
3646
3647  // These are the special masks that may be optimized.
3648  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3649  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3650  bool MatchEvenMask = true;
3651  bool MatchOddMask  = true;
3652  for (int i=0; i<8; ++i) {
3653    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3654      MatchEvenMask = false;
3655    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3656      MatchOddMask = false;
3657  }
3658
3659  if (!MatchEvenMask && !MatchOddMask)
3660    return SDValue();
3661
3662  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3663
3664  SDValue Op0 = SVOp->getOperand(0);
3665  SDValue Op1 = SVOp->getOperand(1);
3666
3667  if (MatchEvenMask) {
3668    // Shift the second operand right to 32 bits.
3669    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3670    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3671  } else {
3672    // Shift the first operand left to 32 bits.
3673    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3674    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3675  }
3676  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3677  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3678}
3679
3680/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3681/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3682static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3683                         bool HasInt256, bool V2IsSplat = false) {
3684  unsigned NumElts = VT.getVectorNumElements();
3685
3686  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3687         "Unsupported vector type for unpckh");
3688
3689  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3690      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3691    return false;
3692
3693  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3694  // independently on 128-bit lanes.
3695  unsigned NumLanes = VT.getSizeInBits()/128;
3696  unsigned NumLaneElts = NumElts/NumLanes;
3697
3698  for (unsigned l = 0; l != NumLanes; ++l) {
3699    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3700         i != (l+1)*NumLaneElts;
3701         i += 2, ++j) {
3702      int BitI  = Mask[i];
3703      int BitI1 = Mask[i+1];
3704      if (!isUndefOrEqual(BitI, j))
3705        return false;
3706      if (V2IsSplat) {
3707        if (!isUndefOrEqual(BitI1, NumElts))
3708          return false;
3709      } else {
3710        if (!isUndefOrEqual(BitI1, j + NumElts))
3711          return false;
3712      }
3713    }
3714  }
3715
3716  return true;
3717}
3718
3719/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3720/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3721static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3722                         bool HasInt256, bool V2IsSplat = false) {
3723  unsigned NumElts = VT.getVectorNumElements();
3724
3725  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3726         "Unsupported vector type for unpckh");
3727
3728  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3729      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3730    return false;
3731
3732  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3733  // independently on 128-bit lanes.
3734  unsigned NumLanes = VT.getSizeInBits()/128;
3735  unsigned NumLaneElts = NumElts/NumLanes;
3736
3737  for (unsigned l = 0; l != NumLanes; ++l) {
3738    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3739         i != (l+1)*NumLaneElts; i += 2, ++j) {
3740      int BitI  = Mask[i];
3741      int BitI1 = Mask[i+1];
3742      if (!isUndefOrEqual(BitI, j))
3743        return false;
3744      if (V2IsSplat) {
3745        if (isUndefOrEqual(BitI1, NumElts))
3746          return false;
3747      } else {
3748        if (!isUndefOrEqual(BitI1, j+NumElts))
3749          return false;
3750      }
3751    }
3752  }
3753  return true;
3754}
3755
3756/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3757/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3758/// <0, 0, 1, 1>
3759static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3760  unsigned NumElts = VT.getVectorNumElements();
3761  bool Is256BitVec = VT.is256BitVector();
3762
3763  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3764         "Unsupported vector type for unpckh");
3765
3766  if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3767      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3768    return false;
3769
3770  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3771  // FIXME: Need a better way to get rid of this, there's no latency difference
3772  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3773  // the former later. We should also remove the "_undef" special mask.
3774  if (NumElts == 4 && Is256BitVec)
3775    return false;
3776
3777  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3778  // independently on 128-bit lanes.
3779  unsigned NumLanes = VT.getSizeInBits()/128;
3780  unsigned NumLaneElts = NumElts/NumLanes;
3781
3782  for (unsigned l = 0; l != NumLanes; ++l) {
3783    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3784         i != (l+1)*NumLaneElts;
3785         i += 2, ++j) {
3786      int BitI  = Mask[i];
3787      int BitI1 = Mask[i+1];
3788
3789      if (!isUndefOrEqual(BitI, j))
3790        return false;
3791      if (!isUndefOrEqual(BitI1, j))
3792        return false;
3793    }
3794  }
3795
3796  return true;
3797}
3798
3799/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3800/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3801/// <2, 2, 3, 3>
3802static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3803  unsigned NumElts = VT.getVectorNumElements();
3804
3805  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3806         "Unsupported vector type for unpckh");
3807
3808  if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3809      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3810    return false;
3811
3812  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3813  // independently on 128-bit lanes.
3814  unsigned NumLanes = VT.getSizeInBits()/128;
3815  unsigned NumLaneElts = NumElts/NumLanes;
3816
3817  for (unsigned l = 0; l != NumLanes; ++l) {
3818    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3819         i != (l+1)*NumLaneElts; i += 2, ++j) {
3820      int BitI  = Mask[i];
3821      int BitI1 = Mask[i+1];
3822      if (!isUndefOrEqual(BitI, j))
3823        return false;
3824      if (!isUndefOrEqual(BitI1, j))
3825        return false;
3826    }
3827  }
3828  return true;
3829}
3830
3831/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3832/// specifies a shuffle of elements that is suitable for input to MOVSS,
3833/// MOVSD, and MOVD, i.e. setting the lowest element.
3834static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3835  if (VT.getVectorElementType().getSizeInBits() < 32)
3836    return false;
3837  if (!VT.is128BitVector())
3838    return false;
3839
3840  unsigned NumElts = VT.getVectorNumElements();
3841
3842  if (!isUndefOrEqual(Mask[0], NumElts))
3843    return false;
3844
3845  for (unsigned i = 1; i != NumElts; ++i)
3846    if (!isUndefOrEqual(Mask[i], i))
3847      return false;
3848
3849  return true;
3850}
3851
3852/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3853/// as permutations between 128-bit chunks or halves. As an example: this
3854/// shuffle bellow:
3855///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3856/// The first half comes from the second half of V1 and the second half from the
3857/// the second half of V2.
3858static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3859  if (!HasFp256 || !VT.is256BitVector())
3860    return false;
3861
3862  // The shuffle result is divided into half A and half B. In total the two
3863  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3864  // B must come from C, D, E or F.
3865  unsigned HalfSize = VT.getVectorNumElements()/2;
3866  bool MatchA = false, MatchB = false;
3867
3868  // Check if A comes from one of C, D, E, F.
3869  for (unsigned Half = 0; Half != 4; ++Half) {
3870    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3871      MatchA = true;
3872      break;
3873    }
3874  }
3875
3876  // Check if B comes from one of C, D, E, F.
3877  for (unsigned Half = 0; Half != 4; ++Half) {
3878    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3879      MatchB = true;
3880      break;
3881    }
3882  }
3883
3884  return MatchA && MatchB;
3885}
3886
3887/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3888/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3889static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3890  MVT VT = SVOp->getValueType(0).getSimpleVT();
3891
3892  unsigned HalfSize = VT.getVectorNumElements()/2;
3893
3894  unsigned FstHalf = 0, SndHalf = 0;
3895  for (unsigned i = 0; i < HalfSize; ++i) {
3896    if (SVOp->getMaskElt(i) > 0) {
3897      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3898      break;
3899    }
3900  }
3901  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3902    if (SVOp->getMaskElt(i) > 0) {
3903      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3904      break;
3905    }
3906  }
3907
3908  return (FstHalf | (SndHalf << 4));
3909}
3910
3911/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3912/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3913/// Note that VPERMIL mask matching is different depending whether theunderlying
3914/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3915/// to the same elements of the low, but to the higher half of the source.
3916/// In VPERMILPD the two lanes could be shuffled independently of each other
3917/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3918static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3919  if (!HasFp256)
3920    return false;
3921
3922  unsigned NumElts = VT.getVectorNumElements();
3923  // Only match 256-bit with 32/64-bit types
3924  if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3925    return false;
3926
3927  unsigned NumLanes = VT.getSizeInBits()/128;
3928  unsigned LaneSize = NumElts/NumLanes;
3929  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3930    for (unsigned i = 0; i != LaneSize; ++i) {
3931      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3932        return false;
3933      if (NumElts != 8 || l == 0)
3934        continue;
3935      // VPERMILPS handling
3936      if (Mask[i] < 0)
3937        continue;
3938      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3939        return false;
3940    }
3941  }
3942
3943  return true;
3944}
3945
3946/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3947/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3948/// element of vector 2 and the other elements to come from vector 1 in order.
3949static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3950                               bool V2IsSplat = false, bool V2IsUndef = false) {
3951  if (!VT.is128BitVector())
3952    return false;
3953
3954  unsigned NumOps = VT.getVectorNumElements();
3955  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3956    return false;
3957
3958  if (!isUndefOrEqual(Mask[0], 0))
3959    return false;
3960
3961  for (unsigned i = 1; i != NumOps; ++i)
3962    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3963          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3964          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3965      return false;
3966
3967  return true;
3968}
3969
3970/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3971/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3972/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3973static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3974                           const X86Subtarget *Subtarget) {
3975  if (!Subtarget->hasSSE3())
3976    return false;
3977
3978  unsigned NumElems = VT.getVectorNumElements();
3979
3980  if ((VT.is128BitVector() && NumElems != 4) ||
3981      (VT.is256BitVector() && NumElems != 8))
3982    return false;
3983
3984  // "i+1" is the value the indexed mask element must have
3985  for (unsigned i = 0; i != NumElems; i += 2)
3986    if (!isUndefOrEqual(Mask[i], i+1) ||
3987        !isUndefOrEqual(Mask[i+1], i+1))
3988      return false;
3989
3990  return true;
3991}
3992
3993/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3994/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3995/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3996static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3997                           const X86Subtarget *Subtarget) {
3998  if (!Subtarget->hasSSE3())
3999    return false;
4000
4001  unsigned NumElems = VT.getVectorNumElements();
4002
4003  if ((VT.is128BitVector() && NumElems != 4) ||
4004      (VT.is256BitVector() && NumElems != 8))
4005    return false;
4006
4007  // "i" is the value the indexed mask element must have
4008  for (unsigned i = 0; i != NumElems; i += 2)
4009    if (!isUndefOrEqual(Mask[i], i) ||
4010        !isUndefOrEqual(Mask[i+1], i))
4011      return false;
4012
4013  return true;
4014}
4015
4016/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4017/// specifies a shuffle of elements that is suitable for input to 256-bit
4018/// version of MOVDDUP.
4019static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4020  if (!HasFp256 || !VT.is256BitVector())
4021    return false;
4022
4023  unsigned NumElts = VT.getVectorNumElements();
4024  if (NumElts != 4)
4025    return false;
4026
4027  for (unsigned i = 0; i != NumElts/2; ++i)
4028    if (!isUndefOrEqual(Mask[i], 0))
4029      return false;
4030  for (unsigned i = NumElts/2; i != NumElts; ++i)
4031    if (!isUndefOrEqual(Mask[i], NumElts/2))
4032      return false;
4033  return true;
4034}
4035
4036/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4037/// specifies a shuffle of elements that is suitable for input to 128-bit
4038/// version of MOVDDUP.
4039static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4040  if (!VT.is128BitVector())
4041    return false;
4042
4043  unsigned e = VT.getVectorNumElements() / 2;
4044  for (unsigned i = 0; i != e; ++i)
4045    if (!isUndefOrEqual(Mask[i], i))
4046      return false;
4047  for (unsigned i = 0; i != e; ++i)
4048    if (!isUndefOrEqual(Mask[e+i], i))
4049      return false;
4050  return true;
4051}
4052
4053/// isVEXTRACTF128Index - Return true if the specified
4054/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4055/// suitable for input to VEXTRACTF128.
4056bool X86::isVEXTRACTF128Index(SDNode *N) {
4057  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4058    return false;
4059
4060  // The index should be aligned on a 128-bit boundary.
4061  uint64_t Index =
4062    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4063
4064  MVT VT = N->getValueType(0).getSimpleVT();
4065  unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4066  bool Result = (Index * ElSize) % 128 == 0;
4067
4068  return Result;
4069}
4070
4071/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4072/// operand specifies a subvector insert that is suitable for input to
4073/// VINSERTF128.
4074bool X86::isVINSERTF128Index(SDNode *N) {
4075  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076    return false;
4077
4078  // The index should be aligned on a 128-bit boundary.
4079  uint64_t Index =
4080    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4081
4082  MVT VT = N->getValueType(0).getSimpleVT();
4083  unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4084  bool Result = (Index * ElSize) % 128 == 0;
4085
4086  return Result;
4087}
4088
4089/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4090/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4091/// Handles 128-bit and 256-bit.
4092static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4093  MVT VT = N->getValueType(0).getSimpleVT();
4094
4095  assert((VT.is128BitVector() || VT.is256BitVector()) &&
4096         "Unsupported vector type for PSHUF/SHUFP");
4097
4098  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4099  // independently on 128-bit lanes.
4100  unsigned NumElts = VT.getVectorNumElements();
4101  unsigned NumLanes = VT.getSizeInBits()/128;
4102  unsigned NumLaneElts = NumElts/NumLanes;
4103
4104  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4105         "Only supports 2 or 4 elements per lane");
4106
4107  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4108  unsigned Mask = 0;
4109  for (unsigned i = 0; i != NumElts; ++i) {
4110    int Elt = N->getMaskElt(i);
4111    if (Elt < 0) continue;
4112    Elt &= NumLaneElts - 1;
4113    unsigned ShAmt = (i << Shift) % 8;
4114    Mask |= Elt << ShAmt;
4115  }
4116
4117  return Mask;
4118}
4119
4120/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4121/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4122static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4123  MVT VT = N->getValueType(0).getSimpleVT();
4124
4125  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4126         "Unsupported vector type for PSHUFHW");
4127
4128  unsigned NumElts = VT.getVectorNumElements();
4129
4130  unsigned Mask = 0;
4131  for (unsigned l = 0; l != NumElts; l += 8) {
4132    // 8 nodes per lane, but we only care about the last 4.
4133    for (unsigned i = 0; i < 4; ++i) {
4134      int Elt = N->getMaskElt(l+i+4);
4135      if (Elt < 0) continue;
4136      Elt &= 0x3; // only 2-bits.
4137      Mask |= Elt << (i * 2);
4138    }
4139  }
4140
4141  return Mask;
4142}
4143
4144/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4145/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4146static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4147  MVT VT = N->getValueType(0).getSimpleVT();
4148
4149  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4150         "Unsupported vector type for PSHUFHW");
4151
4152  unsigned NumElts = VT.getVectorNumElements();
4153
4154  unsigned Mask = 0;
4155  for (unsigned l = 0; l != NumElts; l += 8) {
4156    // 8 nodes per lane, but we only care about the first 4.
4157    for (unsigned i = 0; i < 4; ++i) {
4158      int Elt = N->getMaskElt(l+i);
4159      if (Elt < 0) continue;
4160      Elt &= 0x3; // only 2-bits
4161      Mask |= Elt << (i * 2);
4162    }
4163  }
4164
4165  return Mask;
4166}
4167
4168/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4169/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4170static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4171  MVT VT = SVOp->getValueType(0).getSimpleVT();
4172  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4173
4174  unsigned NumElts = VT.getVectorNumElements();
4175  unsigned NumLanes = VT.getSizeInBits()/128;
4176  unsigned NumLaneElts = NumElts/NumLanes;
4177
4178  int Val = 0;
4179  unsigned i;
4180  for (i = 0; i != NumElts; ++i) {
4181    Val = SVOp->getMaskElt(i);
4182    if (Val >= 0)
4183      break;
4184  }
4185  if (Val >= (int)NumElts)
4186    Val -= NumElts - NumLaneElts;
4187
4188  assert(Val - i > 0 && "PALIGNR imm should be positive");
4189  return (Val - i) * EltSize;
4190}
4191
4192/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4193/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4194/// instructions.
4195unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4196  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4197    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4198
4199  uint64_t Index =
4200    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4201
4202  MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4203  MVT ElVT = VecVT.getVectorElementType();
4204
4205  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4206  return Index / NumElemsPerChunk;
4207}
4208
4209/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4210/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4211/// instructions.
4212unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4213  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4214    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4215
4216  uint64_t Index =
4217    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4218
4219  MVT VecVT = N->getValueType(0).getSimpleVT();
4220  MVT ElVT = VecVT.getVectorElementType();
4221
4222  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4223  return Index / NumElemsPerChunk;
4224}
4225
4226/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4227/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4228/// Handles 256-bit.
4229static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4230  MVT VT = N->getValueType(0).getSimpleVT();
4231
4232  unsigned NumElts = VT.getVectorNumElements();
4233
4234  assert((VT.is256BitVector() && NumElts == 4) &&
4235         "Unsupported vector type for VPERMQ/VPERMPD");
4236
4237  unsigned Mask = 0;
4238  for (unsigned i = 0; i != NumElts; ++i) {
4239    int Elt = N->getMaskElt(i);
4240    if (Elt < 0)
4241      continue;
4242    Mask |= Elt << (i*2);
4243  }
4244
4245  return Mask;
4246}
4247/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4248/// constant +0.0.
4249bool X86::isZeroNode(SDValue Elt) {
4250  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4251    return CN->isNullValue();
4252  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4253    return CFP->getValueAPF().isPosZero();
4254  return false;
4255}
4256
4257/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4258/// their permute mask.
4259static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4260                                    SelectionDAG &DAG) {
4261  MVT VT = SVOp->getValueType(0).getSimpleVT();
4262  unsigned NumElems = VT.getVectorNumElements();
4263  SmallVector<int, 8> MaskVec;
4264
4265  for (unsigned i = 0; i != NumElems; ++i) {
4266    int Idx = SVOp->getMaskElt(i);
4267    if (Idx >= 0) {
4268      if (Idx < (int)NumElems)
4269        Idx += NumElems;
4270      else
4271        Idx -= NumElems;
4272    }
4273    MaskVec.push_back(Idx);
4274  }
4275  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4276                              SVOp->getOperand(0), &MaskVec[0]);
4277}
4278
4279/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4280/// match movhlps. The lower half elements should come from upper half of
4281/// V1 (and in order), and the upper half elements should come from the upper
4282/// half of V2 (and in order).
4283static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4284  if (!VT.is128BitVector())
4285    return false;
4286  if (VT.getVectorNumElements() != 4)
4287    return false;
4288  for (unsigned i = 0, e = 2; i != e; ++i)
4289    if (!isUndefOrEqual(Mask[i], i+2))
4290      return false;
4291  for (unsigned i = 2; i != 4; ++i)
4292    if (!isUndefOrEqual(Mask[i], i+4))
4293      return false;
4294  return true;
4295}
4296
4297/// isScalarLoadToVector - Returns true if the node is a scalar load that
4298/// is promoted to a vector. It also returns the LoadSDNode by reference if
4299/// required.
4300static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4301  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4302    return false;
4303  N = N->getOperand(0).getNode();
4304  if (!ISD::isNON_EXTLoad(N))
4305    return false;
4306  if (LD)
4307    *LD = cast<LoadSDNode>(N);
4308  return true;
4309}
4310
4311// Test whether the given value is a vector value which will be legalized
4312// into a load.
4313static bool WillBeConstantPoolLoad(SDNode *N) {
4314  if (N->getOpcode() != ISD::BUILD_VECTOR)
4315    return false;
4316
4317  // Check for any non-constant elements.
4318  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4319    switch (N->getOperand(i).getNode()->getOpcode()) {
4320    case ISD::UNDEF:
4321    case ISD::ConstantFP:
4322    case ISD::Constant:
4323      break;
4324    default:
4325      return false;
4326    }
4327
4328  // Vectors of all-zeros and all-ones are materialized with special
4329  // instructions rather than being loaded.
4330  return !ISD::isBuildVectorAllZeros(N) &&
4331         !ISD::isBuildVectorAllOnes(N);
4332}
4333
4334/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4335/// match movlp{s|d}. The lower half elements should come from lower half of
4336/// V1 (and in order), and the upper half elements should come from the upper
4337/// half of V2 (and in order). And since V1 will become the source of the
4338/// MOVLP, it must be either a vector load or a scalar load to vector.
4339static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4340                               ArrayRef<int> Mask, EVT VT) {
4341  if (!VT.is128BitVector())
4342    return false;
4343
4344  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4345    return false;
4346  // Is V2 is a vector load, don't do this transformation. We will try to use
4347  // load folding shufps op.
4348  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4349    return false;
4350
4351  unsigned NumElems = VT.getVectorNumElements();
4352
4353  if (NumElems != 2 && NumElems != 4)
4354    return false;
4355  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4356    if (!isUndefOrEqual(Mask[i], i))
4357      return false;
4358  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4359    if (!isUndefOrEqual(Mask[i], i+NumElems))
4360      return false;
4361  return true;
4362}
4363
4364/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4365/// all the same.
4366static bool isSplatVector(SDNode *N) {
4367  if (N->getOpcode() != ISD::BUILD_VECTOR)
4368    return false;
4369
4370  SDValue SplatValue = N->getOperand(0);
4371  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4372    if (N->getOperand(i) != SplatValue)
4373      return false;
4374  return true;
4375}
4376
4377/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4378/// to an zero vector.
4379/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4380static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4381  SDValue V1 = N->getOperand(0);
4382  SDValue V2 = N->getOperand(1);
4383  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4384  for (unsigned i = 0; i != NumElems; ++i) {
4385    int Idx = N->getMaskElt(i);
4386    if (Idx >= (int)NumElems) {
4387      unsigned Opc = V2.getOpcode();
4388      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4389        continue;
4390      if (Opc != ISD::BUILD_VECTOR ||
4391          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4392        return false;
4393    } else if (Idx >= 0) {
4394      unsigned Opc = V1.getOpcode();
4395      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4396        continue;
4397      if (Opc != ISD::BUILD_VECTOR ||
4398          !X86::isZeroNode(V1.getOperand(Idx)))
4399        return false;
4400    }
4401  }
4402  return true;
4403}
4404
4405/// getZeroVector - Returns a vector of specified type with all zero elements.
4406///
4407static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4408                             SelectionDAG &DAG, DebugLoc dl) {
4409  assert(VT.isVector() && "Expected a vector type");
4410
4411  // Always build SSE zero vectors as <4 x i32> bitcasted
4412  // to their dest type. This ensures they get CSE'd.
4413  SDValue Vec;
4414  if (VT.is128BitVector()) {  // SSE
4415    if (Subtarget->hasSSE2()) {  // SSE2
4416      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4417      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4418    } else { // SSE1
4419      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4420      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4421    }
4422  } else if (VT.is256BitVector()) { // AVX
4423    if (Subtarget->hasInt256()) { // AVX2
4424      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4425      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4426      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4427                        array_lengthof(Ops));
4428    } else {
4429      // 256-bit logic and arithmetic instructions in AVX are all
4430      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4431      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4432      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4433      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4434                        array_lengthof(Ops));
4435    }
4436  } else
4437    llvm_unreachable("Unexpected vector type");
4438
4439  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4440}
4441
4442/// getOnesVector - Returns a vector of specified type with all bits set.
4443/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4444/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4445/// Then bitcast to their original type, ensuring they get CSE'd.
4446static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4447                             DebugLoc dl) {
4448  assert(VT.isVector() && "Expected a vector type");
4449
4450  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4451  SDValue Vec;
4452  if (VT.is256BitVector()) {
4453    if (HasInt256) { // AVX2
4454      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4455      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4456                        array_lengthof(Ops));
4457    } else { // AVX
4458      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4459      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4460    }
4461  } else if (VT.is128BitVector()) {
4462    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4463  } else
4464    llvm_unreachable("Unexpected vector type");
4465
4466  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4467}
4468
4469/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4470/// that point to V2 points to its first element.
4471static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4472  for (unsigned i = 0; i != NumElems; ++i) {
4473    if (Mask[i] > (int)NumElems) {
4474      Mask[i] = NumElems;
4475    }
4476  }
4477}
4478
4479/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4480/// operation of specified width.
4481static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4482                       SDValue V2) {
4483  unsigned NumElems = VT.getVectorNumElements();
4484  SmallVector<int, 8> Mask;
4485  Mask.push_back(NumElems);
4486  for (unsigned i = 1; i != NumElems; ++i)
4487    Mask.push_back(i);
4488  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4489}
4490
4491/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4492static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4493                          SDValue V2) {
4494  unsigned NumElems = VT.getVectorNumElements();
4495  SmallVector<int, 8> Mask;
4496  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4497    Mask.push_back(i);
4498    Mask.push_back(i + NumElems);
4499  }
4500  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4501}
4502
4503/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4504static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4505                          SDValue V2) {
4506  unsigned NumElems = VT.getVectorNumElements();
4507  SmallVector<int, 8> Mask;
4508  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4509    Mask.push_back(i + Half);
4510    Mask.push_back(i + NumElems + Half);
4511  }
4512  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4513}
4514
4515// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4516// a generic shuffle instruction because the target has no such instructions.
4517// Generate shuffles which repeat i16 and i8 several times until they can be
4518// represented by v4f32 and then be manipulated by target suported shuffles.
4519static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4520  EVT VT = V.getValueType();
4521  int NumElems = VT.getVectorNumElements();
4522  DebugLoc dl = V.getDebugLoc();
4523
4524  while (NumElems > 4) {
4525    if (EltNo < NumElems/2) {
4526      V = getUnpackl(DAG, dl, VT, V, V);
4527    } else {
4528      V = getUnpackh(DAG, dl, VT, V, V);
4529      EltNo -= NumElems/2;
4530    }
4531    NumElems >>= 1;
4532  }
4533  return V;
4534}
4535
4536/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4537static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4538  EVT VT = V.getValueType();
4539  DebugLoc dl = V.getDebugLoc();
4540
4541  if (VT.is128BitVector()) {
4542    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4543    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4544    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4545                             &SplatMask[0]);
4546  } else if (VT.is256BitVector()) {
4547    // To use VPERMILPS to splat scalars, the second half of indicies must
4548    // refer to the higher part, which is a duplication of the lower one,
4549    // because VPERMILPS can only handle in-lane permutations.
4550    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4551                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4552
4553    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4554    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4555                             &SplatMask[0]);
4556  } else
4557    llvm_unreachable("Vector size not supported");
4558
4559  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4560}
4561
4562/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4563static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4564  EVT SrcVT = SV->getValueType(0);
4565  SDValue V1 = SV->getOperand(0);
4566  DebugLoc dl = SV->getDebugLoc();
4567
4568  int EltNo = SV->getSplatIndex();
4569  int NumElems = SrcVT.getVectorNumElements();
4570  bool Is256BitVec = SrcVT.is256BitVector();
4571
4572  assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4573         "Unknown how to promote splat for type");
4574
4575  // Extract the 128-bit part containing the splat element and update
4576  // the splat element index when it refers to the higher register.
4577  if (Is256BitVec) {
4578    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4579    if (EltNo >= NumElems/2)
4580      EltNo -= NumElems/2;
4581  }
4582
4583  // All i16 and i8 vector types can't be used directly by a generic shuffle
4584  // instruction because the target has no such instruction. Generate shuffles
4585  // which repeat i16 and i8 several times until they fit in i32, and then can
4586  // be manipulated by target suported shuffles.
4587  EVT EltVT = SrcVT.getVectorElementType();
4588  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4589    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4590
4591  // Recreate the 256-bit vector and place the same 128-bit vector
4592  // into the low and high part. This is necessary because we want
4593  // to use VPERM* to shuffle the vectors
4594  if (Is256BitVec) {
4595    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4596  }
4597
4598  return getLegalSplat(DAG, V1, EltNo);
4599}
4600
4601/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4602/// vector of zero or undef vector.  This produces a shuffle where the low
4603/// element of V2 is swizzled into the zero/undef vector, landing at element
4604/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4605static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4606                                           bool IsZero,
4607                                           const X86Subtarget *Subtarget,
4608                                           SelectionDAG &DAG) {
4609  EVT VT = V2.getValueType();
4610  SDValue V1 = IsZero
4611    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4612  unsigned NumElems = VT.getVectorNumElements();
4613  SmallVector<int, 16> MaskVec;
4614  for (unsigned i = 0; i != NumElems; ++i)
4615    // If this is the insertion idx, put the low elt of V2 here.
4616    MaskVec.push_back(i == Idx ? NumElems : i);
4617  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4618}
4619
4620/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4621/// target specific opcode. Returns true if the Mask could be calculated.
4622/// Sets IsUnary to true if only uses one source.
4623static bool getTargetShuffleMask(SDNode *N, MVT VT,
4624                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4625  unsigned NumElems = VT.getVectorNumElements();
4626  SDValue ImmN;
4627
4628  IsUnary = false;
4629  switch(N->getOpcode()) {
4630  case X86ISD::SHUFP:
4631    ImmN = N->getOperand(N->getNumOperands()-1);
4632    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4633    break;
4634  case X86ISD::UNPCKH:
4635    DecodeUNPCKHMask(VT, Mask);
4636    break;
4637  case X86ISD::UNPCKL:
4638    DecodeUNPCKLMask(VT, Mask);
4639    break;
4640  case X86ISD::MOVHLPS:
4641    DecodeMOVHLPSMask(NumElems, Mask);
4642    break;
4643  case X86ISD::MOVLHPS:
4644    DecodeMOVLHPSMask(NumElems, Mask);
4645    break;
4646  case X86ISD::PALIGNR:
4647    ImmN = N->getOperand(N->getNumOperands()-1);
4648    DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4649    break;
4650  case X86ISD::PSHUFD:
4651  case X86ISD::VPERMILP:
4652    ImmN = N->getOperand(N->getNumOperands()-1);
4653    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4654    IsUnary = true;
4655    break;
4656  case X86ISD::PSHUFHW:
4657    ImmN = N->getOperand(N->getNumOperands()-1);
4658    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4659    IsUnary = true;
4660    break;
4661  case X86ISD::PSHUFLW:
4662    ImmN = N->getOperand(N->getNumOperands()-1);
4663    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4664    IsUnary = true;
4665    break;
4666  case X86ISD::VPERMI:
4667    ImmN = N->getOperand(N->getNumOperands()-1);
4668    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4669    IsUnary = true;
4670    break;
4671  case X86ISD::MOVSS:
4672  case X86ISD::MOVSD: {
4673    // The index 0 always comes from the first element of the second source,
4674    // this is why MOVSS and MOVSD are used in the first place. The other
4675    // elements come from the other positions of the first source vector
4676    Mask.push_back(NumElems);
4677    for (unsigned i = 1; i != NumElems; ++i) {
4678      Mask.push_back(i);
4679    }
4680    break;
4681  }
4682  case X86ISD::VPERM2X128:
4683    ImmN = N->getOperand(N->getNumOperands()-1);
4684    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4685    if (Mask.empty()) return false;
4686    break;
4687  case X86ISD::MOVDDUP:
4688  case X86ISD::MOVLHPD:
4689  case X86ISD::MOVLPD:
4690  case X86ISD::MOVLPS:
4691  case X86ISD::MOVSHDUP:
4692  case X86ISD::MOVSLDUP:
4693    // Not yet implemented
4694    return false;
4695  default: llvm_unreachable("unknown target shuffle node");
4696  }
4697
4698  return true;
4699}
4700
4701/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4702/// element of the result of the vector shuffle.
4703static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4704                                   unsigned Depth) {
4705  if (Depth == 6)
4706    return SDValue();  // Limit search depth.
4707
4708  SDValue V = SDValue(N, 0);
4709  EVT VT = V.getValueType();
4710  unsigned Opcode = V.getOpcode();
4711
4712  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4713  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4714    int Elt = SV->getMaskElt(Index);
4715
4716    if (Elt < 0)
4717      return DAG.getUNDEF(VT.getVectorElementType());
4718
4719    unsigned NumElems = VT.getVectorNumElements();
4720    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4721                                         : SV->getOperand(1);
4722    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4723  }
4724
4725  // Recurse into target specific vector shuffles to find scalars.
4726  if (isTargetShuffle(Opcode)) {
4727    MVT ShufVT = V.getValueType().getSimpleVT();
4728    unsigned NumElems = ShufVT.getVectorNumElements();
4729    SmallVector<int, 16> ShuffleMask;
4730    bool IsUnary;
4731
4732    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4733      return SDValue();
4734
4735    int Elt = ShuffleMask[Index];
4736    if (Elt < 0)
4737      return DAG.getUNDEF(ShufVT.getVectorElementType());
4738
4739    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4740                                         : N->getOperand(1);
4741    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4742                               Depth+1);
4743  }
4744
4745  // Actual nodes that may contain scalar elements
4746  if (Opcode == ISD::BITCAST) {
4747    V = V.getOperand(0);
4748    EVT SrcVT = V.getValueType();
4749    unsigned NumElems = VT.getVectorNumElements();
4750
4751    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4752      return SDValue();
4753  }
4754
4755  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4756    return (Index == 0) ? V.getOperand(0)
4757                        : DAG.getUNDEF(VT.getVectorElementType());
4758
4759  if (V.getOpcode() == ISD::BUILD_VECTOR)
4760    return V.getOperand(Index);
4761
4762  return SDValue();
4763}
4764
4765/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4766/// shuffle operation which come from a consecutively from a zero. The
4767/// search can start in two different directions, from left or right.
4768static
4769unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4770                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4771  unsigned i;
4772  for (i = 0; i != NumElems; ++i) {
4773    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4774    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4775    if (!(Elt.getNode() &&
4776         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4777      break;
4778  }
4779
4780  return i;
4781}
4782
4783/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4784/// correspond consecutively to elements from one of the vector operands,
4785/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4786static
4787bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4788                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4789                              unsigned NumElems, unsigned &OpNum) {
4790  bool SeenV1 = false;
4791  bool SeenV2 = false;
4792
4793  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4794    int Idx = SVOp->getMaskElt(i);
4795    // Ignore undef indicies
4796    if (Idx < 0)
4797      continue;
4798
4799    if (Idx < (int)NumElems)
4800      SeenV1 = true;
4801    else
4802      SeenV2 = true;
4803
4804    // Only accept consecutive elements from the same vector
4805    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4806      return false;
4807  }
4808
4809  OpNum = SeenV1 ? 0 : 1;
4810  return true;
4811}
4812
4813/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4814/// logical left shift of a vector.
4815static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4816                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4817  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4818  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4819              false /* check zeros from right */, DAG);
4820  unsigned OpSrc;
4821
4822  if (!NumZeros)
4823    return false;
4824
4825  // Considering the elements in the mask that are not consecutive zeros,
4826  // check if they consecutively come from only one of the source vectors.
4827  //
4828  //               V1 = {X, A, B, C}     0
4829  //                         \  \  \    /
4830  //   vector_shuffle V1, V2 <1, 2, 3, X>
4831  //
4832  if (!isShuffleMaskConsecutive(SVOp,
4833            0,                   // Mask Start Index
4834            NumElems-NumZeros,   // Mask End Index(exclusive)
4835            NumZeros,            // Where to start looking in the src vector
4836            NumElems,            // Number of elements in vector
4837            OpSrc))              // Which source operand ?
4838    return false;
4839
4840  isLeft = false;
4841  ShAmt = NumZeros;
4842  ShVal = SVOp->getOperand(OpSrc);
4843  return true;
4844}
4845
4846/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4847/// logical left shift of a vector.
4848static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4849                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4850  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4851  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4852              true /* check zeros from left */, DAG);
4853  unsigned OpSrc;
4854
4855  if (!NumZeros)
4856    return false;
4857
4858  // Considering the elements in the mask that are not consecutive zeros,
4859  // check if they consecutively come from only one of the source vectors.
4860  //
4861  //                           0    { A, B, X, X } = V2
4862  //                          / \    /  /
4863  //   vector_shuffle V1, V2 <X, X, 4, 5>
4864  //
4865  if (!isShuffleMaskConsecutive(SVOp,
4866            NumZeros,     // Mask Start Index
4867            NumElems,     // Mask End Index(exclusive)
4868            0,            // Where to start looking in the src vector
4869            NumElems,     // Number of elements in vector
4870            OpSrc))       // Which source operand ?
4871    return false;
4872
4873  isLeft = true;
4874  ShAmt = NumZeros;
4875  ShVal = SVOp->getOperand(OpSrc);
4876  return true;
4877}
4878
4879/// isVectorShift - Returns true if the shuffle can be implemented as a
4880/// logical left or right shift of a vector.
4881static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4882                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4883  // Although the logic below support any bitwidth size, there are no
4884  // shift instructions which handle more than 128-bit vectors.
4885  if (!SVOp->getValueType(0).is128BitVector())
4886    return false;
4887
4888  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4889      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4890    return true;
4891
4892  return false;
4893}
4894
4895/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4896///
4897static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4898                                       unsigned NumNonZero, unsigned NumZero,
4899                                       SelectionDAG &DAG,
4900                                       const X86Subtarget* Subtarget,
4901                                       const TargetLowering &TLI) {
4902  if (NumNonZero > 8)
4903    return SDValue();
4904
4905  DebugLoc dl = Op.getDebugLoc();
4906  SDValue V(0, 0);
4907  bool First = true;
4908  for (unsigned i = 0; i < 16; ++i) {
4909    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4910    if (ThisIsNonZero && First) {
4911      if (NumZero)
4912        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4913      else
4914        V = DAG.getUNDEF(MVT::v8i16);
4915      First = false;
4916    }
4917
4918    if ((i & 1) != 0) {
4919      SDValue ThisElt(0, 0), LastElt(0, 0);
4920      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4921      if (LastIsNonZero) {
4922        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4923                              MVT::i16, Op.getOperand(i-1));
4924      }
4925      if (ThisIsNonZero) {
4926        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4927        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4928                              ThisElt, DAG.getConstant(8, MVT::i8));
4929        if (LastIsNonZero)
4930          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4931      } else
4932        ThisElt = LastElt;
4933
4934      if (ThisElt.getNode())
4935        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4936                        DAG.getIntPtrConstant(i/2));
4937    }
4938  }
4939
4940  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4941}
4942
4943/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4944///
4945static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4946                                     unsigned NumNonZero, unsigned NumZero,
4947                                     SelectionDAG &DAG,
4948                                     const X86Subtarget* Subtarget,
4949                                     const TargetLowering &TLI) {
4950  if (NumNonZero > 4)
4951    return SDValue();
4952
4953  DebugLoc dl = Op.getDebugLoc();
4954  SDValue V(0, 0);
4955  bool First = true;
4956  for (unsigned i = 0; i < 8; ++i) {
4957    bool isNonZero = (NonZeros & (1 << i)) != 0;
4958    if (isNonZero) {
4959      if (First) {
4960        if (NumZero)
4961          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4962        else
4963          V = DAG.getUNDEF(MVT::v8i16);
4964        First = false;
4965      }
4966      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4967                      MVT::v8i16, V, Op.getOperand(i),
4968                      DAG.getIntPtrConstant(i));
4969    }
4970  }
4971
4972  return V;
4973}
4974
4975/// getVShift - Return a vector logical shift node.
4976///
4977static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4978                         unsigned NumBits, SelectionDAG &DAG,
4979                         const TargetLowering &TLI, DebugLoc dl) {
4980  assert(VT.is128BitVector() && "Unknown type for VShift");
4981  EVT ShVT = MVT::v2i64;
4982  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4983  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4984  return DAG.getNode(ISD::BITCAST, dl, VT,
4985                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4986                             DAG.getConstant(NumBits,
4987                                  TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4988}
4989
4990SDValue
4991X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4992                                          SelectionDAG &DAG) const {
4993
4994  // Check if the scalar load can be widened into a vector load. And if
4995  // the address is "base + cst" see if the cst can be "absorbed" into
4996  // the shuffle mask.
4997  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4998    SDValue Ptr = LD->getBasePtr();
4999    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5000      return SDValue();
5001    EVT PVT = LD->getValueType(0);
5002    if (PVT != MVT::i32 && PVT != MVT::f32)
5003      return SDValue();
5004
5005    int FI = -1;
5006    int64_t Offset = 0;
5007    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5008      FI = FINode->getIndex();
5009      Offset = 0;
5010    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5011               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5012      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5013      Offset = Ptr.getConstantOperandVal(1);
5014      Ptr = Ptr.getOperand(0);
5015    } else {
5016      return SDValue();
5017    }
5018
5019    // FIXME: 256-bit vector instructions don't require a strict alignment,
5020    // improve this code to support it better.
5021    unsigned RequiredAlign = VT.getSizeInBits()/8;
5022    SDValue Chain = LD->getChain();
5023    // Make sure the stack object alignment is at least 16 or 32.
5024    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5025    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5026      if (MFI->isFixedObjectIndex(FI)) {
5027        // Can't change the alignment. FIXME: It's possible to compute
5028        // the exact stack offset and reference FI + adjust offset instead.
5029        // If someone *really* cares about this. That's the way to implement it.
5030        return SDValue();
5031      } else {
5032        MFI->setObjectAlignment(FI, RequiredAlign);
5033      }
5034    }
5035
5036    // (Offset % 16 or 32) must be multiple of 4. Then address is then
5037    // Ptr + (Offset & ~15).
5038    if (Offset < 0)
5039      return SDValue();
5040    if ((Offset % RequiredAlign) & 3)
5041      return SDValue();
5042    int64_t StartOffset = Offset & ~(RequiredAlign-1);
5043    if (StartOffset)
5044      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5045                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5046
5047    int EltNo = (Offset - StartOffset) >> 2;
5048    unsigned NumElems = VT.getVectorNumElements();
5049
5050    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5051    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5052                             LD->getPointerInfo().getWithOffset(StartOffset),
5053                             false, false, false, 0);
5054
5055    SmallVector<int, 8> Mask;
5056    for (unsigned i = 0; i != NumElems; ++i)
5057      Mask.push_back(EltNo);
5058
5059    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5060  }
5061
5062  return SDValue();
5063}
5064
5065/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5066/// vector of type 'VT', see if the elements can be replaced by a single large
5067/// load which has the same value as a build_vector whose operands are 'elts'.
5068///
5069/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5070///
5071/// FIXME: we'd also like to handle the case where the last elements are zero
5072/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5073/// There's even a handy isZeroNode for that purpose.
5074static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5075                                        DebugLoc &DL, SelectionDAG &DAG) {
5076  EVT EltVT = VT.getVectorElementType();
5077  unsigned NumElems = Elts.size();
5078
5079  LoadSDNode *LDBase = NULL;
5080  unsigned LastLoadedElt = -1U;
5081
5082  // For each element in the initializer, see if we've found a load or an undef.
5083  // If we don't find an initial load element, or later load elements are
5084  // non-consecutive, bail out.
5085  for (unsigned i = 0; i < NumElems; ++i) {
5086    SDValue Elt = Elts[i];
5087
5088    if (!Elt.getNode() ||
5089        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5090      return SDValue();
5091    if (!LDBase) {
5092      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5093        return SDValue();
5094      LDBase = cast<LoadSDNode>(Elt.getNode());
5095      LastLoadedElt = i;
5096      continue;
5097    }
5098    if (Elt.getOpcode() == ISD::UNDEF)
5099      continue;
5100
5101    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5102    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5103      return SDValue();
5104    LastLoadedElt = i;
5105  }
5106
5107  // If we have found an entire vector of loads and undefs, then return a large
5108  // load of the entire vector width starting at the base pointer.  If we found
5109  // consecutive loads for the low half, generate a vzext_load node.
5110  if (LastLoadedElt == NumElems - 1) {
5111    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5112      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5113                         LDBase->getPointerInfo(),
5114                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5115                         LDBase->isInvariant(), 0);
5116    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5117                       LDBase->getPointerInfo(),
5118                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5119                       LDBase->isInvariant(), LDBase->getAlignment());
5120  }
5121  if (NumElems == 4 && LastLoadedElt == 1 &&
5122      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5123    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5124    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5125    SDValue ResNode =
5126        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5127                                array_lengthof(Ops), MVT::i64,
5128                                LDBase->getPointerInfo(),
5129                                LDBase->getAlignment(),
5130                                false/*isVolatile*/, true/*ReadMem*/,
5131                                false/*WriteMem*/);
5132
5133    // Make sure the newly-created LOAD is in the same position as LDBase in
5134    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5135    // update uses of LDBase's output chain to use the TokenFactor.
5136    if (LDBase->hasAnyUseOfValue(1)) {
5137      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5138                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5139      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5140      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5141                             SDValue(ResNode.getNode(), 1));
5142    }
5143
5144    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5145  }
5146  return SDValue();
5147}
5148
5149/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5150/// to generate a splat value for the following cases:
5151/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5152/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5153/// a scalar load, or a constant.
5154/// The VBROADCAST node is returned when a pattern is found,
5155/// or SDValue() otherwise.
5156SDValue
5157X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5158  if (!Subtarget->hasFp256())
5159    return SDValue();
5160
5161  MVT VT = Op.getValueType().getSimpleVT();
5162  DebugLoc dl = Op.getDebugLoc();
5163
5164  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5165         "Unsupported vector type for broadcast.");
5166
5167  SDValue Ld;
5168  bool ConstSplatVal;
5169
5170  switch (Op.getOpcode()) {
5171    default:
5172      // Unknown pattern found.
5173      return SDValue();
5174
5175    case ISD::BUILD_VECTOR: {
5176      // The BUILD_VECTOR node must be a splat.
5177      if (!isSplatVector(Op.getNode()))
5178        return SDValue();
5179
5180      Ld = Op.getOperand(0);
5181      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5182                     Ld.getOpcode() == ISD::ConstantFP);
5183
5184      // The suspected load node has several users. Make sure that all
5185      // of its users are from the BUILD_VECTOR node.
5186      // Constants may have multiple users.
5187      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5188        return SDValue();
5189      break;
5190    }
5191
5192    case ISD::VECTOR_SHUFFLE: {
5193      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5194
5195      // Shuffles must have a splat mask where the first element is
5196      // broadcasted.
5197      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5198        return SDValue();
5199
5200      SDValue Sc = Op.getOperand(0);
5201      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5202          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5203
5204        if (!Subtarget->hasInt256())
5205          return SDValue();
5206
5207        // Use the register form of the broadcast instruction available on AVX2.
5208        if (VT.is256BitVector())
5209          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5210        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5211      }
5212
5213      Ld = Sc.getOperand(0);
5214      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5215                       Ld.getOpcode() == ISD::ConstantFP);
5216
5217      // The scalar_to_vector node and the suspected
5218      // load node must have exactly one user.
5219      // Constants may have multiple users.
5220      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5221        return SDValue();
5222      break;
5223    }
5224  }
5225
5226  bool Is256 = VT.is256BitVector();
5227
5228  // Handle the broadcasting a single constant scalar from the constant pool
5229  // into a vector. On Sandybridge it is still better to load a constant vector
5230  // from the constant pool and not to broadcast it from a scalar.
5231  if (ConstSplatVal && Subtarget->hasInt256()) {
5232    EVT CVT = Ld.getValueType();
5233    assert(!CVT.isVector() && "Must not broadcast a vector type");
5234    unsigned ScalarSize = CVT.getSizeInBits();
5235
5236    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5237      const Constant *C = 0;
5238      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5239        C = CI->getConstantIntValue();
5240      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5241        C = CF->getConstantFPValue();
5242
5243      assert(C && "Invalid constant type");
5244
5245      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5246      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5247      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5248                       MachinePointerInfo::getConstantPool(),
5249                       false, false, false, Alignment);
5250
5251      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5252    }
5253  }
5254
5255  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5256  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5257
5258  // Handle AVX2 in-register broadcasts.
5259  if (!IsLoad && Subtarget->hasInt256() &&
5260      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5261    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5262
5263  // The scalar source must be a normal load.
5264  if (!IsLoad)
5265    return SDValue();
5266
5267  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5268    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5269
5270  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5271  // double since there is no vbroadcastsd xmm
5272  if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5273    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5274      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5275  }
5276
5277  // Unsupported broadcast.
5278  return SDValue();
5279}
5280
5281SDValue
5282X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5283  EVT VT = Op.getValueType();
5284
5285  // Skip if insert_vec_elt is not supported.
5286  if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5287    return SDValue();
5288
5289  DebugLoc DL = Op.getDebugLoc();
5290  unsigned NumElems = Op.getNumOperands();
5291
5292  SDValue VecIn1;
5293  SDValue VecIn2;
5294  SmallVector<unsigned, 4> InsertIndices;
5295  SmallVector<int, 8> Mask(NumElems, -1);
5296
5297  for (unsigned i = 0; i != NumElems; ++i) {
5298    unsigned Opc = Op.getOperand(i).getOpcode();
5299
5300    if (Opc == ISD::UNDEF)
5301      continue;
5302
5303    if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5304      // Quit if more than 1 elements need inserting.
5305      if (InsertIndices.size() > 1)
5306        return SDValue();
5307
5308      InsertIndices.push_back(i);
5309      continue;
5310    }
5311
5312    SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5313    SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5314
5315    // Quit if extracted from vector of different type.
5316    if (ExtractedFromVec.getValueType() != VT)
5317      return SDValue();
5318
5319    // Quit if non-constant index.
5320    if (!isa<ConstantSDNode>(ExtIdx))
5321      return SDValue();
5322
5323    if (VecIn1.getNode() == 0)
5324      VecIn1 = ExtractedFromVec;
5325    else if (VecIn1 != ExtractedFromVec) {
5326      if (VecIn2.getNode() == 0)
5327        VecIn2 = ExtractedFromVec;
5328      else if (VecIn2 != ExtractedFromVec)
5329        // Quit if more than 2 vectors to shuffle
5330        return SDValue();
5331    }
5332
5333    unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5334
5335    if (ExtractedFromVec == VecIn1)
5336      Mask[i] = Idx;
5337    else if (ExtractedFromVec == VecIn2)
5338      Mask[i] = Idx + NumElems;
5339  }
5340
5341  if (VecIn1.getNode() == 0)
5342    return SDValue();
5343
5344  VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5345  SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5346  for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5347    unsigned Idx = InsertIndices[i];
5348    NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5349                     DAG.getIntPtrConstant(Idx));
5350  }
5351
5352  return NV;
5353}
5354
5355SDValue
5356X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5357  DebugLoc dl = Op.getDebugLoc();
5358
5359  MVT VT = Op.getValueType().getSimpleVT();
5360  MVT ExtVT = VT.getVectorElementType();
5361  unsigned NumElems = Op.getNumOperands();
5362
5363  // Vectors containing all zeros can be matched by pxor and xorps later
5364  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5365    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5366    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5367    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5368      return Op;
5369
5370    return getZeroVector(VT, Subtarget, DAG, dl);
5371  }
5372
5373  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5374  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5375  // vpcmpeqd on 256-bit vectors.
5376  if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5377    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5378      return Op;
5379
5380    return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5381  }
5382
5383  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5384  if (Broadcast.getNode())
5385    return Broadcast;
5386
5387  unsigned EVTBits = ExtVT.getSizeInBits();
5388
5389  unsigned NumZero  = 0;
5390  unsigned NumNonZero = 0;
5391  unsigned NonZeros = 0;
5392  bool IsAllConstants = true;
5393  SmallSet<SDValue, 8> Values;
5394  for (unsigned i = 0; i < NumElems; ++i) {
5395    SDValue Elt = Op.getOperand(i);
5396    if (Elt.getOpcode() == ISD::UNDEF)
5397      continue;
5398    Values.insert(Elt);
5399    if (Elt.getOpcode() != ISD::Constant &&
5400        Elt.getOpcode() != ISD::ConstantFP)
5401      IsAllConstants = false;
5402    if (X86::isZeroNode(Elt))
5403      NumZero++;
5404    else {
5405      NonZeros |= (1 << i);
5406      NumNonZero++;
5407    }
5408  }
5409
5410  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5411  if (NumNonZero == 0)
5412    return DAG.getUNDEF(VT);
5413
5414  // Special case for single non-zero, non-undef, element.
5415  if (NumNonZero == 1) {
5416    unsigned Idx = CountTrailingZeros_32(NonZeros);
5417    SDValue Item = Op.getOperand(Idx);
5418
5419    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5420    // the value are obviously zero, truncate the value to i32 and do the
5421    // insertion that way.  Only do this if the value is non-constant or if the
5422    // value is a constant being inserted into element 0.  It is cheaper to do
5423    // a constant pool load than it is to do a movd + shuffle.
5424    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5425        (!IsAllConstants || Idx == 0)) {
5426      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5427        // Handle SSE only.
5428        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5429        EVT VecVT = MVT::v4i32;
5430        unsigned VecElts = 4;
5431
5432        // Truncate the value (which may itself be a constant) to i32, and
5433        // convert it to a vector with movd (S2V+shuffle to zero extend).
5434        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5435        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5436        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5437
5438        // Now we have our 32-bit value zero extended in the low element of
5439        // a vector.  If Idx != 0, swizzle it into place.
5440        if (Idx != 0) {
5441          SmallVector<int, 4> Mask;
5442          Mask.push_back(Idx);
5443          for (unsigned i = 1; i != VecElts; ++i)
5444            Mask.push_back(i);
5445          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5446                                      &Mask[0]);
5447        }
5448        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5449      }
5450    }
5451
5452    // If we have a constant or non-constant insertion into the low element of
5453    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5454    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5455    // depending on what the source datatype is.
5456    if (Idx == 0) {
5457      if (NumZero == 0)
5458        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5459
5460      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5461          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5462        if (VT.is256BitVector()) {
5463          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5464          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5465                             Item, DAG.getIntPtrConstant(0));
5466        }
5467        assert(VT.is128BitVector() && "Expected an SSE value type!");
5468        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5469        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5470        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5471      }
5472
5473      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5474        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5475        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5476        if (VT.is256BitVector()) {
5477          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5478          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5479        } else {
5480          assert(VT.is128BitVector() && "Expected an SSE value type!");
5481          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5482        }
5483        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5484      }
5485    }
5486
5487    // Is it a vector logical left shift?
5488    if (NumElems == 2 && Idx == 1 &&
5489        X86::isZeroNode(Op.getOperand(0)) &&
5490        !X86::isZeroNode(Op.getOperand(1))) {
5491      unsigned NumBits = VT.getSizeInBits();
5492      return getVShift(true, VT,
5493                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5494                                   VT, Op.getOperand(1)),
5495                       NumBits/2, DAG, *this, dl);
5496    }
5497
5498    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5499      return SDValue();
5500
5501    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5502    // is a non-constant being inserted into an element other than the low one,
5503    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5504    // movd/movss) to move this into the low element, then shuffle it into
5505    // place.
5506    if (EVTBits == 32) {
5507      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5508
5509      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5510      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5511      SmallVector<int, 8> MaskVec;
5512      for (unsigned i = 0; i != NumElems; ++i)
5513        MaskVec.push_back(i == Idx ? 0 : 1);
5514      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5515    }
5516  }
5517
5518  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5519  if (Values.size() == 1) {
5520    if (EVTBits == 32) {
5521      // Instead of a shuffle like this:
5522      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5523      // Check if it's possible to issue this instead.
5524      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5525      unsigned Idx = CountTrailingZeros_32(NonZeros);
5526      SDValue Item = Op.getOperand(Idx);
5527      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5528        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5529    }
5530    return SDValue();
5531  }
5532
5533  // A vector full of immediates; various special cases are already
5534  // handled, so this is best done with a single constant-pool load.
5535  if (IsAllConstants)
5536    return SDValue();
5537
5538  // For AVX-length vectors, build the individual 128-bit pieces and use
5539  // shuffles to put them in place.
5540  if (VT.is256BitVector()) {
5541    SmallVector<SDValue, 32> V;
5542    for (unsigned i = 0; i != NumElems; ++i)
5543      V.push_back(Op.getOperand(i));
5544
5545    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5546
5547    // Build both the lower and upper subvector.
5548    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5549    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5550                                NumElems/2);
5551
5552    // Recreate the wider vector with the lower and upper part.
5553    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5554  }
5555
5556  // Let legalizer expand 2-wide build_vectors.
5557  if (EVTBits == 64) {
5558    if (NumNonZero == 1) {
5559      // One half is zero or undef.
5560      unsigned Idx = CountTrailingZeros_32(NonZeros);
5561      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5562                                 Op.getOperand(Idx));
5563      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5564    }
5565    return SDValue();
5566  }
5567
5568  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5569  if (EVTBits == 8 && NumElems == 16) {
5570    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5571                                        Subtarget, *this);
5572    if (V.getNode()) return V;
5573  }
5574
5575  if (EVTBits == 16 && NumElems == 8) {
5576    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5577                                      Subtarget, *this);
5578    if (V.getNode()) return V;
5579  }
5580
5581  // If element VT is == 32 bits, turn it into a number of shuffles.
5582  SmallVector<SDValue, 8> V(NumElems);
5583  if (NumElems == 4 && NumZero > 0) {
5584    for (unsigned i = 0; i < 4; ++i) {
5585      bool isZero = !(NonZeros & (1 << i));
5586      if (isZero)
5587        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5588      else
5589        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5590    }
5591
5592    for (unsigned i = 0; i < 2; ++i) {
5593      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5594        default: break;
5595        case 0:
5596          V[i] = V[i*2];  // Must be a zero vector.
5597          break;
5598        case 1:
5599          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5600          break;
5601        case 2:
5602          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5603          break;
5604        case 3:
5605          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5606          break;
5607      }
5608    }
5609
5610    bool Reverse1 = (NonZeros & 0x3) == 2;
5611    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5612    int MaskVec[] = {
5613      Reverse1 ? 1 : 0,
5614      Reverse1 ? 0 : 1,
5615      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5616      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5617    };
5618    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5619  }
5620
5621  if (Values.size() > 1 && VT.is128BitVector()) {
5622    // Check for a build vector of consecutive loads.
5623    for (unsigned i = 0; i < NumElems; ++i)
5624      V[i] = Op.getOperand(i);
5625
5626    // Check for elements which are consecutive loads.
5627    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5628    if (LD.getNode())
5629      return LD;
5630
5631    // Check for a build vector from mostly shuffle plus few inserting.
5632    SDValue Sh = buildFromShuffleMostly(Op, DAG);
5633    if (Sh.getNode())
5634      return Sh;
5635
5636    // For SSE 4.1, use insertps to put the high elements into the low element.
5637    if (getSubtarget()->hasSSE41()) {
5638      SDValue Result;
5639      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5640        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5641      else
5642        Result = DAG.getUNDEF(VT);
5643
5644      for (unsigned i = 1; i < NumElems; ++i) {
5645        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5646        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5647                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5648      }
5649      return Result;
5650    }
5651
5652    // Otherwise, expand into a number of unpckl*, start by extending each of
5653    // our (non-undef) elements to the full vector width with the element in the
5654    // bottom slot of the vector (which generates no code for SSE).
5655    for (unsigned i = 0; i < NumElems; ++i) {
5656      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5657        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5658      else
5659        V[i] = DAG.getUNDEF(VT);
5660    }
5661
5662    // Next, we iteratively mix elements, e.g. for v4f32:
5663    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5664    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5665    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5666    unsigned EltStride = NumElems >> 1;
5667    while (EltStride != 0) {
5668      for (unsigned i = 0; i < EltStride; ++i) {
5669        // If V[i+EltStride] is undef and this is the first round of mixing,
5670        // then it is safe to just drop this shuffle: V[i] is already in the
5671        // right place, the one element (since it's the first round) being
5672        // inserted as undef can be dropped.  This isn't safe for successive
5673        // rounds because they will permute elements within both vectors.
5674        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5675            EltStride == NumElems/2)
5676          continue;
5677
5678        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5679      }
5680      EltStride >>= 1;
5681    }
5682    return V[0];
5683  }
5684  return SDValue();
5685}
5686
5687// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5688// to create 256-bit vectors from two other 128-bit ones.
5689static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5690  DebugLoc dl = Op.getDebugLoc();
5691  MVT ResVT = Op.getValueType().getSimpleVT();
5692
5693  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5694
5695  SDValue V1 = Op.getOperand(0);
5696  SDValue V2 = Op.getOperand(1);
5697  unsigned NumElems = ResVT.getVectorNumElements();
5698
5699  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5700}
5701
5702static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5703  assert(Op.getNumOperands() == 2);
5704
5705  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5706  // from two other 128-bit ones.
5707  return LowerAVXCONCAT_VECTORS(Op, DAG);
5708}
5709
5710// Try to lower a shuffle node into a simple blend instruction.
5711static SDValue
5712LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5713                           const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5714  SDValue V1 = SVOp->getOperand(0);
5715  SDValue V2 = SVOp->getOperand(1);
5716  DebugLoc dl = SVOp->getDebugLoc();
5717  MVT VT = SVOp->getValueType(0).getSimpleVT();
5718  MVT EltVT = VT.getVectorElementType();
5719  unsigned NumElems = VT.getVectorNumElements();
5720
5721  if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5722    return SDValue();
5723  if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5724    return SDValue();
5725
5726  // Check the mask for BLEND and build the value.
5727  unsigned MaskValue = 0;
5728  // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5729  unsigned NumLanes = (NumElems-1)/8 + 1;
5730  unsigned NumElemsInLane = NumElems / NumLanes;
5731
5732  // Blend for v16i16 should be symetric for the both lanes.
5733  for (unsigned i = 0; i < NumElemsInLane; ++i) {
5734
5735    int SndLaneEltIdx = (NumLanes == 2) ?
5736      SVOp->getMaskElt(i + NumElemsInLane) : -1;
5737    int EltIdx = SVOp->getMaskElt(i);
5738
5739    if ((EltIdx < 0 || EltIdx == (int)i) &&
5740        (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5741      continue;
5742
5743    if (((unsigned)EltIdx == (i + NumElems)) &&
5744        (SndLaneEltIdx < 0 ||
5745         (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5746      MaskValue |= (1<<i);
5747    else
5748      return SDValue();
5749  }
5750
5751  // Convert i32 vectors to floating point if it is not AVX2.
5752  // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5753  MVT BlendVT = VT;
5754  if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5755    BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5756                               NumElems);
5757    V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5758    V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5759  }
5760
5761  SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5762                            DAG.getConstant(MaskValue, MVT::i32));
5763  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5764}
5765
5766// v8i16 shuffles - Prefer shuffles in the following order:
5767// 1. [all]   pshuflw, pshufhw, optional move
5768// 2. [ssse3] 1 x pshufb
5769// 3. [ssse3] 2 x pshufb + 1 x por
5770// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5771static SDValue
5772LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5773                         SelectionDAG &DAG) {
5774  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5775  SDValue V1 = SVOp->getOperand(0);
5776  SDValue V2 = SVOp->getOperand(1);
5777  DebugLoc dl = SVOp->getDebugLoc();
5778  SmallVector<int, 8> MaskVals;
5779
5780  // Determine if more than 1 of the words in each of the low and high quadwords
5781  // of the result come from the same quadword of one of the two inputs.  Undef
5782  // mask values count as coming from any quadword, for better codegen.
5783  unsigned LoQuad[] = { 0, 0, 0, 0 };
5784  unsigned HiQuad[] = { 0, 0, 0, 0 };
5785  std::bitset<4> InputQuads;
5786  for (unsigned i = 0; i < 8; ++i) {
5787    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5788    int EltIdx = SVOp->getMaskElt(i);
5789    MaskVals.push_back(EltIdx);
5790    if (EltIdx < 0) {
5791      ++Quad[0];
5792      ++Quad[1];
5793      ++Quad[2];
5794      ++Quad[3];
5795      continue;
5796    }
5797    ++Quad[EltIdx / 4];
5798    InputQuads.set(EltIdx / 4);
5799  }
5800
5801  int BestLoQuad = -1;
5802  unsigned MaxQuad = 1;
5803  for (unsigned i = 0; i < 4; ++i) {
5804    if (LoQuad[i] > MaxQuad) {
5805      BestLoQuad = i;
5806      MaxQuad = LoQuad[i];
5807    }
5808  }
5809
5810  int BestHiQuad = -1;
5811  MaxQuad = 1;
5812  for (unsigned i = 0; i < 4; ++i) {
5813    if (HiQuad[i] > MaxQuad) {
5814      BestHiQuad = i;
5815      MaxQuad = HiQuad[i];
5816    }
5817  }
5818
5819  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5820  // of the two input vectors, shuffle them into one input vector so only a
5821  // single pshufb instruction is necessary. If There are more than 2 input
5822  // quads, disable the next transformation since it does not help SSSE3.
5823  bool V1Used = InputQuads[0] || InputQuads[1];
5824  bool V2Used = InputQuads[2] || InputQuads[3];
5825  if (Subtarget->hasSSSE3()) {
5826    if (InputQuads.count() == 2 && V1Used && V2Used) {
5827      BestLoQuad = InputQuads[0] ? 0 : 1;
5828      BestHiQuad = InputQuads[2] ? 2 : 3;
5829    }
5830    if (InputQuads.count() > 2) {
5831      BestLoQuad = -1;
5832      BestHiQuad = -1;
5833    }
5834  }
5835
5836  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5837  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5838  // words from all 4 input quadwords.
5839  SDValue NewV;
5840  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5841    int MaskV[] = {
5842      BestLoQuad < 0 ? 0 : BestLoQuad,
5843      BestHiQuad < 0 ? 1 : BestHiQuad
5844    };
5845    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5846                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5847                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5848    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5849
5850    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5851    // source words for the shuffle, to aid later transformations.
5852    bool AllWordsInNewV = true;
5853    bool InOrder[2] = { true, true };
5854    for (unsigned i = 0; i != 8; ++i) {
5855      int idx = MaskVals[i];
5856      if (idx != (int)i)
5857        InOrder[i/4] = false;
5858      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5859        continue;
5860      AllWordsInNewV = false;
5861      break;
5862    }
5863
5864    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5865    if (AllWordsInNewV) {
5866      for (int i = 0; i != 8; ++i) {
5867        int idx = MaskVals[i];
5868        if (idx < 0)
5869          continue;
5870        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5871        if ((idx != i) && idx < 4)
5872          pshufhw = false;
5873        if ((idx != i) && idx > 3)
5874          pshuflw = false;
5875      }
5876      V1 = NewV;
5877      V2Used = false;
5878      BestLoQuad = 0;
5879      BestHiQuad = 1;
5880    }
5881
5882    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5883    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5884    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5885      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5886      unsigned TargetMask = 0;
5887      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5888                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5889      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5890      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5891                             getShufflePSHUFLWImmediate(SVOp);
5892      V1 = NewV.getOperand(0);
5893      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5894    }
5895  }
5896
5897  // Promote splats to a larger type which usually leads to more efficient code.
5898  // FIXME: Is this true if pshufb is available?
5899  if (SVOp->isSplat())
5900    return PromoteSplat(SVOp, DAG);
5901
5902  // If we have SSSE3, and all words of the result are from 1 input vector,
5903  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5904  // is present, fall back to case 4.
5905  if (Subtarget->hasSSSE3()) {
5906    SmallVector<SDValue,16> pshufbMask;
5907
5908    // If we have elements from both input vectors, set the high bit of the
5909    // shuffle mask element to zero out elements that come from V2 in the V1
5910    // mask, and elements that come from V1 in the V2 mask, so that the two
5911    // results can be OR'd together.
5912    bool TwoInputs = V1Used && V2Used;
5913    for (unsigned i = 0; i != 8; ++i) {
5914      int EltIdx = MaskVals[i] * 2;
5915      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5916      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5917      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5918      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5919    }
5920    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5921    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5922                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5923                                 MVT::v16i8, &pshufbMask[0], 16));
5924    if (!TwoInputs)
5925      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5926
5927    // Calculate the shuffle mask for the second input, shuffle it, and
5928    // OR it with the first shuffled input.
5929    pshufbMask.clear();
5930    for (unsigned i = 0; i != 8; ++i) {
5931      int EltIdx = MaskVals[i] * 2;
5932      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5933      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5934      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5935      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5936    }
5937    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5938    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5939                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5940                                 MVT::v16i8, &pshufbMask[0], 16));
5941    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5942    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5943  }
5944
5945  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5946  // and update MaskVals with new element order.
5947  std::bitset<8> InOrder;
5948  if (BestLoQuad >= 0) {
5949    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5950    for (int i = 0; i != 4; ++i) {
5951      int idx = MaskVals[i];
5952      if (idx < 0) {
5953        InOrder.set(i);
5954      } else if ((idx / 4) == BestLoQuad) {
5955        MaskV[i] = idx & 3;
5956        InOrder.set(i);
5957      }
5958    }
5959    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5960                                &MaskV[0]);
5961
5962    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5963      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5964      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5965                                  NewV.getOperand(0),
5966                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5967    }
5968  }
5969
5970  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5971  // and update MaskVals with the new element order.
5972  if (BestHiQuad >= 0) {
5973    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5974    for (unsigned i = 4; i != 8; ++i) {
5975      int idx = MaskVals[i];
5976      if (idx < 0) {
5977        InOrder.set(i);
5978      } else if ((idx / 4) == BestHiQuad) {
5979        MaskV[i] = (idx & 3) + 4;
5980        InOrder.set(i);
5981      }
5982    }
5983    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5984                                &MaskV[0]);
5985
5986    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5987      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5988      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5989                                  NewV.getOperand(0),
5990                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5991    }
5992  }
5993
5994  // In case BestHi & BestLo were both -1, which means each quadword has a word
5995  // from each of the four input quadwords, calculate the InOrder bitvector now
5996  // before falling through to the insert/extract cleanup.
5997  if (BestLoQuad == -1 && BestHiQuad == -1) {
5998    NewV = V1;
5999    for (int i = 0; i != 8; ++i)
6000      if (MaskVals[i] < 0 || MaskVals[i] == i)
6001        InOrder.set(i);
6002  }
6003
6004  // The other elements are put in the right place using pextrw and pinsrw.
6005  for (unsigned i = 0; i != 8; ++i) {
6006    if (InOrder[i])
6007      continue;
6008    int EltIdx = MaskVals[i];
6009    if (EltIdx < 0)
6010      continue;
6011    SDValue ExtOp = (EltIdx < 8) ?
6012      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6013                  DAG.getIntPtrConstant(EltIdx)) :
6014      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6015                  DAG.getIntPtrConstant(EltIdx - 8));
6016    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6017                       DAG.getIntPtrConstant(i));
6018  }
6019  return NewV;
6020}
6021
6022// v16i8 shuffles - Prefer shuffles in the following order:
6023// 1. [ssse3] 1 x pshufb
6024// 2. [ssse3] 2 x pshufb + 1 x por
6025// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6026static
6027SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6028                                 SelectionDAG &DAG,
6029                                 const X86TargetLowering &TLI) {
6030  SDValue V1 = SVOp->getOperand(0);
6031  SDValue V2 = SVOp->getOperand(1);
6032  DebugLoc dl = SVOp->getDebugLoc();
6033  ArrayRef<int> MaskVals = SVOp->getMask();
6034
6035  // Promote splats to a larger type which usually leads to more efficient code.
6036  // FIXME: Is this true if pshufb is available?
6037  if (SVOp->isSplat())
6038    return PromoteSplat(SVOp, DAG);
6039
6040  // If we have SSSE3, case 1 is generated when all result bytes come from
6041  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6042  // present, fall back to case 3.
6043
6044  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6045  if (TLI.getSubtarget()->hasSSSE3()) {
6046    SmallVector<SDValue,16> pshufbMask;
6047
6048    // If all result elements are from one input vector, then only translate
6049    // undef mask values to 0x80 (zero out result) in the pshufb mask.
6050    //
6051    // Otherwise, we have elements from both input vectors, and must zero out
6052    // elements that come from V2 in the first mask, and V1 in the second mask
6053    // so that we can OR them together.
6054    for (unsigned i = 0; i != 16; ++i) {
6055      int EltIdx = MaskVals[i];
6056      if (EltIdx < 0 || EltIdx >= 16)
6057        EltIdx = 0x80;
6058      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6059    }
6060    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6061                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6062                                 MVT::v16i8, &pshufbMask[0], 16));
6063
6064    // As PSHUFB will zero elements with negative indices, it's safe to ignore
6065    // the 2nd operand if it's undefined or zero.
6066    if (V2.getOpcode() == ISD::UNDEF ||
6067        ISD::isBuildVectorAllZeros(V2.getNode()))
6068      return V1;
6069
6070    // Calculate the shuffle mask for the second input, shuffle it, and
6071    // OR it with the first shuffled input.
6072    pshufbMask.clear();
6073    for (unsigned i = 0; i != 16; ++i) {
6074      int EltIdx = MaskVals[i];
6075      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6076      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6077    }
6078    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6079                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6080                                 MVT::v16i8, &pshufbMask[0], 16));
6081    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6082  }
6083
6084  // No SSSE3 - Calculate in place words and then fix all out of place words
6085  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6086  // the 16 different words that comprise the two doublequadword input vectors.
6087  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6088  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6089  SDValue NewV = V1;
6090  for (int i = 0; i != 8; ++i) {
6091    int Elt0 = MaskVals[i*2];
6092    int Elt1 = MaskVals[i*2+1];
6093
6094    // This word of the result is all undef, skip it.
6095    if (Elt0 < 0 && Elt1 < 0)
6096      continue;
6097
6098    // This word of the result is already in the correct place, skip it.
6099    if ((Elt0 == i*2) && (Elt1 == i*2+1))
6100      continue;
6101
6102    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6103    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6104    SDValue InsElt;
6105
6106    // If Elt0 and Elt1 are defined, are consecutive, and can be load
6107    // using a single extract together, load it and store it.
6108    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6109      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6110                           DAG.getIntPtrConstant(Elt1 / 2));
6111      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6112                        DAG.getIntPtrConstant(i));
6113      continue;
6114    }
6115
6116    // If Elt1 is defined, extract it from the appropriate source.  If the
6117    // source byte is not also odd, shift the extracted word left 8 bits
6118    // otherwise clear the bottom 8 bits if we need to do an or.
6119    if (Elt1 >= 0) {
6120      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6121                           DAG.getIntPtrConstant(Elt1 / 2));
6122      if ((Elt1 & 1) == 0)
6123        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6124                             DAG.getConstant(8,
6125                                  TLI.getShiftAmountTy(InsElt.getValueType())));
6126      else if (Elt0 >= 0)
6127        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6128                             DAG.getConstant(0xFF00, MVT::i16));
6129    }
6130    // If Elt0 is defined, extract it from the appropriate source.  If the
6131    // source byte is not also even, shift the extracted word right 8 bits. If
6132    // Elt1 was also defined, OR the extracted values together before
6133    // inserting them in the result.
6134    if (Elt0 >= 0) {
6135      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6136                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6137      if ((Elt0 & 1) != 0)
6138        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6139                              DAG.getConstant(8,
6140                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6141      else if (Elt1 >= 0)
6142        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6143                             DAG.getConstant(0x00FF, MVT::i16));
6144      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6145                         : InsElt0;
6146    }
6147    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6148                       DAG.getIntPtrConstant(i));
6149  }
6150  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6151}
6152
6153// v32i8 shuffles - Translate to VPSHUFB if possible.
6154static
6155SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6156                                 const X86Subtarget *Subtarget,
6157                                 SelectionDAG &DAG) {
6158  MVT VT = SVOp->getValueType(0).getSimpleVT();
6159  SDValue V1 = SVOp->getOperand(0);
6160  SDValue V2 = SVOp->getOperand(1);
6161  DebugLoc dl = SVOp->getDebugLoc();
6162  SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6163
6164  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6165  bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6166  bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6167
6168  // VPSHUFB may be generated if
6169  // (1) one of input vector is undefined or zeroinitializer.
6170  // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6171  // And (2) the mask indexes don't cross the 128-bit lane.
6172  if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6173      (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6174    return SDValue();
6175
6176  if (V1IsAllZero && !V2IsAllZero) {
6177    CommuteVectorShuffleMask(MaskVals, 32);
6178    V1 = V2;
6179  }
6180  SmallVector<SDValue, 32> pshufbMask;
6181  for (unsigned i = 0; i != 32; i++) {
6182    int EltIdx = MaskVals[i];
6183    if (EltIdx < 0 || EltIdx >= 32)
6184      EltIdx = 0x80;
6185    else {
6186      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6187        // Cross lane is not allowed.
6188        return SDValue();
6189      EltIdx &= 0xf;
6190    }
6191    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6192  }
6193  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6194                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6195                                  MVT::v32i8, &pshufbMask[0], 32));
6196}
6197
6198/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6199/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6200/// done when every pair / quad of shuffle mask elements point to elements in
6201/// the right sequence. e.g.
6202/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6203static
6204SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6205                                 SelectionDAG &DAG) {
6206  MVT VT = SVOp->getValueType(0).getSimpleVT();
6207  DebugLoc dl = SVOp->getDebugLoc();
6208  unsigned NumElems = VT.getVectorNumElements();
6209  MVT NewVT;
6210  unsigned Scale;
6211  switch (VT.SimpleTy) {
6212  default: llvm_unreachable("Unexpected!");
6213  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6214  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6215  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6216  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6217  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6218  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6219  }
6220
6221  SmallVector<int, 8> MaskVec;
6222  for (unsigned i = 0; i != NumElems; i += Scale) {
6223    int StartIdx = -1;
6224    for (unsigned j = 0; j != Scale; ++j) {
6225      int EltIdx = SVOp->getMaskElt(i+j);
6226      if (EltIdx < 0)
6227        continue;
6228      if (StartIdx < 0)
6229        StartIdx = (EltIdx / Scale);
6230      if (EltIdx != (int)(StartIdx*Scale + j))
6231        return SDValue();
6232    }
6233    MaskVec.push_back(StartIdx);
6234  }
6235
6236  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6237  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6238  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6239}
6240
6241/// getVZextMovL - Return a zero-extending vector move low node.
6242///
6243static SDValue getVZextMovL(MVT VT, EVT OpVT,
6244                            SDValue SrcOp, SelectionDAG &DAG,
6245                            const X86Subtarget *Subtarget, DebugLoc dl) {
6246  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6247    LoadSDNode *LD = NULL;
6248    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6249      LD = dyn_cast<LoadSDNode>(SrcOp);
6250    if (!LD) {
6251      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6252      // instead.
6253      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6254      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6255          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6256          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6257          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6258        // PR2108
6259        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6260        return DAG.getNode(ISD::BITCAST, dl, VT,
6261                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6262                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6263                                                   OpVT,
6264                                                   SrcOp.getOperand(0)
6265                                                          .getOperand(0))));
6266      }
6267    }
6268  }
6269
6270  return DAG.getNode(ISD::BITCAST, dl, VT,
6271                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6272                                 DAG.getNode(ISD::BITCAST, dl,
6273                                             OpVT, SrcOp)));
6274}
6275
6276/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6277/// which could not be matched by any known target speficic shuffle
6278static SDValue
6279LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6280
6281  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6282  if (NewOp.getNode())
6283    return NewOp;
6284
6285  MVT VT = SVOp->getValueType(0).getSimpleVT();
6286
6287  unsigned NumElems = VT.getVectorNumElements();
6288  unsigned NumLaneElems = NumElems / 2;
6289
6290  DebugLoc dl = SVOp->getDebugLoc();
6291  MVT EltVT = VT.getVectorElementType();
6292  MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6293  SDValue Output[2];
6294
6295  SmallVector<int, 16> Mask;
6296  for (unsigned l = 0; l < 2; ++l) {
6297    // Build a shuffle mask for the output, discovering on the fly which
6298    // input vectors to use as shuffle operands (recorded in InputUsed).
6299    // If building a suitable shuffle vector proves too hard, then bail
6300    // out with UseBuildVector set.
6301    bool UseBuildVector = false;
6302    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6303    unsigned LaneStart = l * NumLaneElems;
6304    for (unsigned i = 0; i != NumLaneElems; ++i) {
6305      // The mask element.  This indexes into the input.
6306      int Idx = SVOp->getMaskElt(i+LaneStart);
6307      if (Idx < 0) {
6308        // the mask element does not index into any input vector.
6309        Mask.push_back(-1);
6310        continue;
6311      }
6312
6313      // The input vector this mask element indexes into.
6314      int Input = Idx / NumLaneElems;
6315
6316      // Turn the index into an offset from the start of the input vector.
6317      Idx -= Input * NumLaneElems;
6318
6319      // Find or create a shuffle vector operand to hold this input.
6320      unsigned OpNo;
6321      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6322        if (InputUsed[OpNo] == Input)
6323          // This input vector is already an operand.
6324          break;
6325        if (InputUsed[OpNo] < 0) {
6326          // Create a new operand for this input vector.
6327          InputUsed[OpNo] = Input;
6328          break;
6329        }
6330      }
6331
6332      if (OpNo >= array_lengthof(InputUsed)) {
6333        // More than two input vectors used!  Give up on trying to create a
6334        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6335        UseBuildVector = true;
6336        break;
6337      }
6338
6339      // Add the mask index for the new shuffle vector.
6340      Mask.push_back(Idx + OpNo * NumLaneElems);
6341    }
6342
6343    if (UseBuildVector) {
6344      SmallVector<SDValue, 16> SVOps;
6345      for (unsigned i = 0; i != NumLaneElems; ++i) {
6346        // The mask element.  This indexes into the input.
6347        int Idx = SVOp->getMaskElt(i+LaneStart);
6348        if (Idx < 0) {
6349          SVOps.push_back(DAG.getUNDEF(EltVT));
6350          continue;
6351        }
6352
6353        // The input vector this mask element indexes into.
6354        int Input = Idx / NumElems;
6355
6356        // Turn the index into an offset from the start of the input vector.
6357        Idx -= Input * NumElems;
6358
6359        // Extract the vector element by hand.
6360        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6361                                    SVOp->getOperand(Input),
6362                                    DAG.getIntPtrConstant(Idx)));
6363      }
6364
6365      // Construct the output using a BUILD_VECTOR.
6366      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6367                              SVOps.size());
6368    } else if (InputUsed[0] < 0) {
6369      // No input vectors were used! The result is undefined.
6370      Output[l] = DAG.getUNDEF(NVT);
6371    } else {
6372      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6373                                        (InputUsed[0] % 2) * NumLaneElems,
6374                                        DAG, dl);
6375      // If only one input was used, use an undefined vector for the other.
6376      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6377        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6378                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6379      // At least one input vector was used. Create a new shuffle vector.
6380      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6381    }
6382
6383    Mask.clear();
6384  }
6385
6386  // Concatenate the result back
6387  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6388}
6389
6390/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6391/// 4 elements, and match them with several different shuffle types.
6392static SDValue
6393LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6394  SDValue V1 = SVOp->getOperand(0);
6395  SDValue V2 = SVOp->getOperand(1);
6396  DebugLoc dl = SVOp->getDebugLoc();
6397  MVT VT = SVOp->getValueType(0).getSimpleVT();
6398
6399  assert(VT.is128BitVector() && "Unsupported vector size");
6400
6401  std::pair<int, int> Locs[4];
6402  int Mask1[] = { -1, -1, -1, -1 };
6403  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6404
6405  unsigned NumHi = 0;
6406  unsigned NumLo = 0;
6407  for (unsigned i = 0; i != 4; ++i) {
6408    int Idx = PermMask[i];
6409    if (Idx < 0) {
6410      Locs[i] = std::make_pair(-1, -1);
6411    } else {
6412      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6413      if (Idx < 4) {
6414        Locs[i] = std::make_pair(0, NumLo);
6415        Mask1[NumLo] = Idx;
6416        NumLo++;
6417      } else {
6418        Locs[i] = std::make_pair(1, NumHi);
6419        if (2+NumHi < 4)
6420          Mask1[2+NumHi] = Idx;
6421        NumHi++;
6422      }
6423    }
6424  }
6425
6426  if (NumLo <= 2 && NumHi <= 2) {
6427    // If no more than two elements come from either vector. This can be
6428    // implemented with two shuffles. First shuffle gather the elements.
6429    // The second shuffle, which takes the first shuffle as both of its
6430    // vector operands, put the elements into the right order.
6431    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6432
6433    int Mask2[] = { -1, -1, -1, -1 };
6434
6435    for (unsigned i = 0; i != 4; ++i)
6436      if (Locs[i].first != -1) {
6437        unsigned Idx = (i < 2) ? 0 : 4;
6438        Idx += Locs[i].first * 2 + Locs[i].second;
6439        Mask2[i] = Idx;
6440      }
6441
6442    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6443  }
6444
6445  if (NumLo == 3 || NumHi == 3) {
6446    // Otherwise, we must have three elements from one vector, call it X, and
6447    // one element from the other, call it Y.  First, use a shufps to build an
6448    // intermediate vector with the one element from Y and the element from X
6449    // that will be in the same half in the final destination (the indexes don't
6450    // matter). Then, use a shufps to build the final vector, taking the half
6451    // containing the element from Y from the intermediate, and the other half
6452    // from X.
6453    if (NumHi == 3) {
6454      // Normalize it so the 3 elements come from V1.
6455      CommuteVectorShuffleMask(PermMask, 4);
6456      std::swap(V1, V2);
6457    }
6458
6459    // Find the element from V2.
6460    unsigned HiIndex;
6461    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6462      int Val = PermMask[HiIndex];
6463      if (Val < 0)
6464        continue;
6465      if (Val >= 4)
6466        break;
6467    }
6468
6469    Mask1[0] = PermMask[HiIndex];
6470    Mask1[1] = -1;
6471    Mask1[2] = PermMask[HiIndex^1];
6472    Mask1[3] = -1;
6473    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6474
6475    if (HiIndex >= 2) {
6476      Mask1[0] = PermMask[0];
6477      Mask1[1] = PermMask[1];
6478      Mask1[2] = HiIndex & 1 ? 6 : 4;
6479      Mask1[3] = HiIndex & 1 ? 4 : 6;
6480      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6481    }
6482
6483    Mask1[0] = HiIndex & 1 ? 2 : 0;
6484    Mask1[1] = HiIndex & 1 ? 0 : 2;
6485    Mask1[2] = PermMask[2];
6486    Mask1[3] = PermMask[3];
6487    if (Mask1[2] >= 0)
6488      Mask1[2] += 4;
6489    if (Mask1[3] >= 0)
6490      Mask1[3] += 4;
6491    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6492  }
6493
6494  // Break it into (shuffle shuffle_hi, shuffle_lo).
6495  int LoMask[] = { -1, -1, -1, -1 };
6496  int HiMask[] = { -1, -1, -1, -1 };
6497
6498  int *MaskPtr = LoMask;
6499  unsigned MaskIdx = 0;
6500  unsigned LoIdx = 0;
6501  unsigned HiIdx = 2;
6502  for (unsigned i = 0; i != 4; ++i) {
6503    if (i == 2) {
6504      MaskPtr = HiMask;
6505      MaskIdx = 1;
6506      LoIdx = 0;
6507      HiIdx = 2;
6508    }
6509    int Idx = PermMask[i];
6510    if (Idx < 0) {
6511      Locs[i] = std::make_pair(-1, -1);
6512    } else if (Idx < 4) {
6513      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6514      MaskPtr[LoIdx] = Idx;
6515      LoIdx++;
6516    } else {
6517      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6518      MaskPtr[HiIdx] = Idx;
6519      HiIdx++;
6520    }
6521  }
6522
6523  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6524  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6525  int MaskOps[] = { -1, -1, -1, -1 };
6526  for (unsigned i = 0; i != 4; ++i)
6527    if (Locs[i].first != -1)
6528      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6529  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6530}
6531
6532static bool MayFoldVectorLoad(SDValue V) {
6533  while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6534    V = V.getOperand(0);
6535
6536  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6537    V = V.getOperand(0);
6538  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6539      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6540    // BUILD_VECTOR (load), undef
6541    V = V.getOperand(0);
6542
6543  return MayFoldLoad(V);
6544}
6545
6546static
6547SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6548  EVT VT = Op.getValueType();
6549
6550  // Canonizalize to v2f64.
6551  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6552  return DAG.getNode(ISD::BITCAST, dl, VT,
6553                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6554                                          V1, DAG));
6555}
6556
6557static
6558SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6559                        bool HasSSE2) {
6560  SDValue V1 = Op.getOperand(0);
6561  SDValue V2 = Op.getOperand(1);
6562  EVT VT = Op.getValueType();
6563
6564  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6565
6566  if (HasSSE2 && VT == MVT::v2f64)
6567    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6568
6569  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6570  return DAG.getNode(ISD::BITCAST, dl, VT,
6571                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6572                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6573                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6574}
6575
6576static
6577SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6578  SDValue V1 = Op.getOperand(0);
6579  SDValue V2 = Op.getOperand(1);
6580  EVT VT = Op.getValueType();
6581
6582  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6583         "unsupported shuffle type");
6584
6585  if (V2.getOpcode() == ISD::UNDEF)
6586    V2 = V1;
6587
6588  // v4i32 or v4f32
6589  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6590}
6591
6592static
6593SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6594  SDValue V1 = Op.getOperand(0);
6595  SDValue V2 = Op.getOperand(1);
6596  EVT VT = Op.getValueType();
6597  unsigned NumElems = VT.getVectorNumElements();
6598
6599  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6600  // operand of these instructions is only memory, so check if there's a
6601  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6602  // same masks.
6603  bool CanFoldLoad = false;
6604
6605  // Trivial case, when V2 comes from a load.
6606  if (MayFoldVectorLoad(V2))
6607    CanFoldLoad = true;
6608
6609  // When V1 is a load, it can be folded later into a store in isel, example:
6610  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6611  //    turns into:
6612  //  (MOVLPSmr addr:$src1, VR128:$src2)
6613  // So, recognize this potential and also use MOVLPS or MOVLPD
6614  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6615    CanFoldLoad = true;
6616
6617  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6618  if (CanFoldLoad) {
6619    if (HasSSE2 && NumElems == 2)
6620      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6621
6622    if (NumElems == 4)
6623      // If we don't care about the second element, proceed to use movss.
6624      if (SVOp->getMaskElt(1) != -1)
6625        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6626  }
6627
6628  // movl and movlp will both match v2i64, but v2i64 is never matched by
6629  // movl earlier because we make it strict to avoid messing with the movlp load
6630  // folding logic (see the code above getMOVLP call). Match it here then,
6631  // this is horrible, but will stay like this until we move all shuffle
6632  // matching to x86 specific nodes. Note that for the 1st condition all
6633  // types are matched with movsd.
6634  if (HasSSE2) {
6635    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6636    // as to remove this logic from here, as much as possible
6637    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6638      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6639    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6640  }
6641
6642  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6643
6644  // Invert the operand order and use SHUFPS to match it.
6645  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6646                              getShuffleSHUFImmediate(SVOp), DAG);
6647}
6648
6649// Reduce a vector shuffle to zext.
6650SDValue
6651X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6652  // PMOVZX is only available from SSE41.
6653  if (!Subtarget->hasSSE41())
6654    return SDValue();
6655
6656  EVT VT = Op.getValueType();
6657
6658  // Only AVX2 support 256-bit vector integer extending.
6659  if (!Subtarget->hasInt256() && VT.is256BitVector())
6660    return SDValue();
6661
6662  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6663  DebugLoc DL = Op.getDebugLoc();
6664  SDValue V1 = Op.getOperand(0);
6665  SDValue V2 = Op.getOperand(1);
6666  unsigned NumElems = VT.getVectorNumElements();
6667
6668  // Extending is an unary operation and the element type of the source vector
6669  // won't be equal to or larger than i64.
6670  if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6671      VT.getVectorElementType() == MVT::i64)
6672    return SDValue();
6673
6674  // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6675  unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6676  while ((1U << Shift) < NumElems) {
6677    if (SVOp->getMaskElt(1U << Shift) == 1)
6678      break;
6679    Shift += 1;
6680    // The maximal ratio is 8, i.e. from i8 to i64.
6681    if (Shift > 3)
6682      return SDValue();
6683  }
6684
6685  // Check the shuffle mask.
6686  unsigned Mask = (1U << Shift) - 1;
6687  for (unsigned i = 0; i != NumElems; ++i) {
6688    int EltIdx = SVOp->getMaskElt(i);
6689    if ((i & Mask) != 0 && EltIdx != -1)
6690      return SDValue();
6691    if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6692      return SDValue();
6693  }
6694
6695  LLVMContext *Context = DAG.getContext();
6696  unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6697  EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6698  EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6699
6700  if (!isTypeLegal(NVT))
6701    return SDValue();
6702
6703  // Simplify the operand as it's prepared to be fed into shuffle.
6704  unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6705  if (V1.getOpcode() == ISD::BITCAST &&
6706      V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6707      V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6708      V1.getOperand(0)
6709        .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6710    // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6711    SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6712    ConstantSDNode *CIdx =
6713      dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6714    // If it's foldable, i.e. normal load with single use, we will let code
6715    // selection to fold it. Otherwise, we will short the conversion sequence.
6716    if (CIdx && CIdx->getZExtValue() == 0 &&
6717        (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6718      if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6719        // The "ext_vec_elt" node is wider than the result node.
6720        // In this case we should extract subvector from V.
6721        // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6722        unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6723        EVT FullVT = V.getValueType();
6724        EVT SubVecVT = EVT::getVectorVT(*Context,
6725                                        FullVT.getVectorElementType(),
6726                                        FullVT.getVectorNumElements()/Ratio);
6727        V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6728                        DAG.getIntPtrConstant(0));
6729      }
6730      V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6731    }
6732  }
6733
6734  return DAG.getNode(ISD::BITCAST, DL, VT,
6735                     DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6736}
6737
6738SDValue
6739X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6740  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6741  MVT VT = Op.getValueType().getSimpleVT();
6742  DebugLoc dl = Op.getDebugLoc();
6743  SDValue V1 = Op.getOperand(0);
6744  SDValue V2 = Op.getOperand(1);
6745
6746  if (isZeroShuffle(SVOp))
6747    return getZeroVector(VT, Subtarget, DAG, dl);
6748
6749  // Handle splat operations
6750  if (SVOp->isSplat()) {
6751    // Use vbroadcast whenever the splat comes from a foldable load
6752    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6753    if (Broadcast.getNode())
6754      return Broadcast;
6755  }
6756
6757  // Check integer expanding shuffles.
6758  SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6759  if (NewOp.getNode())
6760    return NewOp;
6761
6762  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6763  // do it!
6764  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6765      VT == MVT::v16i16 || VT == MVT::v32i8) {
6766    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6767    if (NewOp.getNode())
6768      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6769  } else if ((VT == MVT::v4i32 ||
6770             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6771    // FIXME: Figure out a cleaner way to do this.
6772    // Try to make use of movq to zero out the top part.
6773    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6774      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6775      if (NewOp.getNode()) {
6776        MVT NewVT = NewOp.getValueType().getSimpleVT();
6777        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6778                               NewVT, true, false))
6779          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6780                              DAG, Subtarget, dl);
6781      }
6782    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6783      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6784      if (NewOp.getNode()) {
6785        MVT NewVT = NewOp.getValueType().getSimpleVT();
6786        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6787          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6788                              DAG, Subtarget, dl);
6789      }
6790    }
6791  }
6792  return SDValue();
6793}
6794
6795SDValue
6796X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6797  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6798  SDValue V1 = Op.getOperand(0);
6799  SDValue V2 = Op.getOperand(1);
6800  MVT VT = Op.getValueType().getSimpleVT();
6801  DebugLoc dl = Op.getDebugLoc();
6802  unsigned NumElems = VT.getVectorNumElements();
6803  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6804  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6805  bool V1IsSplat = false;
6806  bool V2IsSplat = false;
6807  bool HasSSE2 = Subtarget->hasSSE2();
6808  bool HasFp256    = Subtarget->hasFp256();
6809  bool HasInt256   = Subtarget->hasInt256();
6810  MachineFunction &MF = DAG.getMachineFunction();
6811  bool OptForSize = MF.getFunction()->getAttributes().
6812    hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6813
6814  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6815
6816  if (V1IsUndef && V2IsUndef)
6817    return DAG.getUNDEF(VT);
6818
6819  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6820
6821  // Vector shuffle lowering takes 3 steps:
6822  //
6823  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6824  //    narrowing and commutation of operands should be handled.
6825  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6826  //    shuffle nodes.
6827  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6828  //    so the shuffle can be broken into other shuffles and the legalizer can
6829  //    try the lowering again.
6830  //
6831  // The general idea is that no vector_shuffle operation should be left to
6832  // be matched during isel, all of them must be converted to a target specific
6833  // node here.
6834
6835  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6836  // narrowing and commutation of operands should be handled. The actual code
6837  // doesn't include all of those, work in progress...
6838  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6839  if (NewOp.getNode())
6840    return NewOp;
6841
6842  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6843
6844  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6845  // unpckh_undef). Only use pshufd if speed is more important than size.
6846  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6847    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6848  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6849    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6850
6851  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6852      V2IsUndef && MayFoldVectorLoad(V1))
6853    return getMOVDDup(Op, dl, V1, DAG);
6854
6855  if (isMOVHLPS_v_undef_Mask(M, VT))
6856    return getMOVHighToLow(Op, dl, DAG);
6857
6858  // Use to match splats
6859  if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6860      (VT == MVT::v2f64 || VT == MVT::v2i64))
6861    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6862
6863  if (isPSHUFDMask(M, VT)) {
6864    // The actual implementation will match the mask in the if above and then
6865    // during isel it can match several different instructions, not only pshufd
6866    // as its name says, sad but true, emulate the behavior for now...
6867    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6868      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6869
6870    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6871
6872    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6873      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6874
6875    if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6876      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6877                                  DAG);
6878
6879    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6880                                TargetMask, DAG);
6881  }
6882
6883  // Check if this can be converted into a logical shift.
6884  bool isLeft = false;
6885  unsigned ShAmt = 0;
6886  SDValue ShVal;
6887  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6888  if (isShift && ShVal.hasOneUse()) {
6889    // If the shifted value has multiple uses, it may be cheaper to use
6890    // v_set0 + movlhps or movhlps, etc.
6891    MVT EltVT = VT.getVectorElementType();
6892    ShAmt *= EltVT.getSizeInBits();
6893    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6894  }
6895
6896  if (isMOVLMask(M, VT)) {
6897    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6898      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6899    if (!isMOVLPMask(M, VT)) {
6900      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6901        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6902
6903      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6904        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6905    }
6906  }
6907
6908  // FIXME: fold these into legal mask.
6909  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6910    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6911
6912  if (isMOVHLPSMask(M, VT))
6913    return getMOVHighToLow(Op, dl, DAG);
6914
6915  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6916    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6917
6918  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6919    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6920
6921  if (isMOVLPMask(M, VT))
6922    return getMOVLP(Op, dl, DAG, HasSSE2);
6923
6924  if (ShouldXformToMOVHLPS(M, VT) ||
6925      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6926    return CommuteVectorShuffle(SVOp, DAG);
6927
6928  if (isShift) {
6929    // No better options. Use a vshldq / vsrldq.
6930    MVT EltVT = VT.getVectorElementType();
6931    ShAmt *= EltVT.getSizeInBits();
6932    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6933  }
6934
6935  bool Commuted = false;
6936  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6937  // 1,1,1,1 -> v8i16 though.
6938  V1IsSplat = isSplatVector(V1.getNode());
6939  V2IsSplat = isSplatVector(V2.getNode());
6940
6941  // Canonicalize the splat or undef, if present, to be on the RHS.
6942  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6943    CommuteVectorShuffleMask(M, NumElems);
6944    std::swap(V1, V2);
6945    std::swap(V1IsSplat, V2IsSplat);
6946    Commuted = true;
6947  }
6948
6949  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6950    // Shuffling low element of v1 into undef, just return v1.
6951    if (V2IsUndef)
6952      return V1;
6953    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6954    // the instruction selector will not match, so get a canonical MOVL with
6955    // swapped operands to undo the commute.
6956    return getMOVL(DAG, dl, VT, V2, V1);
6957  }
6958
6959  if (isUNPCKLMask(M, VT, HasInt256))
6960    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6961
6962  if (isUNPCKHMask(M, VT, HasInt256))
6963    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6964
6965  if (V2IsSplat) {
6966    // Normalize mask so all entries that point to V2 points to its first
6967    // element then try to match unpck{h|l} again. If match, return a
6968    // new vector_shuffle with the corrected mask.p
6969    SmallVector<int, 8> NewMask(M.begin(), M.end());
6970    NormalizeMask(NewMask, NumElems);
6971    if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6972      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6973    if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6974      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6975  }
6976
6977  if (Commuted) {
6978    // Commute is back and try unpck* again.
6979    // FIXME: this seems wrong.
6980    CommuteVectorShuffleMask(M, NumElems);
6981    std::swap(V1, V2);
6982    std::swap(V1IsSplat, V2IsSplat);
6983    Commuted = false;
6984
6985    if (isUNPCKLMask(M, VT, HasInt256))
6986      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6987
6988    if (isUNPCKHMask(M, VT, HasInt256))
6989      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6990  }
6991
6992  // Normalize the node to match x86 shuffle ops if needed
6993  if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6994    return CommuteVectorShuffle(SVOp, DAG);
6995
6996  // The checks below are all present in isShuffleMaskLegal, but they are
6997  // inlined here right now to enable us to directly emit target specific
6998  // nodes, and remove one by one until they don't return Op anymore.
6999
7000  if (isPALIGNRMask(M, VT, Subtarget))
7001    return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7002                                getShufflePALIGNRImmediate(SVOp),
7003                                DAG);
7004
7005  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7006      SVOp->getSplatIndex() == 0 && V2IsUndef) {
7007    if (VT == MVT::v2f64 || VT == MVT::v2i64)
7008      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7009  }
7010
7011  if (isPSHUFHWMask(M, VT, HasInt256))
7012    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7013                                getShufflePSHUFHWImmediate(SVOp),
7014                                DAG);
7015
7016  if (isPSHUFLWMask(M, VT, HasInt256))
7017    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7018                                getShufflePSHUFLWImmediate(SVOp),
7019                                DAG);
7020
7021  if (isSHUFPMask(M, VT, HasFp256))
7022    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7023                                getShuffleSHUFImmediate(SVOp), DAG);
7024
7025  if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7026    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7027  if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7028    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7029
7030  //===--------------------------------------------------------------------===//
7031  // Generate target specific nodes for 128 or 256-bit shuffles only
7032  // supported in the AVX instruction set.
7033  //
7034
7035  // Handle VMOVDDUPY permutations
7036  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7037    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7038
7039  // Handle VPERMILPS/D* permutations
7040  if (isVPERMILPMask(M, VT, HasFp256)) {
7041    if (HasInt256 && VT == MVT::v8i32)
7042      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7043                                  getShuffleSHUFImmediate(SVOp), DAG);
7044    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7045                                getShuffleSHUFImmediate(SVOp), DAG);
7046  }
7047
7048  // Handle VPERM2F128/VPERM2I128 permutations
7049  if (isVPERM2X128Mask(M, VT, HasFp256))
7050    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7051                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7052
7053  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7054  if (BlendOp.getNode())
7055    return BlendOp;
7056
7057  if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7058    SmallVector<SDValue, 8> permclMask;
7059    for (unsigned i = 0; i != 8; ++i) {
7060      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7061    }
7062    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7063                               &permclMask[0], 8);
7064    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7065    return DAG.getNode(X86ISD::VPERMV, dl, VT,
7066                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7067  }
7068
7069  if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7070    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7071                                getShuffleCLImmediate(SVOp), DAG);
7072
7073  //===--------------------------------------------------------------------===//
7074  // Since no target specific shuffle was selected for this generic one,
7075  // lower it into other known shuffles. FIXME: this isn't true yet, but
7076  // this is the plan.
7077  //
7078
7079  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7080  if (VT == MVT::v8i16) {
7081    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7082    if (NewOp.getNode())
7083      return NewOp;
7084  }
7085
7086  if (VT == MVT::v16i8) {
7087    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7088    if (NewOp.getNode())
7089      return NewOp;
7090  }
7091
7092  if (VT == MVT::v32i8) {
7093    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7094    if (NewOp.getNode())
7095      return NewOp;
7096  }
7097
7098  // Handle all 128-bit wide vectors with 4 elements, and match them with
7099  // several different shuffle types.
7100  if (NumElems == 4 && VT.is128BitVector())
7101    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7102
7103  // Handle general 256-bit shuffles
7104  if (VT.is256BitVector())
7105    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7106
7107  return SDValue();
7108}
7109
7110static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7111  MVT VT = Op.getValueType().getSimpleVT();
7112  DebugLoc dl = Op.getDebugLoc();
7113
7114  if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7115    return SDValue();
7116
7117  if (VT.getSizeInBits() == 8) {
7118    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7119                                  Op.getOperand(0), Op.getOperand(1));
7120    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7121                                  DAG.getValueType(VT));
7122    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7123  }
7124
7125  if (VT.getSizeInBits() == 16) {
7126    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7127    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7128    if (Idx == 0)
7129      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7130                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7131                                     DAG.getNode(ISD::BITCAST, dl,
7132                                                 MVT::v4i32,
7133                                                 Op.getOperand(0)),
7134                                     Op.getOperand(1)));
7135    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7136                                  Op.getOperand(0), Op.getOperand(1));
7137    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7138                                  DAG.getValueType(VT));
7139    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7140  }
7141
7142  if (VT == MVT::f32) {
7143    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7144    // the result back to FR32 register. It's only worth matching if the
7145    // result has a single use which is a store or a bitcast to i32.  And in
7146    // the case of a store, it's not worth it if the index is a constant 0,
7147    // because a MOVSSmr can be used instead, which is smaller and faster.
7148    if (!Op.hasOneUse())
7149      return SDValue();
7150    SDNode *User = *Op.getNode()->use_begin();
7151    if ((User->getOpcode() != ISD::STORE ||
7152         (isa<ConstantSDNode>(Op.getOperand(1)) &&
7153          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7154        (User->getOpcode() != ISD::BITCAST ||
7155         User->getValueType(0) != MVT::i32))
7156      return SDValue();
7157    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7158                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7159                                              Op.getOperand(0)),
7160                                              Op.getOperand(1));
7161    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7162  }
7163
7164  if (VT == MVT::i32 || VT == MVT::i64) {
7165    // ExtractPS/pextrq works with constant index.
7166    if (isa<ConstantSDNode>(Op.getOperand(1)))
7167      return Op;
7168  }
7169  return SDValue();
7170}
7171
7172SDValue
7173X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7174                                           SelectionDAG &DAG) const {
7175  if (!isa<ConstantSDNode>(Op.getOperand(1)))
7176    return SDValue();
7177
7178  SDValue Vec = Op.getOperand(0);
7179  MVT VecVT = Vec.getValueType().getSimpleVT();
7180
7181  // If this is a 256-bit vector result, first extract the 128-bit vector and
7182  // then extract the element from the 128-bit vector.
7183  if (VecVT.is256BitVector()) {
7184    DebugLoc dl = Op.getNode()->getDebugLoc();
7185    unsigned NumElems = VecVT.getVectorNumElements();
7186    SDValue Idx = Op.getOperand(1);
7187    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7188
7189    // Get the 128-bit vector.
7190    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7191
7192    if (IdxVal >= NumElems/2)
7193      IdxVal -= NumElems/2;
7194    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7195                       DAG.getConstant(IdxVal, MVT::i32));
7196  }
7197
7198  assert(VecVT.is128BitVector() && "Unexpected vector length");
7199
7200  if (Subtarget->hasSSE41()) {
7201    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7202    if (Res.getNode())
7203      return Res;
7204  }
7205
7206  MVT VT = Op.getValueType().getSimpleVT();
7207  DebugLoc dl = Op.getDebugLoc();
7208  // TODO: handle v16i8.
7209  if (VT.getSizeInBits() == 16) {
7210    SDValue Vec = Op.getOperand(0);
7211    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7212    if (Idx == 0)
7213      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7214                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7215                                     DAG.getNode(ISD::BITCAST, dl,
7216                                                 MVT::v4i32, Vec),
7217                                     Op.getOperand(1)));
7218    // Transform it so it match pextrw which produces a 32-bit result.
7219    MVT EltVT = MVT::i32;
7220    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7221                                  Op.getOperand(0), Op.getOperand(1));
7222    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7223                                  DAG.getValueType(VT));
7224    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7225  }
7226
7227  if (VT.getSizeInBits() == 32) {
7228    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7229    if (Idx == 0)
7230      return Op;
7231
7232    // SHUFPS the element to the lowest double word, then movss.
7233    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7234    MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7235    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7236                                       DAG.getUNDEF(VVT), Mask);
7237    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7238                       DAG.getIntPtrConstant(0));
7239  }
7240
7241  if (VT.getSizeInBits() == 64) {
7242    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7243    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7244    //        to match extract_elt for f64.
7245    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7246    if (Idx == 0)
7247      return Op;
7248
7249    // UNPCKHPD the element to the lowest double word, then movsd.
7250    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7251    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7252    int Mask[2] = { 1, -1 };
7253    MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7254    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7255                                       DAG.getUNDEF(VVT), Mask);
7256    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7257                       DAG.getIntPtrConstant(0));
7258  }
7259
7260  return SDValue();
7261}
7262
7263static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7264  MVT VT = Op.getValueType().getSimpleVT();
7265  MVT EltVT = VT.getVectorElementType();
7266  DebugLoc dl = Op.getDebugLoc();
7267
7268  SDValue N0 = Op.getOperand(0);
7269  SDValue N1 = Op.getOperand(1);
7270  SDValue N2 = Op.getOperand(2);
7271
7272  if (!VT.is128BitVector())
7273    return SDValue();
7274
7275  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7276      isa<ConstantSDNode>(N2)) {
7277    unsigned Opc;
7278    if (VT == MVT::v8i16)
7279      Opc = X86ISD::PINSRW;
7280    else if (VT == MVT::v16i8)
7281      Opc = X86ISD::PINSRB;
7282    else
7283      Opc = X86ISD::PINSRB;
7284
7285    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7286    // argument.
7287    if (N1.getValueType() != MVT::i32)
7288      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7289    if (N2.getValueType() != MVT::i32)
7290      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7291    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7292  }
7293
7294  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7295    // Bits [7:6] of the constant are the source select.  This will always be
7296    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7297    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7298    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7299    // Bits [5:4] of the constant are the destination select.  This is the
7300    //  value of the incoming immediate.
7301    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7302    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7303    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7304    // Create this as a scalar to vector..
7305    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7306    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7307  }
7308
7309  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7310    // PINSR* works with constant index.
7311    return Op;
7312  }
7313  return SDValue();
7314}
7315
7316SDValue
7317X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7318  MVT VT = Op.getValueType().getSimpleVT();
7319  MVT EltVT = VT.getVectorElementType();
7320
7321  DebugLoc dl = Op.getDebugLoc();
7322  SDValue N0 = Op.getOperand(0);
7323  SDValue N1 = Op.getOperand(1);
7324  SDValue N2 = Op.getOperand(2);
7325
7326  // If this is a 256-bit vector result, first extract the 128-bit vector,
7327  // insert the element into the extracted half and then place it back.
7328  if (VT.is256BitVector()) {
7329    if (!isa<ConstantSDNode>(N2))
7330      return SDValue();
7331
7332    // Get the desired 128-bit vector half.
7333    unsigned NumElems = VT.getVectorNumElements();
7334    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7335    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7336
7337    // Insert the element into the desired half.
7338    bool Upper = IdxVal >= NumElems/2;
7339    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7340                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7341
7342    // Insert the changed part back to the 256-bit vector
7343    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7344  }
7345
7346  if (Subtarget->hasSSE41())
7347    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7348
7349  if (EltVT == MVT::i8)
7350    return SDValue();
7351
7352  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7353    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7354    // as its second argument.
7355    if (N1.getValueType() != MVT::i32)
7356      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7357    if (N2.getValueType() != MVT::i32)
7358      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7359    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7360  }
7361  return SDValue();
7362}
7363
7364static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7365  LLVMContext *Context = DAG.getContext();
7366  DebugLoc dl = Op.getDebugLoc();
7367  MVT OpVT = Op.getValueType().getSimpleVT();
7368
7369  // If this is a 256-bit vector result, first insert into a 128-bit
7370  // vector and then insert into the 256-bit vector.
7371  if (!OpVT.is128BitVector()) {
7372    // Insert into a 128-bit vector.
7373    EVT VT128 = EVT::getVectorVT(*Context,
7374                                 OpVT.getVectorElementType(),
7375                                 OpVT.getVectorNumElements() / 2);
7376
7377    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7378
7379    // Insert the 128-bit vector.
7380    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7381  }
7382
7383  if (OpVT == MVT::v1i64 &&
7384      Op.getOperand(0).getValueType() == MVT::i64)
7385    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7386
7387  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7388  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7389  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7390                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7391}
7392
7393// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7394// a simple subregister reference or explicit instructions to grab
7395// upper bits of a vector.
7396static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7397                                      SelectionDAG &DAG) {
7398  if (Subtarget->hasFp256()) {
7399    DebugLoc dl = Op.getNode()->getDebugLoc();
7400    SDValue Vec = Op.getNode()->getOperand(0);
7401    SDValue Idx = Op.getNode()->getOperand(1);
7402
7403    if (Op.getNode()->getValueType(0).is128BitVector() &&
7404        Vec.getNode()->getValueType(0).is256BitVector() &&
7405        isa<ConstantSDNode>(Idx)) {
7406      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7407      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7408    }
7409  }
7410  return SDValue();
7411}
7412
7413// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7414// simple superregister reference or explicit instructions to insert
7415// the upper bits of a vector.
7416static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7417                                     SelectionDAG &DAG) {
7418  if (Subtarget->hasFp256()) {
7419    DebugLoc dl = Op.getNode()->getDebugLoc();
7420    SDValue Vec = Op.getNode()->getOperand(0);
7421    SDValue SubVec = Op.getNode()->getOperand(1);
7422    SDValue Idx = Op.getNode()->getOperand(2);
7423
7424    if (Op.getNode()->getValueType(0).is256BitVector() &&
7425        SubVec.getNode()->getValueType(0).is128BitVector() &&
7426        isa<ConstantSDNode>(Idx)) {
7427      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7428      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7429    }
7430  }
7431  return SDValue();
7432}
7433
7434// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7435// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7436// one of the above mentioned nodes. It has to be wrapped because otherwise
7437// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7438// be used to form addressing mode. These wrapped nodes will be selected
7439// into MOV32ri.
7440SDValue
7441X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7442  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7443
7444  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7445  // global base reg.
7446  unsigned char OpFlag = 0;
7447  unsigned WrapperKind = X86ISD::Wrapper;
7448  CodeModel::Model M = getTargetMachine().getCodeModel();
7449
7450  if (Subtarget->isPICStyleRIPRel() &&
7451      (M == CodeModel::Small || M == CodeModel::Kernel))
7452    WrapperKind = X86ISD::WrapperRIP;
7453  else if (Subtarget->isPICStyleGOT())
7454    OpFlag = X86II::MO_GOTOFF;
7455  else if (Subtarget->isPICStyleStubPIC())
7456    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7457
7458  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7459                                             CP->getAlignment(),
7460                                             CP->getOffset(), OpFlag);
7461  DebugLoc DL = CP->getDebugLoc();
7462  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7463  // With PIC, the address is actually $g + Offset.
7464  if (OpFlag) {
7465    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7466                         DAG.getNode(X86ISD::GlobalBaseReg,
7467                                     DebugLoc(), getPointerTy()),
7468                         Result);
7469  }
7470
7471  return Result;
7472}
7473
7474SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7475  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7476
7477  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7478  // global base reg.
7479  unsigned char OpFlag = 0;
7480  unsigned WrapperKind = X86ISD::Wrapper;
7481  CodeModel::Model M = getTargetMachine().getCodeModel();
7482
7483  if (Subtarget->isPICStyleRIPRel() &&
7484      (M == CodeModel::Small || M == CodeModel::Kernel))
7485    WrapperKind = X86ISD::WrapperRIP;
7486  else if (Subtarget->isPICStyleGOT())
7487    OpFlag = X86II::MO_GOTOFF;
7488  else if (Subtarget->isPICStyleStubPIC())
7489    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7490
7491  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7492                                          OpFlag);
7493  DebugLoc DL = JT->getDebugLoc();
7494  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7495
7496  // With PIC, the address is actually $g + Offset.
7497  if (OpFlag)
7498    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7499                         DAG.getNode(X86ISD::GlobalBaseReg,
7500                                     DebugLoc(), getPointerTy()),
7501                         Result);
7502
7503  return Result;
7504}
7505
7506SDValue
7507X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7508  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7509
7510  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7511  // global base reg.
7512  unsigned char OpFlag = 0;
7513  unsigned WrapperKind = X86ISD::Wrapper;
7514  CodeModel::Model M = getTargetMachine().getCodeModel();
7515
7516  if (Subtarget->isPICStyleRIPRel() &&
7517      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7518    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7519      OpFlag = X86II::MO_GOTPCREL;
7520    WrapperKind = X86ISD::WrapperRIP;
7521  } else if (Subtarget->isPICStyleGOT()) {
7522    OpFlag = X86II::MO_GOT;
7523  } else if (Subtarget->isPICStyleStubPIC()) {
7524    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7525  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7526    OpFlag = X86II::MO_DARWIN_NONLAZY;
7527  }
7528
7529  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7530
7531  DebugLoc DL = Op.getDebugLoc();
7532  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7533
7534  // With PIC, the address is actually $g + Offset.
7535  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7536      !Subtarget->is64Bit()) {
7537    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7538                         DAG.getNode(X86ISD::GlobalBaseReg,
7539                                     DebugLoc(), getPointerTy()),
7540                         Result);
7541  }
7542
7543  // For symbols that require a load from a stub to get the address, emit the
7544  // load.
7545  if (isGlobalStubReference(OpFlag))
7546    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7547                         MachinePointerInfo::getGOT(), false, false, false, 0);
7548
7549  return Result;
7550}
7551
7552SDValue
7553X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7554  // Create the TargetBlockAddressAddress node.
7555  unsigned char OpFlags =
7556    Subtarget->ClassifyBlockAddressReference();
7557  CodeModel::Model M = getTargetMachine().getCodeModel();
7558  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7559  int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7560  DebugLoc dl = Op.getDebugLoc();
7561  SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7562                                             OpFlags);
7563
7564  if (Subtarget->isPICStyleRIPRel() &&
7565      (M == CodeModel::Small || M == CodeModel::Kernel))
7566    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7567  else
7568    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7569
7570  // With PIC, the address is actually $g + Offset.
7571  if (isGlobalRelativeToPICBase(OpFlags)) {
7572    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7573                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7574                         Result);
7575  }
7576
7577  return Result;
7578}
7579
7580SDValue
7581X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7582                                      int64_t Offset, SelectionDAG &DAG) const {
7583  // Create the TargetGlobalAddress node, folding in the constant
7584  // offset if it is legal.
7585  unsigned char OpFlags =
7586    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7587  CodeModel::Model M = getTargetMachine().getCodeModel();
7588  SDValue Result;
7589  if (OpFlags == X86II::MO_NO_FLAG &&
7590      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7591    // A direct static reference to a global.
7592    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7593    Offset = 0;
7594  } else {
7595    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7596  }
7597
7598  if (Subtarget->isPICStyleRIPRel() &&
7599      (M == CodeModel::Small || M == CodeModel::Kernel))
7600    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7601  else
7602    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7603
7604  // With PIC, the address is actually $g + Offset.
7605  if (isGlobalRelativeToPICBase(OpFlags)) {
7606    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7607                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7608                         Result);
7609  }
7610
7611  // For globals that require a load from a stub to get the address, emit the
7612  // load.
7613  if (isGlobalStubReference(OpFlags))
7614    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7615                         MachinePointerInfo::getGOT(), false, false, false, 0);
7616
7617  // If there was a non-zero offset that we didn't fold, create an explicit
7618  // addition for it.
7619  if (Offset != 0)
7620    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7621                         DAG.getConstant(Offset, getPointerTy()));
7622
7623  return Result;
7624}
7625
7626SDValue
7627X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7628  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7629  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7630  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7631}
7632
7633static SDValue
7634GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7635           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7636           unsigned char OperandFlags, bool LocalDynamic = false) {
7637  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7638  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7639  DebugLoc dl = GA->getDebugLoc();
7640  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7641                                           GA->getValueType(0),
7642                                           GA->getOffset(),
7643                                           OperandFlags);
7644
7645  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7646                                           : X86ISD::TLSADDR;
7647
7648  if (InFlag) {
7649    SDValue Ops[] = { Chain,  TGA, *InFlag };
7650    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7651  } else {
7652    SDValue Ops[]  = { Chain, TGA };
7653    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7654  }
7655
7656  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7657  MFI->setAdjustsStack(true);
7658
7659  SDValue Flag = Chain.getValue(1);
7660  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7661}
7662
7663// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7664static SDValue
7665LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7666                                const EVT PtrVT) {
7667  SDValue InFlag;
7668  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7669  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7670                                   DAG.getNode(X86ISD::GlobalBaseReg,
7671                                               DebugLoc(), PtrVT), InFlag);
7672  InFlag = Chain.getValue(1);
7673
7674  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7675}
7676
7677// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7678static SDValue
7679LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7680                                const EVT PtrVT) {
7681  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7682                    X86::RAX, X86II::MO_TLSGD);
7683}
7684
7685static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7686                                           SelectionDAG &DAG,
7687                                           const EVT PtrVT,
7688                                           bool is64Bit) {
7689  DebugLoc dl = GA->getDebugLoc();
7690
7691  // Get the start address of the TLS block for this module.
7692  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7693      .getInfo<X86MachineFunctionInfo>();
7694  MFI->incNumLocalDynamicTLSAccesses();
7695
7696  SDValue Base;
7697  if (is64Bit) {
7698    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7699                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7700  } else {
7701    SDValue InFlag;
7702    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7703        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7704    InFlag = Chain.getValue(1);
7705    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7706                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7707  }
7708
7709  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7710  // of Base.
7711
7712  // Build x@dtpoff.
7713  unsigned char OperandFlags = X86II::MO_DTPOFF;
7714  unsigned WrapperKind = X86ISD::Wrapper;
7715  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7716                                           GA->getValueType(0),
7717                                           GA->getOffset(), OperandFlags);
7718  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7719
7720  // Add x@dtpoff with the base.
7721  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7722}
7723
7724// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7725static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7726                                   const EVT PtrVT, TLSModel::Model model,
7727                                   bool is64Bit, bool isPIC) {
7728  DebugLoc dl = GA->getDebugLoc();
7729
7730  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7731  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7732                                                         is64Bit ? 257 : 256));
7733
7734  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7735                                      DAG.getIntPtrConstant(0),
7736                                      MachinePointerInfo(Ptr),
7737                                      false, false, false, 0);
7738
7739  unsigned char OperandFlags = 0;
7740  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7741  // initialexec.
7742  unsigned WrapperKind = X86ISD::Wrapper;
7743  if (model == TLSModel::LocalExec) {
7744    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7745  } else if (model == TLSModel::InitialExec) {
7746    if (is64Bit) {
7747      OperandFlags = X86II::MO_GOTTPOFF;
7748      WrapperKind = X86ISD::WrapperRIP;
7749    } else {
7750      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7751    }
7752  } else {
7753    llvm_unreachable("Unexpected model");
7754  }
7755
7756  // emit "addl x@ntpoff,%eax" (local exec)
7757  // or "addl x@indntpoff,%eax" (initial exec)
7758  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7759  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7760                                           GA->getValueType(0),
7761                                           GA->getOffset(), OperandFlags);
7762  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7763
7764  if (model == TLSModel::InitialExec) {
7765    if (isPIC && !is64Bit) {
7766      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7767                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7768                           Offset);
7769    }
7770
7771    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7772                         MachinePointerInfo::getGOT(), false, false, false,
7773                         0);
7774  }
7775
7776  // The address of the thread local variable is the add of the thread
7777  // pointer with the offset of the variable.
7778  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7779}
7780
7781SDValue
7782X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7783
7784  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7785  const GlobalValue *GV = GA->getGlobal();
7786
7787  if (Subtarget->isTargetELF()) {
7788    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7789
7790    switch (model) {
7791      case TLSModel::GeneralDynamic:
7792        if (Subtarget->is64Bit())
7793          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7794        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7795      case TLSModel::LocalDynamic:
7796        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7797                                           Subtarget->is64Bit());
7798      case TLSModel::InitialExec:
7799      case TLSModel::LocalExec:
7800        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7801                                   Subtarget->is64Bit(),
7802                        getTargetMachine().getRelocationModel() == Reloc::PIC_);
7803    }
7804    llvm_unreachable("Unknown TLS model.");
7805  }
7806
7807  if (Subtarget->isTargetDarwin()) {
7808    // Darwin only has one model of TLS.  Lower to that.
7809    unsigned char OpFlag = 0;
7810    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7811                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7812
7813    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7814    // global base reg.
7815    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7816                  !Subtarget->is64Bit();
7817    if (PIC32)
7818      OpFlag = X86II::MO_TLVP_PIC_BASE;
7819    else
7820      OpFlag = X86II::MO_TLVP;
7821    DebugLoc DL = Op.getDebugLoc();
7822    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7823                                                GA->getValueType(0),
7824                                                GA->getOffset(), OpFlag);
7825    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7826
7827    // With PIC32, the address is actually $g + Offset.
7828    if (PIC32)
7829      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7830                           DAG.getNode(X86ISD::GlobalBaseReg,
7831                                       DebugLoc(), getPointerTy()),
7832                           Offset);
7833
7834    // Lowering the machine isd will make sure everything is in the right
7835    // location.
7836    SDValue Chain = DAG.getEntryNode();
7837    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7838    SDValue Args[] = { Chain, Offset };
7839    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7840
7841    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7842    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7843    MFI->setAdjustsStack(true);
7844
7845    // And our return value (tls address) is in the standard call return value
7846    // location.
7847    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7848    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7849                              Chain.getValue(1));
7850  }
7851
7852  if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7853    // Just use the implicit TLS architecture
7854    // Need to generate someting similar to:
7855    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7856    //                                  ; from TEB
7857    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7858    //   mov     rcx, qword [rdx+rcx*8]
7859    //   mov     eax, .tls$:tlsvar
7860    //   [rax+rcx] contains the address
7861    // Windows 64bit: gs:0x58
7862    // Windows 32bit: fs:__tls_array
7863
7864    // If GV is an alias then use the aliasee for determining
7865    // thread-localness.
7866    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7867      GV = GA->resolveAliasedGlobal(false);
7868    DebugLoc dl = GA->getDebugLoc();
7869    SDValue Chain = DAG.getEntryNode();
7870
7871    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7872    // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7873    // use its literal value of 0x2C.
7874    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7875                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7876                                                             256)
7877                                        : Type::getInt32PtrTy(*DAG.getContext(),
7878                                                              257));
7879
7880    SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7881      (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7882        DAG.getExternalSymbol("_tls_array", getPointerTy()));
7883
7884    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7885                                        MachinePointerInfo(Ptr),
7886                                        false, false, false, 0);
7887
7888    // Load the _tls_index variable
7889    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7890    if (Subtarget->is64Bit())
7891      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7892                           IDX, MachinePointerInfo(), MVT::i32,
7893                           false, false, 0);
7894    else
7895      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7896                        false, false, false, 0);
7897
7898    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7899                                    getPointerTy());
7900    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7901
7902    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7903    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7904                      false, false, false, 0);
7905
7906    // Get the offset of start of .tls section
7907    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7908                                             GA->getValueType(0),
7909                                             GA->getOffset(), X86II::MO_SECREL);
7910    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7911
7912    // The address of the thread local variable is the add of the thread
7913    // pointer with the offset of the variable.
7914    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7915  }
7916
7917  llvm_unreachable("TLS not implemented for this target.");
7918}
7919
7920/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7921/// and take a 2 x i32 value to shift plus a shift amount.
7922SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7923  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7924  EVT VT = Op.getValueType();
7925  unsigned VTBits = VT.getSizeInBits();
7926  DebugLoc dl = Op.getDebugLoc();
7927  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7928  SDValue ShOpLo = Op.getOperand(0);
7929  SDValue ShOpHi = Op.getOperand(1);
7930  SDValue ShAmt  = Op.getOperand(2);
7931  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7932                                     DAG.getConstant(VTBits - 1, MVT::i8))
7933                       : DAG.getConstant(0, VT);
7934
7935  SDValue Tmp2, Tmp3;
7936  if (Op.getOpcode() == ISD::SHL_PARTS) {
7937    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7938    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7939  } else {
7940    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7941    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7942  }
7943
7944  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7945                                DAG.getConstant(VTBits, MVT::i8));
7946  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7947                             AndNode, DAG.getConstant(0, MVT::i8));
7948
7949  SDValue Hi, Lo;
7950  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7951  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7952  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7953
7954  if (Op.getOpcode() == ISD::SHL_PARTS) {
7955    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7956    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7957  } else {
7958    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7959    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7960  }
7961
7962  SDValue Ops[2] = { Lo, Hi };
7963  return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7964}
7965
7966SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7967                                           SelectionDAG &DAG) const {
7968  EVT SrcVT = Op.getOperand(0).getValueType();
7969
7970  if (SrcVT.isVector())
7971    return SDValue();
7972
7973  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7974         "Unknown SINT_TO_FP to lower!");
7975
7976  // These are really Legal; return the operand so the caller accepts it as
7977  // Legal.
7978  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7979    return Op;
7980  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7981      Subtarget->is64Bit()) {
7982    return Op;
7983  }
7984
7985  DebugLoc dl = Op.getDebugLoc();
7986  unsigned Size = SrcVT.getSizeInBits()/8;
7987  MachineFunction &MF = DAG.getMachineFunction();
7988  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7989  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7990  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7991                               StackSlot,
7992                               MachinePointerInfo::getFixedStack(SSFI),
7993                               false, false, 0);
7994  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7995}
7996
7997SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7998                                     SDValue StackSlot,
7999                                     SelectionDAG &DAG) const {
8000  // Build the FILD
8001  DebugLoc DL = Op.getDebugLoc();
8002  SDVTList Tys;
8003  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8004  if (useSSE)
8005    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8006  else
8007    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8008
8009  unsigned ByteSize = SrcVT.getSizeInBits()/8;
8010
8011  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8012  MachineMemOperand *MMO;
8013  if (FI) {
8014    int SSFI = FI->getIndex();
8015    MMO =
8016      DAG.getMachineFunction()
8017      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8018                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
8019  } else {
8020    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8021    StackSlot = StackSlot.getOperand(1);
8022  }
8023  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8024  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8025                                           X86ISD::FILD, DL,
8026                                           Tys, Ops, array_lengthof(Ops),
8027                                           SrcVT, MMO);
8028
8029  if (useSSE) {
8030    Chain = Result.getValue(1);
8031    SDValue InFlag = Result.getValue(2);
8032
8033    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8034    // shouldn't be necessary except that RFP cannot be live across
8035    // multiple blocks. When stackifier is fixed, they can be uncoupled.
8036    MachineFunction &MF = DAG.getMachineFunction();
8037    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8038    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8039    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8040    Tys = DAG.getVTList(MVT::Other);
8041    SDValue Ops[] = {
8042      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8043    };
8044    MachineMemOperand *MMO =
8045      DAG.getMachineFunction()
8046      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8047                            MachineMemOperand::MOStore, SSFISize, SSFISize);
8048
8049    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8050                                    Ops, array_lengthof(Ops),
8051                                    Op.getValueType(), MMO);
8052    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8053                         MachinePointerInfo::getFixedStack(SSFI),
8054                         false, false, false, 0);
8055  }
8056
8057  return Result;
8058}
8059
8060// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8061SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8062                                               SelectionDAG &DAG) const {
8063  // This algorithm is not obvious. Here it is what we're trying to output:
8064  /*
8065     movq       %rax,  %xmm0
8066     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8067     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8068     #ifdef __SSE3__
8069       haddpd   %xmm0, %xmm0
8070     #else
8071       pshufd   $0x4e, %xmm0, %xmm1
8072       addpd    %xmm1, %xmm0
8073     #endif
8074  */
8075
8076  DebugLoc dl = Op.getDebugLoc();
8077  LLVMContext *Context = DAG.getContext();
8078
8079  // Build some magic constants.
8080  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8081  Constant *C0 = ConstantDataVector::get(*Context, CV0);
8082  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8083
8084  SmallVector<Constant*,2> CV1;
8085  CV1.push_back(
8086    ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8087                                      APInt(64, 0x4330000000000000ULL))));
8088  CV1.push_back(
8089    ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8090                                      APInt(64, 0x4530000000000000ULL))));
8091  Constant *C1 = ConstantVector::get(CV1);
8092  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8093
8094  // Load the 64-bit value into an XMM register.
8095  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8096                            Op.getOperand(0));
8097  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8098                              MachinePointerInfo::getConstantPool(),
8099                              false, false, false, 16);
8100  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8101                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8102                              CLod0);
8103
8104  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8105                              MachinePointerInfo::getConstantPool(),
8106                              false, false, false, 16);
8107  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8108  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8109  SDValue Result;
8110
8111  if (Subtarget->hasSSE3()) {
8112    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8113    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8114  } else {
8115    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8116    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8117                                           S2F, 0x4E, DAG);
8118    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8119                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8120                         Sub);
8121  }
8122
8123  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8124                     DAG.getIntPtrConstant(0));
8125}
8126
8127// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8128SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8129                                               SelectionDAG &DAG) const {
8130  DebugLoc dl = Op.getDebugLoc();
8131  // FP constant to bias correct the final result.
8132  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8133                                   MVT::f64);
8134
8135  // Load the 32-bit value into an XMM register.
8136  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8137                             Op.getOperand(0));
8138
8139  // Zero out the upper parts of the register.
8140  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8141
8142  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8143                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8144                     DAG.getIntPtrConstant(0));
8145
8146  // Or the load with the bias.
8147  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8148                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8149                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8150                                                   MVT::v2f64, Load)),
8151                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8152                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8153                                                   MVT::v2f64, Bias)));
8154  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8155                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8156                   DAG.getIntPtrConstant(0));
8157
8158  // Subtract the bias.
8159  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8160
8161  // Handle final rounding.
8162  EVT DestVT = Op.getValueType();
8163
8164  if (DestVT.bitsLT(MVT::f64))
8165    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8166                       DAG.getIntPtrConstant(0));
8167  if (DestVT.bitsGT(MVT::f64))
8168    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8169
8170  // Handle final rounding.
8171  return Sub;
8172}
8173
8174SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8175                                               SelectionDAG &DAG) const {
8176  SDValue N0 = Op.getOperand(0);
8177  EVT SVT = N0.getValueType();
8178  DebugLoc dl = Op.getDebugLoc();
8179
8180  assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8181          SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8182         "Custom UINT_TO_FP is not supported!");
8183
8184  EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8185                             SVT.getVectorNumElements());
8186  return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8187                     DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8188}
8189
8190SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8191                                           SelectionDAG &DAG) const {
8192  SDValue N0 = Op.getOperand(0);
8193  DebugLoc dl = Op.getDebugLoc();
8194
8195  if (Op.getValueType().isVector())
8196    return lowerUINT_TO_FP_vec(Op, DAG);
8197
8198  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8199  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8200  // the optimization here.
8201  if (DAG.SignBitIsZero(N0))
8202    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8203
8204  EVT SrcVT = N0.getValueType();
8205  EVT DstVT = Op.getValueType();
8206  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8207    return LowerUINT_TO_FP_i64(Op, DAG);
8208  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8209    return LowerUINT_TO_FP_i32(Op, DAG);
8210  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8211    return SDValue();
8212
8213  // Make a 64-bit buffer, and use it to build an FILD.
8214  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8215  if (SrcVT == MVT::i32) {
8216    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8217    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8218                                     getPointerTy(), StackSlot, WordOff);
8219    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8220                                  StackSlot, MachinePointerInfo(),
8221                                  false, false, 0);
8222    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8223                                  OffsetSlot, MachinePointerInfo(),
8224                                  false, false, 0);
8225    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8226    return Fild;
8227  }
8228
8229  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8230  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8231                               StackSlot, MachinePointerInfo(),
8232                               false, false, 0);
8233  // For i64 source, we need to add the appropriate power of 2 if the input
8234  // was negative.  This is the same as the optimization in
8235  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8236  // we must be careful to do the computation in x87 extended precision, not
8237  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8238  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8239  MachineMemOperand *MMO =
8240    DAG.getMachineFunction()
8241    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8242                          MachineMemOperand::MOLoad, 8, 8);
8243
8244  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8245  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8246  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8247                                         array_lengthof(Ops), MVT::i64, MMO);
8248
8249  APInt FF(32, 0x5F800000ULL);
8250
8251  // Check whether the sign bit is set.
8252  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8253                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8254                                 ISD::SETLT);
8255
8256  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8257  SDValue FudgePtr = DAG.getConstantPool(
8258                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8259                                         getPointerTy());
8260
8261  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8262  SDValue Zero = DAG.getIntPtrConstant(0);
8263  SDValue Four = DAG.getIntPtrConstant(4);
8264  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8265                               Zero, Four);
8266  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8267
8268  // Load the value out, extending it from f32 to f80.
8269  // FIXME: Avoid the extend by constructing the right constant pool?
8270  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8271                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8272                                 MVT::f32, false, false, 4);
8273  // Extend everything to 80 bits to force it to be done on x87.
8274  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8275  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8276}
8277
8278std::pair<SDValue,SDValue>
8279X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8280                                    bool IsSigned, bool IsReplace) const {
8281  DebugLoc DL = Op.getDebugLoc();
8282
8283  EVT DstTy = Op.getValueType();
8284
8285  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8286    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8287    DstTy = MVT::i64;
8288  }
8289
8290  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8291         DstTy.getSimpleVT() >= MVT::i16 &&
8292         "Unknown FP_TO_INT to lower!");
8293
8294  // These are really Legal.
8295  if (DstTy == MVT::i32 &&
8296      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8297    return std::make_pair(SDValue(), SDValue());
8298  if (Subtarget->is64Bit() &&
8299      DstTy == MVT::i64 &&
8300      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8301    return std::make_pair(SDValue(), SDValue());
8302
8303  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8304  // stack slot, or into the FTOL runtime function.
8305  MachineFunction &MF = DAG.getMachineFunction();
8306  unsigned MemSize = DstTy.getSizeInBits()/8;
8307  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8308  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8309
8310  unsigned Opc;
8311  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8312    Opc = X86ISD::WIN_FTOL;
8313  else
8314    switch (DstTy.getSimpleVT().SimpleTy) {
8315    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8316    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8317    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8318    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8319    }
8320
8321  SDValue Chain = DAG.getEntryNode();
8322  SDValue Value = Op.getOperand(0);
8323  EVT TheVT = Op.getOperand(0).getValueType();
8324  // FIXME This causes a redundant load/store if the SSE-class value is already
8325  // in memory, such as if it is on the callstack.
8326  if (isScalarFPTypeInSSEReg(TheVT)) {
8327    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8328    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8329                         MachinePointerInfo::getFixedStack(SSFI),
8330                         false, false, 0);
8331    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8332    SDValue Ops[] = {
8333      Chain, StackSlot, DAG.getValueType(TheVT)
8334    };
8335
8336    MachineMemOperand *MMO =
8337      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8338                              MachineMemOperand::MOLoad, MemSize, MemSize);
8339    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8340                                    array_lengthof(Ops), DstTy, MMO);
8341    Chain = Value.getValue(1);
8342    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8343    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8344  }
8345
8346  MachineMemOperand *MMO =
8347    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8348                            MachineMemOperand::MOStore, MemSize, MemSize);
8349
8350  if (Opc != X86ISD::WIN_FTOL) {
8351    // Build the FP_TO_INT*_IN_MEM
8352    SDValue Ops[] = { Chain, Value, StackSlot };
8353    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8354                                           Ops, array_lengthof(Ops), DstTy,
8355                                           MMO);
8356    return std::make_pair(FIST, StackSlot);
8357  } else {
8358    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8359      DAG.getVTList(MVT::Other, MVT::Glue),
8360      Chain, Value);
8361    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8362      MVT::i32, ftol.getValue(1));
8363    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8364      MVT::i32, eax.getValue(2));
8365    SDValue Ops[] = { eax, edx };
8366    SDValue pair = IsReplace
8367      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8368      : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8369    return std::make_pair(pair, SDValue());
8370  }
8371}
8372
8373static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8374                              const X86Subtarget *Subtarget) {
8375  MVT VT = Op->getValueType(0).getSimpleVT();
8376  SDValue In = Op->getOperand(0);
8377  MVT InVT = In.getValueType().getSimpleVT();
8378  DebugLoc dl = Op->getDebugLoc();
8379
8380  // Optimize vectors in AVX mode:
8381  //
8382  //   v8i16 -> v8i32
8383  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8384  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8385  //   Concat upper and lower parts.
8386  //
8387  //   v4i32 -> v4i64
8388  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8389  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8390  //   Concat upper and lower parts.
8391  //
8392
8393  if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8394      ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8395    return SDValue();
8396
8397  if (Subtarget->hasInt256())
8398    return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8399
8400  SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8401  SDValue Undef = DAG.getUNDEF(InVT);
8402  bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8403  SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8404  SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8405
8406  MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8407                             VT.getVectorNumElements()/2);
8408
8409  OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8410  OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8411
8412  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8413}
8414
8415SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8416                                           SelectionDAG &DAG) const {
8417  if (Subtarget->hasFp256()) {
8418    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8419    if (Res.getNode())
8420      return Res;
8421  }
8422
8423  return SDValue();
8424}
8425SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8426                                            SelectionDAG &DAG) const {
8427  DebugLoc DL = Op.getDebugLoc();
8428  MVT VT = Op.getValueType().getSimpleVT();
8429  SDValue In = Op.getOperand(0);
8430  MVT SVT = In.getValueType().getSimpleVT();
8431
8432  if (Subtarget->hasFp256()) {
8433    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8434    if (Res.getNode())
8435      return Res;
8436  }
8437
8438  if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8439      VT.getVectorNumElements() != SVT.getVectorNumElements())
8440    return SDValue();
8441
8442  assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8443
8444  // AVX2 has better support of integer extending.
8445  if (Subtarget->hasInt256())
8446    return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8447
8448  SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8449  static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8450  SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8451                           DAG.getVectorShuffle(MVT::v8i16, DL, In,
8452                                                DAG.getUNDEF(MVT::v8i16),
8453                                                &Mask[0]));
8454
8455  return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8456}
8457
8458SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8459  DebugLoc DL = Op.getDebugLoc();
8460  MVT VT = Op.getValueType().getSimpleVT();
8461  SDValue In = Op.getOperand(0);
8462  MVT SVT = In.getValueType().getSimpleVT();
8463
8464  if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8465    // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8466    if (Subtarget->hasInt256()) {
8467      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8468      In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8469      In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8470                                ShufMask);
8471      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8472                         DAG.getIntPtrConstant(0));
8473    }
8474
8475    // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8476    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8477                               DAG.getIntPtrConstant(0));
8478    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8479                               DAG.getIntPtrConstant(2));
8480
8481    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8482    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8483
8484    // The PSHUFD mask:
8485    static const int ShufMask1[] = {0, 2, 0, 0};
8486    SDValue Undef = DAG.getUNDEF(VT);
8487    OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8488    OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8489
8490    // The MOVLHPS mask:
8491    static const int ShufMask2[] = {0, 1, 4, 5};
8492    return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8493  }
8494
8495  if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8496    // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8497    if (Subtarget->hasInt256()) {
8498      In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8499
8500      SmallVector<SDValue,32> pshufbMask;
8501      for (unsigned i = 0; i < 2; ++i) {
8502        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8503        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8504        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8505        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8506        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8507        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8508        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8509        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8510        for (unsigned j = 0; j < 8; ++j)
8511          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8512      }
8513      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8514                               &pshufbMask[0], 32);
8515      In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8516      In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8517
8518      static const int ShufMask[] = {0,  2,  -1,  -1};
8519      In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8520                                &ShufMask[0]);
8521      In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8522                       DAG.getIntPtrConstant(0));
8523      return DAG.getNode(ISD::BITCAST, DL, VT, In);
8524    }
8525
8526    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8527                               DAG.getIntPtrConstant(0));
8528
8529    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8530                               DAG.getIntPtrConstant(4));
8531
8532    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8533    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8534
8535    // The PSHUFB mask:
8536    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8537                                   -1, -1, -1, -1, -1, -1, -1, -1};
8538
8539    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8540    OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8541    OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8542
8543    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8544    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8545
8546    // The MOVLHPS Mask:
8547    static const int ShufMask2[] = {0, 1, 4, 5};
8548    SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8549    return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8550  }
8551
8552  // Handle truncation of V256 to V128 using shuffles.
8553  if (!VT.is128BitVector() || !SVT.is256BitVector())
8554    return SDValue();
8555
8556  assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8557         "Invalid op");
8558  assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8559
8560  unsigned NumElems = VT.getVectorNumElements();
8561  EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8562                             NumElems * 2);
8563
8564  SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8565  // Prepare truncation shuffle mask
8566  for (unsigned i = 0; i != NumElems; ++i)
8567    MaskVec[i] = i * 2;
8568  SDValue V = DAG.getVectorShuffle(NVT, DL,
8569                                   DAG.getNode(ISD::BITCAST, DL, NVT, In),
8570                                   DAG.getUNDEF(NVT), &MaskVec[0]);
8571  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8572                     DAG.getIntPtrConstant(0));
8573}
8574
8575SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8576                                           SelectionDAG &DAG) const {
8577  MVT VT = Op.getValueType().getSimpleVT();
8578  if (VT.isVector()) {
8579    if (VT == MVT::v8i16)
8580      return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8581                         DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8582                                     MVT::v8i32, Op.getOperand(0)));
8583    return SDValue();
8584  }
8585
8586  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8587    /*IsSigned=*/ true, /*IsReplace=*/ false);
8588  SDValue FIST = Vals.first, StackSlot = Vals.second;
8589  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8590  if (FIST.getNode() == 0) return Op;
8591
8592  if (StackSlot.getNode())
8593    // Load the result.
8594    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8595                       FIST, StackSlot, MachinePointerInfo(),
8596                       false, false, false, 0);
8597
8598  // The node is the result.
8599  return FIST;
8600}
8601
8602SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8603                                           SelectionDAG &DAG) const {
8604  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8605    /*IsSigned=*/ false, /*IsReplace=*/ false);
8606  SDValue FIST = Vals.first, StackSlot = Vals.second;
8607  assert(FIST.getNode() && "Unexpected failure");
8608
8609  if (StackSlot.getNode())
8610    // Load the result.
8611    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8612                       FIST, StackSlot, MachinePointerInfo(),
8613                       false, false, false, 0);
8614
8615  // The node is the result.
8616  return FIST;
8617}
8618
8619static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8620  DebugLoc DL = Op.getDebugLoc();
8621  MVT VT = Op.getValueType().getSimpleVT();
8622  SDValue In = Op.getOperand(0);
8623  MVT SVT = In.getValueType().getSimpleVT();
8624
8625  assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8626
8627  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8628                     DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8629                                 In, DAG.getUNDEF(SVT)));
8630}
8631
8632SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8633  LLVMContext *Context = DAG.getContext();
8634  DebugLoc dl = Op.getDebugLoc();
8635  MVT VT = Op.getValueType().getSimpleVT();
8636  MVT EltVT = VT;
8637  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8638  if (VT.isVector()) {
8639    EltVT = VT.getVectorElementType();
8640    NumElts = VT.getVectorNumElements();
8641  }
8642  Constant *C;
8643  if (EltVT == MVT::f64)
8644    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8645                                          APInt(64, ~(1ULL << 63))));
8646  else
8647    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8648                                          APInt(32, ~(1U << 31))));
8649  C = ConstantVector::getSplat(NumElts, C);
8650  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8651  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8652  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8653                             MachinePointerInfo::getConstantPool(),
8654                             false, false, false, Alignment);
8655  if (VT.isVector()) {
8656    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8657    return DAG.getNode(ISD::BITCAST, dl, VT,
8658                       DAG.getNode(ISD::AND, dl, ANDVT,
8659                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8660                                               Op.getOperand(0)),
8661                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8662  }
8663  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8664}
8665
8666SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8667  LLVMContext *Context = DAG.getContext();
8668  DebugLoc dl = Op.getDebugLoc();
8669  MVT VT = Op.getValueType().getSimpleVT();
8670  MVT EltVT = VT;
8671  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8672  if (VT.isVector()) {
8673    EltVT = VT.getVectorElementType();
8674    NumElts = VT.getVectorNumElements();
8675  }
8676  Constant *C;
8677  if (EltVT == MVT::f64)
8678    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8679                                          APInt(64, 1ULL << 63)));
8680  else
8681    C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8682                                          APInt(32, 1U << 31)));
8683  C = ConstantVector::getSplat(NumElts, C);
8684  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8685  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8686  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8687                             MachinePointerInfo::getConstantPool(),
8688                             false, false, false, Alignment);
8689  if (VT.isVector()) {
8690    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8691    return DAG.getNode(ISD::BITCAST, dl, VT,
8692                       DAG.getNode(ISD::XOR, dl, XORVT,
8693                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8694                                               Op.getOperand(0)),
8695                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8696  }
8697
8698  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8699}
8700
8701SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8702  LLVMContext *Context = DAG.getContext();
8703  SDValue Op0 = Op.getOperand(0);
8704  SDValue Op1 = Op.getOperand(1);
8705  DebugLoc dl = Op.getDebugLoc();
8706  MVT VT = Op.getValueType().getSimpleVT();
8707  MVT SrcVT = Op1.getValueType().getSimpleVT();
8708
8709  // If second operand is smaller, extend it first.
8710  if (SrcVT.bitsLT(VT)) {
8711    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8712    SrcVT = VT;
8713  }
8714  // And if it is bigger, shrink it first.
8715  if (SrcVT.bitsGT(VT)) {
8716    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8717    SrcVT = VT;
8718  }
8719
8720  // At this point the operands and the result should have the same
8721  // type, and that won't be f80 since that is not custom lowered.
8722
8723  // First get the sign bit of second operand.
8724  SmallVector<Constant*,4> CV;
8725  if (SrcVT == MVT::f64) {
8726    const fltSemantics &Sem = APFloat::IEEEdouble;
8727    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8728    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8729  } else {
8730    const fltSemantics &Sem = APFloat::IEEEsingle;
8731    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8732    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8733    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8734    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8735  }
8736  Constant *C = ConstantVector::get(CV);
8737  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8738  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8739                              MachinePointerInfo::getConstantPool(),
8740                              false, false, false, 16);
8741  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8742
8743  // Shift sign bit right or left if the two operands have different types.
8744  if (SrcVT.bitsGT(VT)) {
8745    // Op0 is MVT::f32, Op1 is MVT::f64.
8746    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8747    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8748                          DAG.getConstant(32, MVT::i32));
8749    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8750    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8751                          DAG.getIntPtrConstant(0));
8752  }
8753
8754  // Clear first operand sign bit.
8755  CV.clear();
8756  if (VT == MVT::f64) {
8757    const fltSemantics &Sem = APFloat::IEEEdouble;
8758    CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8759                                                   APInt(64, ~(1ULL << 63)))));
8760    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8761  } else {
8762    const fltSemantics &Sem = APFloat::IEEEsingle;
8763    CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8764                                                   APInt(32, ~(1U << 31)))));
8765    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8766    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8767    CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8768  }
8769  C = ConstantVector::get(CV);
8770  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8771  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8772                              MachinePointerInfo::getConstantPool(),
8773                              false, false, false, 16);
8774  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8775
8776  // Or the value with the sign bit.
8777  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8778}
8779
8780static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8781  SDValue N0 = Op.getOperand(0);
8782  DebugLoc dl = Op.getDebugLoc();
8783  MVT VT = Op.getValueType().getSimpleVT();
8784
8785  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8786  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8787                                  DAG.getConstant(1, VT));
8788  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8789}
8790
8791// LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8792//
8793SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8794                                                  SelectionDAG &DAG) const {
8795  assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8796
8797  if (!Subtarget->hasSSE41())
8798    return SDValue();
8799
8800  if (!Op->hasOneUse())
8801    return SDValue();
8802
8803  SDNode *N = Op.getNode();
8804  DebugLoc DL = N->getDebugLoc();
8805
8806  SmallVector<SDValue, 8> Opnds;
8807  DenseMap<SDValue, unsigned> VecInMap;
8808  EVT VT = MVT::Other;
8809
8810  // Recognize a special case where a vector is casted into wide integer to
8811  // test all 0s.
8812  Opnds.push_back(N->getOperand(0));
8813  Opnds.push_back(N->getOperand(1));
8814
8815  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8816    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8817    // BFS traverse all OR'd operands.
8818    if (I->getOpcode() == ISD::OR) {
8819      Opnds.push_back(I->getOperand(0));
8820      Opnds.push_back(I->getOperand(1));
8821      // Re-evaluate the number of nodes to be traversed.
8822      e += 2; // 2 more nodes (LHS and RHS) are pushed.
8823      continue;
8824    }
8825
8826    // Quit if a non-EXTRACT_VECTOR_ELT
8827    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8828      return SDValue();
8829
8830    // Quit if without a constant index.
8831    SDValue Idx = I->getOperand(1);
8832    if (!isa<ConstantSDNode>(Idx))
8833      return SDValue();
8834
8835    SDValue ExtractedFromVec = I->getOperand(0);
8836    DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8837    if (M == VecInMap.end()) {
8838      VT = ExtractedFromVec.getValueType();
8839      // Quit if not 128/256-bit vector.
8840      if (!VT.is128BitVector() && !VT.is256BitVector())
8841        return SDValue();
8842      // Quit if not the same type.
8843      if (VecInMap.begin() != VecInMap.end() &&
8844          VT != VecInMap.begin()->first.getValueType())
8845        return SDValue();
8846      M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8847    }
8848    M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8849  }
8850
8851  assert((VT.is128BitVector() || VT.is256BitVector()) &&
8852         "Not extracted from 128-/256-bit vector.");
8853
8854  unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8855  SmallVector<SDValue, 8> VecIns;
8856
8857  for (DenseMap<SDValue, unsigned>::const_iterator
8858        I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8859    // Quit if not all elements are used.
8860    if (I->second != FullMask)
8861      return SDValue();
8862    VecIns.push_back(I->first);
8863  }
8864
8865  EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8866
8867  // Cast all vectors into TestVT for PTEST.
8868  for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8869    VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8870
8871  // If more than one full vectors are evaluated, OR them first before PTEST.
8872  for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8873    // Each iteration will OR 2 nodes and append the result until there is only
8874    // 1 node left, i.e. the final OR'd value of all vectors.
8875    SDValue LHS = VecIns[Slot];
8876    SDValue RHS = VecIns[Slot + 1];
8877    VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8878  }
8879
8880  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8881                     VecIns.back(), VecIns.back());
8882}
8883
8884/// Emit nodes that will be selected as "test Op0,Op0", or something
8885/// equivalent.
8886SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8887                                    SelectionDAG &DAG) const {
8888  DebugLoc dl = Op.getDebugLoc();
8889
8890  // CF and OF aren't always set the way we want. Determine which
8891  // of these we need.
8892  bool NeedCF = false;
8893  bool NeedOF = false;
8894  switch (X86CC) {
8895  default: break;
8896  case X86::COND_A: case X86::COND_AE:
8897  case X86::COND_B: case X86::COND_BE:
8898    NeedCF = true;
8899    break;
8900  case X86::COND_G: case X86::COND_GE:
8901  case X86::COND_L: case X86::COND_LE:
8902  case X86::COND_O: case X86::COND_NO:
8903    NeedOF = true;
8904    break;
8905  }
8906
8907  // See if we can use the EFLAGS value from the operand instead of
8908  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8909  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8910  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8911    // Emit a CMP with 0, which is the TEST pattern.
8912    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8913                       DAG.getConstant(0, Op.getValueType()));
8914
8915  unsigned Opcode = 0;
8916  unsigned NumOperands = 0;
8917
8918  // Truncate operations may prevent the merge of the SETCC instruction
8919  // and the arithmetic intruction before it. Attempt to truncate the operands
8920  // of the arithmetic instruction and use a reduced bit-width instruction.
8921  bool NeedTruncation = false;
8922  SDValue ArithOp = Op;
8923  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8924    SDValue Arith = Op->getOperand(0);
8925    // Both the trunc and the arithmetic op need to have one user each.
8926    if (Arith->hasOneUse())
8927      switch (Arith.getOpcode()) {
8928        default: break;
8929        case ISD::ADD:
8930        case ISD::SUB:
8931        case ISD::AND:
8932        case ISD::OR:
8933        case ISD::XOR: {
8934          NeedTruncation = true;
8935          ArithOp = Arith;
8936        }
8937      }
8938  }
8939
8940  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8941  // which may be the result of a CAST.  We use the variable 'Op', which is the
8942  // non-casted variable when we check for possible users.
8943  switch (ArithOp.getOpcode()) {
8944  case ISD::ADD:
8945    // Due to an isel shortcoming, be conservative if this add is likely to be
8946    // selected as part of a load-modify-store instruction. When the root node
8947    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8948    // uses of other nodes in the match, such as the ADD in this case. This
8949    // leads to the ADD being left around and reselected, with the result being
8950    // two adds in the output.  Alas, even if none our users are stores, that
8951    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8952    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8953    // climbing the DAG back to the root, and it doesn't seem to be worth the
8954    // effort.
8955    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8956         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8957      if (UI->getOpcode() != ISD::CopyToReg &&
8958          UI->getOpcode() != ISD::SETCC &&
8959          UI->getOpcode() != ISD::STORE)
8960        goto default_case;
8961
8962    if (ConstantSDNode *C =
8963        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8964      // An add of one will be selected as an INC.
8965      if (C->getAPIntValue() == 1) {
8966        Opcode = X86ISD::INC;
8967        NumOperands = 1;
8968        break;
8969      }
8970
8971      // An add of negative one (subtract of one) will be selected as a DEC.
8972      if (C->getAPIntValue().isAllOnesValue()) {
8973        Opcode = X86ISD::DEC;
8974        NumOperands = 1;
8975        break;
8976      }
8977    }
8978
8979    // Otherwise use a regular EFLAGS-setting add.
8980    Opcode = X86ISD::ADD;
8981    NumOperands = 2;
8982    break;
8983  case ISD::AND: {
8984    // If the primary and result isn't used, don't bother using X86ISD::AND,
8985    // because a TEST instruction will be better.
8986    bool NonFlagUse = false;
8987    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8988           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8989      SDNode *User = *UI;
8990      unsigned UOpNo = UI.getOperandNo();
8991      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8992        // Look pass truncate.
8993        UOpNo = User->use_begin().getOperandNo();
8994        User = *User->use_begin();
8995      }
8996
8997      if (User->getOpcode() != ISD::BRCOND &&
8998          User->getOpcode() != ISD::SETCC &&
8999          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9000        NonFlagUse = true;
9001        break;
9002      }
9003    }
9004
9005    if (!NonFlagUse)
9006      break;
9007  }
9008    // FALL THROUGH
9009  case ISD::SUB:
9010  case ISD::OR:
9011  case ISD::XOR:
9012    // Due to the ISEL shortcoming noted above, be conservative if this op is
9013    // likely to be selected as part of a load-modify-store instruction.
9014    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9015           UE = Op.getNode()->use_end(); UI != UE; ++UI)
9016      if (UI->getOpcode() == ISD::STORE)
9017        goto default_case;
9018
9019    // Otherwise use a regular EFLAGS-setting instruction.
9020    switch (ArithOp.getOpcode()) {
9021    default: llvm_unreachable("unexpected operator!");
9022    case ISD::SUB: Opcode = X86ISD::SUB; break;
9023    case ISD::XOR: Opcode = X86ISD::XOR; break;
9024    case ISD::AND: Opcode = X86ISD::AND; break;
9025    case ISD::OR: {
9026      if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9027        SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9028        if (EFLAGS.getNode())
9029          return EFLAGS;
9030      }
9031      Opcode = X86ISD::OR;
9032      break;
9033    }
9034    }
9035
9036    NumOperands = 2;
9037    break;
9038  case X86ISD::ADD:
9039  case X86ISD::SUB:
9040  case X86ISD::INC:
9041  case X86ISD::DEC:
9042  case X86ISD::OR:
9043  case X86ISD::XOR:
9044  case X86ISD::AND:
9045    return SDValue(Op.getNode(), 1);
9046  default:
9047  default_case:
9048    break;
9049  }
9050
9051  // If we found that truncation is beneficial, perform the truncation and
9052  // update 'Op'.
9053  if (NeedTruncation) {
9054    EVT VT = Op.getValueType();
9055    SDValue WideVal = Op->getOperand(0);
9056    EVT WideVT = WideVal.getValueType();
9057    unsigned ConvertedOp = 0;
9058    // Use a target machine opcode to prevent further DAGCombine
9059    // optimizations that may separate the arithmetic operations
9060    // from the setcc node.
9061    switch (WideVal.getOpcode()) {
9062      default: break;
9063      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9064      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9065      case ISD::AND: ConvertedOp = X86ISD::AND; break;
9066      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9067      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9068    }
9069
9070    if (ConvertedOp) {
9071      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9072      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9073        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9074        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9075        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9076      }
9077    }
9078  }
9079
9080  if (Opcode == 0)
9081    // Emit a CMP with 0, which is the TEST pattern.
9082    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9083                       DAG.getConstant(0, Op.getValueType()));
9084
9085  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9086  SmallVector<SDValue, 4> Ops;
9087  for (unsigned i = 0; i != NumOperands; ++i)
9088    Ops.push_back(Op.getOperand(i));
9089
9090  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9091  DAG.ReplaceAllUsesWith(Op, New);
9092  return SDValue(New.getNode(), 1);
9093}
9094
9095/// Emit nodes that will be selected as "cmp Op0,Op1", or something
9096/// equivalent.
9097SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9098                                   SelectionDAG &DAG) const {
9099  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9100    if (C->getAPIntValue() == 0)
9101      return EmitTest(Op0, X86CC, DAG);
9102
9103  DebugLoc dl = Op0.getDebugLoc();
9104  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9105       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9106    // Use SUB instead of CMP to enable CSE between SUB and CMP.
9107    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9108    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9109                              Op0, Op1);
9110    return SDValue(Sub.getNode(), 1);
9111  }
9112  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9113}
9114
9115/// Convert a comparison if required by the subtarget.
9116SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9117                                                 SelectionDAG &DAG) const {
9118  // If the subtarget does not support the FUCOMI instruction, floating-point
9119  // comparisons have to be converted.
9120  if (Subtarget->hasCMov() ||
9121      Cmp.getOpcode() != X86ISD::CMP ||
9122      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9123      !Cmp.getOperand(1).getValueType().isFloatingPoint())
9124    return Cmp;
9125
9126  // The instruction selector will select an FUCOM instruction instead of
9127  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9128  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9129  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9130  DebugLoc dl = Cmp.getDebugLoc();
9131  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9132  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9133  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9134                            DAG.getConstant(8, MVT::i8));
9135  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9136  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9137}
9138
9139static bool isAllOnes(SDValue V) {
9140  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9141  return C && C->isAllOnesValue();
9142}
9143
9144/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9145/// if it's possible.
9146SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9147                                     DebugLoc dl, SelectionDAG &DAG) const {
9148  SDValue Op0 = And.getOperand(0);
9149  SDValue Op1 = And.getOperand(1);
9150  if (Op0.getOpcode() == ISD::TRUNCATE)
9151    Op0 = Op0.getOperand(0);
9152  if (Op1.getOpcode() == ISD::TRUNCATE)
9153    Op1 = Op1.getOperand(0);
9154
9155  SDValue LHS, RHS;
9156  if (Op1.getOpcode() == ISD::SHL)
9157    std::swap(Op0, Op1);
9158  if (Op0.getOpcode() == ISD::SHL) {
9159    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9160      if (And00C->getZExtValue() == 1) {
9161        // If we looked past a truncate, check that it's only truncating away
9162        // known zeros.
9163        unsigned BitWidth = Op0.getValueSizeInBits();
9164        unsigned AndBitWidth = And.getValueSizeInBits();
9165        if (BitWidth > AndBitWidth) {
9166          APInt Zeros, Ones;
9167          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9168          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9169            return SDValue();
9170        }
9171        LHS = Op1;
9172        RHS = Op0.getOperand(1);
9173      }
9174  } else if (Op1.getOpcode() == ISD::Constant) {
9175    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9176    uint64_t AndRHSVal = AndRHS->getZExtValue();
9177    SDValue AndLHS = Op0;
9178
9179    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9180      LHS = AndLHS.getOperand(0);
9181      RHS = AndLHS.getOperand(1);
9182    }
9183
9184    // Use BT if the immediate can't be encoded in a TEST instruction.
9185    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9186      LHS = AndLHS;
9187      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9188    }
9189  }
9190
9191  if (LHS.getNode()) {
9192    // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9193    // the condition code later.
9194    bool Invert = false;
9195    if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9196      Invert = true;
9197      LHS = LHS.getOperand(0);
9198    }
9199
9200    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9201    // instruction.  Since the shift amount is in-range-or-undefined, we know
9202    // that doing a bittest on the i32 value is ok.  We extend to i32 because
9203    // the encoding for the i16 version is larger than the i32 version.
9204    // Also promote i16 to i32 for performance / code size reason.
9205    if (LHS.getValueType() == MVT::i8 ||
9206        LHS.getValueType() == MVT::i16)
9207      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9208
9209    // If the operand types disagree, extend the shift amount to match.  Since
9210    // BT ignores high bits (like shifts) we can use anyextend.
9211    if (LHS.getValueType() != RHS.getValueType())
9212      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9213
9214    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9215    X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9216    // Flip the condition if the LHS was a not instruction
9217    if (Invert)
9218      Cond = X86::GetOppositeBranchCondition(Cond);
9219    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9220                       DAG.getConstant(Cond, MVT::i8), BT);
9221  }
9222
9223  return SDValue();
9224}
9225
9226// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9227// ones, and then concatenate the result back.
9228static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9229  MVT VT = Op.getValueType().getSimpleVT();
9230
9231  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9232         "Unsupported value type for operation");
9233
9234  unsigned NumElems = VT.getVectorNumElements();
9235  DebugLoc dl = Op.getDebugLoc();
9236  SDValue CC = Op.getOperand(2);
9237
9238  // Extract the LHS vectors
9239  SDValue LHS = Op.getOperand(0);
9240  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9241  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9242
9243  // Extract the RHS vectors
9244  SDValue RHS = Op.getOperand(1);
9245  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9246  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9247
9248  // Issue the operation on the smaller types and concatenate the result back
9249  MVT EltVT = VT.getVectorElementType();
9250  MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9251  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9252                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9253                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9254}
9255
9256static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9257                           SelectionDAG &DAG) {
9258  SDValue Cond;
9259  SDValue Op0 = Op.getOperand(0);
9260  SDValue Op1 = Op.getOperand(1);
9261  SDValue CC = Op.getOperand(2);
9262  MVT VT = Op.getValueType().getSimpleVT();
9263  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9264  bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9265  DebugLoc dl = Op.getDebugLoc();
9266
9267  if (isFP) {
9268#ifndef NDEBUG
9269    MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9270    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9271#endif
9272
9273    unsigned SSECC;
9274    bool Swap = false;
9275
9276    // SSE Condition code mapping:
9277    //  0 - EQ
9278    //  1 - LT
9279    //  2 - LE
9280    //  3 - UNORD
9281    //  4 - NEQ
9282    //  5 - NLT
9283    //  6 - NLE
9284    //  7 - ORD
9285    switch (SetCCOpcode) {
9286    default: llvm_unreachable("Unexpected SETCC condition");
9287    case ISD::SETOEQ:
9288    case ISD::SETEQ:  SSECC = 0; break;
9289    case ISD::SETOGT:
9290    case ISD::SETGT: Swap = true; // Fallthrough
9291    case ISD::SETLT:
9292    case ISD::SETOLT: SSECC = 1; break;
9293    case ISD::SETOGE:
9294    case ISD::SETGE: Swap = true; // Fallthrough
9295    case ISD::SETLE:
9296    case ISD::SETOLE: SSECC = 2; break;
9297    case ISD::SETUO:  SSECC = 3; break;
9298    case ISD::SETUNE:
9299    case ISD::SETNE:  SSECC = 4; break;
9300    case ISD::SETULE: Swap = true; // Fallthrough
9301    case ISD::SETUGE: SSECC = 5; break;
9302    case ISD::SETULT: Swap = true; // Fallthrough
9303    case ISD::SETUGT: SSECC = 6; break;
9304    case ISD::SETO:   SSECC = 7; break;
9305    case ISD::SETUEQ:
9306    case ISD::SETONE: SSECC = 8; break;
9307    }
9308    if (Swap)
9309      std::swap(Op0, Op1);
9310
9311    // In the two special cases we can't handle, emit two comparisons.
9312    if (SSECC == 8) {
9313      unsigned CC0, CC1;
9314      unsigned CombineOpc;
9315      if (SetCCOpcode == ISD::SETUEQ) {
9316        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9317      } else {
9318        assert(SetCCOpcode == ISD::SETONE);
9319        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9320      }
9321
9322      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9323                                 DAG.getConstant(CC0, MVT::i8));
9324      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9325                                 DAG.getConstant(CC1, MVT::i8));
9326      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9327    }
9328    // Handle all other FP comparisons here.
9329    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9330                       DAG.getConstant(SSECC, MVT::i8));
9331  }
9332
9333  // Break 256-bit integer vector compare into smaller ones.
9334  if (VT.is256BitVector() && !Subtarget->hasInt256())
9335    return Lower256IntVSETCC(Op, DAG);
9336
9337  // We are handling one of the integer comparisons here.  Since SSE only has
9338  // GT and EQ comparisons for integer, swapping operands and multiple
9339  // operations may be required for some comparisons.
9340  unsigned Opc;
9341  bool Swap = false, Invert = false, FlipSigns = false;
9342
9343  switch (SetCCOpcode) {
9344  default: llvm_unreachable("Unexpected SETCC condition");
9345  case ISD::SETNE:  Invert = true;
9346  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9347  case ISD::SETLT:  Swap = true;
9348  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9349  case ISD::SETGE:  Swap = true;
9350  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9351  case ISD::SETULT: Swap = true;
9352  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9353  case ISD::SETUGE: Swap = true;
9354  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9355  }
9356  if (Swap)
9357    std::swap(Op0, Op1);
9358
9359  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9360  // bits of the inputs before performing those operations.
9361  if (FlipSigns) {
9362    EVT EltVT = VT.getVectorElementType();
9363    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9364                                      EltVT);
9365    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9366    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9367                                    SignBits.size());
9368    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9369    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9370  }
9371
9372  // Check that the operation in question is available (most are plain SSE2,
9373  // but PCMPGTQ and PCMPEQQ have different requirements).
9374  if (VT == MVT::v2i64) {
9375    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9376      assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9377
9378      // First cast everything to the right type,
9379      Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9380      Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9381
9382      // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9383      SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9384      SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9385
9386      // Create masks for only the low parts/high parts of the 64 bit integers.
9387      const int MaskHi[] = { 1, 1, 3, 3 };
9388      const int MaskLo[] = { 0, 0, 2, 2 };
9389      SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9390      SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9391      SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9392
9393      SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9394      Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9395
9396      if (Invert)
9397        Result = DAG.getNOT(dl, Result, MVT::v4i32);
9398
9399      return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9400    }
9401
9402    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9403      // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9404      // pcmpeqd + pshufd + pand.
9405      assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9406
9407      // First cast everything to the right type,
9408      Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9409      Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9410
9411      // Do the compare.
9412      SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9413
9414      // Make sure the lower and upper halves are both all-ones.
9415      const int Mask[] = { 1, 0, 3, 2 };
9416      SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9417      Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9418
9419      if (Invert)
9420        Result = DAG.getNOT(dl, Result, MVT::v4i32);
9421
9422      return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9423    }
9424  }
9425
9426  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9427
9428  // If the logical-not of the result is required, perform that now.
9429  if (Invert)
9430    Result = DAG.getNOT(dl, Result, VT);
9431
9432  return Result;
9433}
9434
9435SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9436
9437  MVT VT = Op.getValueType().getSimpleVT();
9438
9439  if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9440
9441  assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9442  SDValue Op0 = Op.getOperand(0);
9443  SDValue Op1 = Op.getOperand(1);
9444  DebugLoc dl = Op.getDebugLoc();
9445  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9446
9447  // Optimize to BT if possible.
9448  // Lower (X & (1 << N)) == 0 to BT(X, N).
9449  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9450  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9451  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9452      Op1.getOpcode() == ISD::Constant &&
9453      cast<ConstantSDNode>(Op1)->isNullValue() &&
9454      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9455    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9456    if (NewSetCC.getNode())
9457      return NewSetCC;
9458  }
9459
9460  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9461  // these.
9462  if (Op1.getOpcode() == ISD::Constant &&
9463      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9464       cast<ConstantSDNode>(Op1)->isNullValue()) &&
9465      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9466
9467    // If the input is a setcc, then reuse the input setcc or use a new one with
9468    // the inverted condition.
9469    if (Op0.getOpcode() == X86ISD::SETCC) {
9470      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9471      bool Invert = (CC == ISD::SETNE) ^
9472        cast<ConstantSDNode>(Op1)->isNullValue();
9473      if (!Invert) return Op0;
9474
9475      CCode = X86::GetOppositeBranchCondition(CCode);
9476      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9477                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9478    }
9479  }
9480
9481  bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9482  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9483  if (X86CC == X86::COND_INVALID)
9484    return SDValue();
9485
9486  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9487  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9488  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9489                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9490}
9491
9492// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9493static bool isX86LogicalCmp(SDValue Op) {
9494  unsigned Opc = Op.getNode()->getOpcode();
9495  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9496      Opc == X86ISD::SAHF)
9497    return true;
9498  if (Op.getResNo() == 1 &&
9499      (Opc == X86ISD::ADD ||
9500       Opc == X86ISD::SUB ||
9501       Opc == X86ISD::ADC ||
9502       Opc == X86ISD::SBB ||
9503       Opc == X86ISD::SMUL ||
9504       Opc == X86ISD::UMUL ||
9505       Opc == X86ISD::INC ||
9506       Opc == X86ISD::DEC ||
9507       Opc == X86ISD::OR ||
9508       Opc == X86ISD::XOR ||
9509       Opc == X86ISD::AND))
9510    return true;
9511
9512  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9513    return true;
9514
9515  return false;
9516}
9517
9518static bool isZero(SDValue V) {
9519  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9520  return C && C->isNullValue();
9521}
9522
9523static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9524  if (V.getOpcode() != ISD::TRUNCATE)
9525    return false;
9526
9527  SDValue VOp0 = V.getOperand(0);
9528  unsigned InBits = VOp0.getValueSizeInBits();
9529  unsigned Bits = V.getValueSizeInBits();
9530  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9531}
9532
9533SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9534  bool addTest = true;
9535  SDValue Cond  = Op.getOperand(0);
9536  SDValue Op1 = Op.getOperand(1);
9537  SDValue Op2 = Op.getOperand(2);
9538  DebugLoc DL = Op.getDebugLoc();
9539  SDValue CC;
9540
9541  if (Cond.getOpcode() == ISD::SETCC) {
9542    SDValue NewCond = LowerSETCC(Cond, DAG);
9543    if (NewCond.getNode())
9544      Cond = NewCond;
9545  }
9546
9547  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9548  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9549  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9550  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9551  if (Cond.getOpcode() == X86ISD::SETCC &&
9552      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9553      isZero(Cond.getOperand(1).getOperand(1))) {
9554    SDValue Cmp = Cond.getOperand(1);
9555
9556    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9557
9558    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9559        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9560      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9561
9562      SDValue CmpOp0 = Cmp.getOperand(0);
9563      // Apply further optimizations for special cases
9564      // (select (x != 0), -1, 0) -> neg & sbb
9565      // (select (x == 0), 0, -1) -> neg & sbb
9566      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9567        if (YC->isNullValue() &&
9568            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9569          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9570          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9571                                    DAG.getConstant(0, CmpOp0.getValueType()),
9572                                    CmpOp0);
9573          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9574                                    DAG.getConstant(X86::COND_B, MVT::i8),
9575                                    SDValue(Neg.getNode(), 1));
9576          return Res;
9577        }
9578
9579      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9580                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9581      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9582
9583      SDValue Res =   // Res = 0 or -1.
9584        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9585                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9586
9587      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9588        Res = DAG.getNOT(DL, Res, Res.getValueType());
9589
9590      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9591      if (N2C == 0 || !N2C->isNullValue())
9592        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9593      return Res;
9594    }
9595  }
9596
9597  // Look past (and (setcc_carry (cmp ...)), 1).
9598  if (Cond.getOpcode() == ISD::AND &&
9599      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9600    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9601    if (C && C->getAPIntValue() == 1)
9602      Cond = Cond.getOperand(0);
9603  }
9604
9605  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9606  // setting operand in place of the X86ISD::SETCC.
9607  unsigned CondOpcode = Cond.getOpcode();
9608  if (CondOpcode == X86ISD::SETCC ||
9609      CondOpcode == X86ISD::SETCC_CARRY) {
9610    CC = Cond.getOperand(0);
9611
9612    SDValue Cmp = Cond.getOperand(1);
9613    unsigned Opc = Cmp.getOpcode();
9614    MVT VT = Op.getValueType().getSimpleVT();
9615
9616    bool IllegalFPCMov = false;
9617    if (VT.isFloatingPoint() && !VT.isVector() &&
9618        !isScalarFPTypeInSSEReg(VT))  // FPStack?
9619      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9620
9621    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9622        Opc == X86ISD::BT) { // FIXME
9623      Cond = Cmp;
9624      addTest = false;
9625    }
9626  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9627             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9628             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9629              Cond.getOperand(0).getValueType() != MVT::i8)) {
9630    SDValue LHS = Cond.getOperand(0);
9631    SDValue RHS = Cond.getOperand(1);
9632    unsigned X86Opcode;
9633    unsigned X86Cond;
9634    SDVTList VTs;
9635    switch (CondOpcode) {
9636    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9637    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9638    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9639    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9640    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9641    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9642    default: llvm_unreachable("unexpected overflowing operator");
9643    }
9644    if (CondOpcode == ISD::UMULO)
9645      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9646                          MVT::i32);
9647    else
9648      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9649
9650    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9651
9652    if (CondOpcode == ISD::UMULO)
9653      Cond = X86Op.getValue(2);
9654    else
9655      Cond = X86Op.getValue(1);
9656
9657    CC = DAG.getConstant(X86Cond, MVT::i8);
9658    addTest = false;
9659  }
9660
9661  if (addTest) {
9662    // Look pass the truncate if the high bits are known zero.
9663    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9664        Cond = Cond.getOperand(0);
9665
9666    // We know the result of AND is compared against zero. Try to match
9667    // it to BT.
9668    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9669      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9670      if (NewSetCC.getNode()) {
9671        CC = NewSetCC.getOperand(0);
9672        Cond = NewSetCC.getOperand(1);
9673        addTest = false;
9674      }
9675    }
9676  }
9677
9678  if (addTest) {
9679    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9680    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9681  }
9682
9683  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9684  // a <  b ?  0 : -1 -> RES = setcc_carry
9685  // a >= b ? -1 :  0 -> RES = setcc_carry
9686  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9687  if (Cond.getOpcode() == X86ISD::SUB) {
9688    Cond = ConvertCmpIfNecessary(Cond, DAG);
9689    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9690
9691    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9692        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9693      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9694                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9695      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9696        return DAG.getNOT(DL, Res, Res.getValueType());
9697      return Res;
9698    }
9699  }
9700
9701  // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9702  // widen the cmov and push the truncate through. This avoids introducing a new
9703  // branch during isel and doesn't add any extensions.
9704  if (Op.getValueType() == MVT::i8 &&
9705      Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9706    SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9707    if (T1.getValueType() == T2.getValueType() &&
9708        // Blacklist CopyFromReg to avoid partial register stalls.
9709        T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9710      SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9711      SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9712      return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9713    }
9714  }
9715
9716  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9717  // condition is true.
9718  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9719  SDValue Ops[] = { Op2, Op1, CC, Cond };
9720  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9721}
9722
9723SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9724                                            SelectionDAG &DAG) const {
9725  MVT VT = Op->getValueType(0).getSimpleVT();
9726  SDValue In = Op->getOperand(0);
9727  MVT InVT = In.getValueType().getSimpleVT();
9728  DebugLoc dl = Op->getDebugLoc();
9729
9730  if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9731      (VT != MVT::v8i32 || InVT != MVT::v8i16))
9732    return SDValue();
9733
9734  if (Subtarget->hasInt256())
9735    return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9736
9737  // Optimize vectors in AVX mode
9738  // Sign extend  v8i16 to v8i32 and
9739  //              v4i32 to v4i64
9740  //
9741  // Divide input vector into two parts
9742  // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9743  // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9744  // concat the vectors to original VT
9745
9746  unsigned NumElems = InVT.getVectorNumElements();
9747  SDValue Undef = DAG.getUNDEF(InVT);
9748
9749  SmallVector<int,8> ShufMask1(NumElems, -1);
9750  for (unsigned i = 0; i != NumElems/2; ++i)
9751    ShufMask1[i] = i;
9752
9753  SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9754
9755  SmallVector<int,8> ShufMask2(NumElems, -1);
9756  for (unsigned i = 0; i != NumElems/2; ++i)
9757    ShufMask2[i] = i + NumElems/2;
9758
9759  SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9760
9761  MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9762                                VT.getVectorNumElements()/2);
9763
9764  OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9765  OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9766
9767  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9768}
9769
9770// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9771// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9772// from the AND / OR.
9773static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9774  Opc = Op.getOpcode();
9775  if (Opc != ISD::OR && Opc != ISD::AND)
9776    return false;
9777  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9778          Op.getOperand(0).hasOneUse() &&
9779          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9780          Op.getOperand(1).hasOneUse());
9781}
9782
9783// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9784// 1 and that the SETCC node has a single use.
9785static bool isXor1OfSetCC(SDValue Op) {
9786  if (Op.getOpcode() != ISD::XOR)
9787    return false;
9788  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9789  if (N1C && N1C->getAPIntValue() == 1) {
9790    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9791      Op.getOperand(0).hasOneUse();
9792  }
9793  return false;
9794}
9795
9796SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9797  bool addTest = true;
9798  SDValue Chain = Op.getOperand(0);
9799  SDValue Cond  = Op.getOperand(1);
9800  SDValue Dest  = Op.getOperand(2);
9801  DebugLoc dl = Op.getDebugLoc();
9802  SDValue CC;
9803  bool Inverted = false;
9804
9805  if (Cond.getOpcode() == ISD::SETCC) {
9806    // Check for setcc([su]{add,sub,mul}o == 0).
9807    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9808        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9809        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9810        Cond.getOperand(0).getResNo() == 1 &&
9811        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9812         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9813         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9814         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9815         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9816         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9817      Inverted = true;
9818      Cond = Cond.getOperand(0);
9819    } else {
9820      SDValue NewCond = LowerSETCC(Cond, DAG);
9821      if (NewCond.getNode())
9822        Cond = NewCond;
9823    }
9824  }
9825#if 0
9826  // FIXME: LowerXALUO doesn't handle these!!
9827  else if (Cond.getOpcode() == X86ISD::ADD  ||
9828           Cond.getOpcode() == X86ISD::SUB  ||
9829           Cond.getOpcode() == X86ISD::SMUL ||
9830           Cond.getOpcode() == X86ISD::UMUL)
9831    Cond = LowerXALUO(Cond, DAG);
9832#endif
9833
9834  // Look pass (and (setcc_carry (cmp ...)), 1).
9835  if (Cond.getOpcode() == ISD::AND &&
9836      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9837    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9838    if (C && C->getAPIntValue() == 1)
9839      Cond = Cond.getOperand(0);
9840  }
9841
9842  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9843  // setting operand in place of the X86ISD::SETCC.
9844  unsigned CondOpcode = Cond.getOpcode();
9845  if (CondOpcode == X86ISD::SETCC ||
9846      CondOpcode == X86ISD::SETCC_CARRY) {
9847    CC = Cond.getOperand(0);
9848
9849    SDValue Cmp = Cond.getOperand(1);
9850    unsigned Opc = Cmp.getOpcode();
9851    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9852    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9853      Cond = Cmp;
9854      addTest = false;
9855    } else {
9856      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9857      default: break;
9858      case X86::COND_O:
9859      case X86::COND_B:
9860        // These can only come from an arithmetic instruction with overflow,
9861        // e.g. SADDO, UADDO.
9862        Cond = Cond.getNode()->getOperand(1);
9863        addTest = false;
9864        break;
9865      }
9866    }
9867  }
9868  CondOpcode = Cond.getOpcode();
9869  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9870      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9871      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9872       Cond.getOperand(0).getValueType() != MVT::i8)) {
9873    SDValue LHS = Cond.getOperand(0);
9874    SDValue RHS = Cond.getOperand(1);
9875    unsigned X86Opcode;
9876    unsigned X86Cond;
9877    SDVTList VTs;
9878    switch (CondOpcode) {
9879    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9880    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9881    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9882    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9883    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9884    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9885    default: llvm_unreachable("unexpected overflowing operator");
9886    }
9887    if (Inverted)
9888      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9889    if (CondOpcode == ISD::UMULO)
9890      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9891                          MVT::i32);
9892    else
9893      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9894
9895    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9896
9897    if (CondOpcode == ISD::UMULO)
9898      Cond = X86Op.getValue(2);
9899    else
9900      Cond = X86Op.getValue(1);
9901
9902    CC = DAG.getConstant(X86Cond, MVT::i8);
9903    addTest = false;
9904  } else {
9905    unsigned CondOpc;
9906    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9907      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9908      if (CondOpc == ISD::OR) {
9909        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9910        // two branches instead of an explicit OR instruction with a
9911        // separate test.
9912        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9913            isX86LogicalCmp(Cmp)) {
9914          CC = Cond.getOperand(0).getOperand(0);
9915          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9916                              Chain, Dest, CC, Cmp);
9917          CC = Cond.getOperand(1).getOperand(0);
9918          Cond = Cmp;
9919          addTest = false;
9920        }
9921      } else { // ISD::AND
9922        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9923        // two branches instead of an explicit AND instruction with a
9924        // separate test. However, we only do this if this block doesn't
9925        // have a fall-through edge, because this requires an explicit
9926        // jmp when the condition is false.
9927        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9928            isX86LogicalCmp(Cmp) &&
9929            Op.getNode()->hasOneUse()) {
9930          X86::CondCode CCode =
9931            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9932          CCode = X86::GetOppositeBranchCondition(CCode);
9933          CC = DAG.getConstant(CCode, MVT::i8);
9934          SDNode *User = *Op.getNode()->use_begin();
9935          // Look for an unconditional branch following this conditional branch.
9936          // We need this because we need to reverse the successors in order
9937          // to implement FCMP_OEQ.
9938          if (User->getOpcode() == ISD::BR) {
9939            SDValue FalseBB = User->getOperand(1);
9940            SDNode *NewBR =
9941              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9942            assert(NewBR == User);
9943            (void)NewBR;
9944            Dest = FalseBB;
9945
9946            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9947                                Chain, Dest, CC, Cmp);
9948            X86::CondCode CCode =
9949              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9950            CCode = X86::GetOppositeBranchCondition(CCode);
9951            CC = DAG.getConstant(CCode, MVT::i8);
9952            Cond = Cmp;
9953            addTest = false;
9954          }
9955        }
9956      }
9957    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9958      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9959      // It should be transformed during dag combiner except when the condition
9960      // is set by a arithmetics with overflow node.
9961      X86::CondCode CCode =
9962        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9963      CCode = X86::GetOppositeBranchCondition(CCode);
9964      CC = DAG.getConstant(CCode, MVT::i8);
9965      Cond = Cond.getOperand(0).getOperand(1);
9966      addTest = false;
9967    } else if (Cond.getOpcode() == ISD::SETCC &&
9968               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9969      // For FCMP_OEQ, we can emit
9970      // two branches instead of an explicit AND instruction with a
9971      // separate test. However, we only do this if this block doesn't
9972      // have a fall-through edge, because this requires an explicit
9973      // jmp when the condition is false.
9974      if (Op.getNode()->hasOneUse()) {
9975        SDNode *User = *Op.getNode()->use_begin();
9976        // Look for an unconditional branch following this conditional branch.
9977        // We need this because we need to reverse the successors in order
9978        // to implement FCMP_OEQ.
9979        if (User->getOpcode() == ISD::BR) {
9980          SDValue FalseBB = User->getOperand(1);
9981          SDNode *NewBR =
9982            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9983          assert(NewBR == User);
9984          (void)NewBR;
9985          Dest = FalseBB;
9986
9987          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9988                                    Cond.getOperand(0), Cond.getOperand(1));
9989          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9990          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9991          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9992                              Chain, Dest, CC, Cmp);
9993          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9994          Cond = Cmp;
9995          addTest = false;
9996        }
9997      }
9998    } else if (Cond.getOpcode() == ISD::SETCC &&
9999               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10000      // For FCMP_UNE, we can emit
10001      // two branches instead of an explicit AND instruction with a
10002      // separate test. However, we only do this if this block doesn't
10003      // have a fall-through edge, because this requires an explicit
10004      // jmp when the condition is false.
10005      if (Op.getNode()->hasOneUse()) {
10006        SDNode *User = *Op.getNode()->use_begin();
10007        // Look for an unconditional branch following this conditional branch.
10008        // We need this because we need to reverse the successors in order
10009        // to implement FCMP_UNE.
10010        if (User->getOpcode() == ISD::BR) {
10011          SDValue FalseBB = User->getOperand(1);
10012          SDNode *NewBR =
10013            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10014          assert(NewBR == User);
10015          (void)NewBR;
10016
10017          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10018                                    Cond.getOperand(0), Cond.getOperand(1));
10019          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10020          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10021          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10022                              Chain, Dest, CC, Cmp);
10023          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10024          Cond = Cmp;
10025          addTest = false;
10026          Dest = FalseBB;
10027        }
10028      }
10029    }
10030  }
10031
10032  if (addTest) {
10033    // Look pass the truncate if the high bits are known zero.
10034    if (isTruncWithZeroHighBitsInput(Cond, DAG))
10035        Cond = Cond.getOperand(0);
10036
10037    // We know the result of AND is compared against zero. Try to match
10038    // it to BT.
10039    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10040      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10041      if (NewSetCC.getNode()) {
10042        CC = NewSetCC.getOperand(0);
10043        Cond = NewSetCC.getOperand(1);
10044        addTest = false;
10045      }
10046    }
10047  }
10048
10049  if (addTest) {
10050    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10051    Cond = EmitTest(Cond, X86::COND_NE, DAG);
10052  }
10053  Cond = ConvertCmpIfNecessary(Cond, DAG);
10054  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10055                     Chain, Dest, CC, Cond);
10056}
10057
10058// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10059// Calls to _alloca is needed to probe the stack when allocating more than 4k
10060// bytes in one go. Touching the stack at 4K increments is necessary to ensure
10061// that the guard pages used by the OS virtual memory manager are allocated in
10062// correct sequence.
10063SDValue
10064X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10065                                           SelectionDAG &DAG) const {
10066  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10067          getTargetMachine().Options.EnableSegmentedStacks) &&
10068         "This should be used only on Windows targets or when segmented stacks "
10069         "are being used");
10070  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10071  DebugLoc dl = Op.getDebugLoc();
10072
10073  // Get the inputs.
10074  SDValue Chain = Op.getOperand(0);
10075  SDValue Size  = Op.getOperand(1);
10076  // FIXME: Ensure alignment here
10077
10078  bool Is64Bit = Subtarget->is64Bit();
10079  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10080
10081  if (getTargetMachine().Options.EnableSegmentedStacks) {
10082    MachineFunction &MF = DAG.getMachineFunction();
10083    MachineRegisterInfo &MRI = MF.getRegInfo();
10084
10085    if (Is64Bit) {
10086      // The 64 bit implementation of segmented stacks needs to clobber both r10
10087      // r11. This makes it impossible to use it along with nested parameters.
10088      const Function *F = MF.getFunction();
10089
10090      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10091           I != E; ++I)
10092        if (I->hasNestAttr())
10093          report_fatal_error("Cannot use segmented stacks with functions that "
10094                             "have nested arguments.");
10095    }
10096
10097    const TargetRegisterClass *AddrRegClass =
10098      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10099    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10100    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10101    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10102                                DAG.getRegister(Vreg, SPTy));
10103    SDValue Ops1[2] = { Value, Chain };
10104    return DAG.getMergeValues(Ops1, 2, dl);
10105  } else {
10106    SDValue Flag;
10107    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10108
10109    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10110    Flag = Chain.getValue(1);
10111    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10112
10113    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10114    Flag = Chain.getValue(1);
10115
10116    Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10117                               SPTy).getValue(1);
10118
10119    SDValue Ops1[2] = { Chain.getValue(0), Chain };
10120    return DAG.getMergeValues(Ops1, 2, dl);
10121  }
10122}
10123
10124SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10125  MachineFunction &MF = DAG.getMachineFunction();
10126  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10127
10128  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10129  DebugLoc DL = Op.getDebugLoc();
10130
10131  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10132    // vastart just stores the address of the VarArgsFrameIndex slot into the
10133    // memory location argument.
10134    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10135                                   getPointerTy());
10136    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10137                        MachinePointerInfo(SV), false, false, 0);
10138  }
10139
10140  // __va_list_tag:
10141  //   gp_offset         (0 - 6 * 8)
10142  //   fp_offset         (48 - 48 + 8 * 16)
10143  //   overflow_arg_area (point to parameters coming in memory).
10144  //   reg_save_area
10145  SmallVector<SDValue, 8> MemOps;
10146  SDValue FIN = Op.getOperand(1);
10147  // Store gp_offset
10148  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10149                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10150                                               MVT::i32),
10151                               FIN, MachinePointerInfo(SV), false, false, 0);
10152  MemOps.push_back(Store);
10153
10154  // Store fp_offset
10155  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10156                    FIN, DAG.getIntPtrConstant(4));
10157  Store = DAG.getStore(Op.getOperand(0), DL,
10158                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10159                                       MVT::i32),
10160                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
10161  MemOps.push_back(Store);
10162
10163  // Store ptr to overflow_arg_area
10164  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10165                    FIN, DAG.getIntPtrConstant(4));
10166  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10167                                    getPointerTy());
10168  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10169                       MachinePointerInfo(SV, 8),
10170                       false, false, 0);
10171  MemOps.push_back(Store);
10172
10173  // Store ptr to reg_save_area.
10174  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10175                    FIN, DAG.getIntPtrConstant(8));
10176  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10177                                    getPointerTy());
10178  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10179                       MachinePointerInfo(SV, 16), false, false, 0);
10180  MemOps.push_back(Store);
10181  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10182                     &MemOps[0], MemOps.size());
10183}
10184
10185SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10186  assert(Subtarget->is64Bit() &&
10187         "LowerVAARG only handles 64-bit va_arg!");
10188  assert((Subtarget->isTargetLinux() ||
10189          Subtarget->isTargetDarwin()) &&
10190          "Unhandled target in LowerVAARG");
10191  assert(Op.getNode()->getNumOperands() == 4);
10192  SDValue Chain = Op.getOperand(0);
10193  SDValue SrcPtr = Op.getOperand(1);
10194  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10195  unsigned Align = Op.getConstantOperandVal(3);
10196  DebugLoc dl = Op.getDebugLoc();
10197
10198  EVT ArgVT = Op.getNode()->getValueType(0);
10199  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10200  uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10201  uint8_t ArgMode;
10202
10203  // Decide which area this value should be read from.
10204  // TODO: Implement the AMD64 ABI in its entirety. This simple
10205  // selection mechanism works only for the basic types.
10206  if (ArgVT == MVT::f80) {
10207    llvm_unreachable("va_arg for f80 not yet implemented");
10208  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10209    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10210  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10211    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10212  } else {
10213    llvm_unreachable("Unhandled argument type in LowerVAARG");
10214  }
10215
10216  if (ArgMode == 2) {
10217    // Sanity Check: Make sure using fp_offset makes sense.
10218    assert(!getTargetMachine().Options.UseSoftFloat &&
10219           !(DAG.getMachineFunction()
10220                .getFunction()->getAttributes()
10221                .hasAttribute(AttributeSet::FunctionIndex,
10222                              Attribute::NoImplicitFloat)) &&
10223           Subtarget->hasSSE1());
10224  }
10225
10226  // Insert VAARG_64 node into the DAG
10227  // VAARG_64 returns two values: Variable Argument Address, Chain
10228  SmallVector<SDValue, 11> InstOps;
10229  InstOps.push_back(Chain);
10230  InstOps.push_back(SrcPtr);
10231  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10232  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10233  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10234  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10235  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10236                                          VTs, &InstOps[0], InstOps.size(),
10237                                          MVT::i64,
10238                                          MachinePointerInfo(SV),
10239                                          /*Align=*/0,
10240                                          /*Volatile=*/false,
10241                                          /*ReadMem=*/true,
10242                                          /*WriteMem=*/true);
10243  Chain = VAARG.getValue(1);
10244
10245  // Load the next argument and return it
10246  return DAG.getLoad(ArgVT, dl,
10247                     Chain,
10248                     VAARG,
10249                     MachinePointerInfo(),
10250                     false, false, false, 0);
10251}
10252
10253static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10254                           SelectionDAG &DAG) {
10255  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10256  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10257  SDValue Chain = Op.getOperand(0);
10258  SDValue DstPtr = Op.getOperand(1);
10259  SDValue SrcPtr = Op.getOperand(2);
10260  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10261  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10262  DebugLoc DL = Op.getDebugLoc();
10263
10264  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10265                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10266                       false,
10267                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10268}
10269
10270// getTargetVShiftNode - Handle vector element shifts where the shift amount
10271// may or may not be a constant. Takes immediate version of shift as input.
10272static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10273                                   SDValue SrcOp, SDValue ShAmt,
10274                                   SelectionDAG &DAG) {
10275  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10276
10277  if (isa<ConstantSDNode>(ShAmt)) {
10278    // Constant may be a TargetConstant. Use a regular constant.
10279    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10280    switch (Opc) {
10281      default: llvm_unreachable("Unknown target vector shift node");
10282      case X86ISD::VSHLI:
10283      case X86ISD::VSRLI:
10284      case X86ISD::VSRAI:
10285        return DAG.getNode(Opc, dl, VT, SrcOp,
10286                           DAG.getConstant(ShiftAmt, MVT::i32));
10287    }
10288  }
10289
10290  // Change opcode to non-immediate version
10291  switch (Opc) {
10292    default: llvm_unreachable("Unknown target vector shift node");
10293    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10294    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10295    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10296  }
10297
10298  // Need to build a vector containing shift amount
10299  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10300  SDValue ShOps[4];
10301  ShOps[0] = ShAmt;
10302  ShOps[1] = DAG.getConstant(0, MVT::i32);
10303  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10304  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10305
10306  // The return type has to be a 128-bit type with the same element
10307  // type as the input type.
10308  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10309  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10310
10311  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10312  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10313}
10314
10315static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10316  DebugLoc dl = Op.getDebugLoc();
10317  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10318  switch (IntNo) {
10319  default: return SDValue();    // Don't custom lower most intrinsics.
10320  // Comparison intrinsics.
10321  case Intrinsic::x86_sse_comieq_ss:
10322  case Intrinsic::x86_sse_comilt_ss:
10323  case Intrinsic::x86_sse_comile_ss:
10324  case Intrinsic::x86_sse_comigt_ss:
10325  case Intrinsic::x86_sse_comige_ss:
10326  case Intrinsic::x86_sse_comineq_ss:
10327  case Intrinsic::x86_sse_ucomieq_ss:
10328  case Intrinsic::x86_sse_ucomilt_ss:
10329  case Intrinsic::x86_sse_ucomile_ss:
10330  case Intrinsic::x86_sse_ucomigt_ss:
10331  case Intrinsic::x86_sse_ucomige_ss:
10332  case Intrinsic::x86_sse_ucomineq_ss:
10333  case Intrinsic::x86_sse2_comieq_sd:
10334  case Intrinsic::x86_sse2_comilt_sd:
10335  case Intrinsic::x86_sse2_comile_sd:
10336  case Intrinsic::x86_sse2_comigt_sd:
10337  case Intrinsic::x86_sse2_comige_sd:
10338  case Intrinsic::x86_sse2_comineq_sd:
10339  case Intrinsic::x86_sse2_ucomieq_sd:
10340  case Intrinsic::x86_sse2_ucomilt_sd:
10341  case Intrinsic::x86_sse2_ucomile_sd:
10342  case Intrinsic::x86_sse2_ucomigt_sd:
10343  case Intrinsic::x86_sse2_ucomige_sd:
10344  case Intrinsic::x86_sse2_ucomineq_sd: {
10345    unsigned Opc;
10346    ISD::CondCode CC;
10347    switch (IntNo) {
10348    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10349    case Intrinsic::x86_sse_comieq_ss:
10350    case Intrinsic::x86_sse2_comieq_sd:
10351      Opc = X86ISD::COMI;
10352      CC = ISD::SETEQ;
10353      break;
10354    case Intrinsic::x86_sse_comilt_ss:
10355    case Intrinsic::x86_sse2_comilt_sd:
10356      Opc = X86ISD::COMI;
10357      CC = ISD::SETLT;
10358      break;
10359    case Intrinsic::x86_sse_comile_ss:
10360    case Intrinsic::x86_sse2_comile_sd:
10361      Opc = X86ISD::COMI;
10362      CC = ISD::SETLE;
10363      break;
10364    case Intrinsic::x86_sse_comigt_ss:
10365    case Intrinsic::x86_sse2_comigt_sd:
10366      Opc = X86ISD::COMI;
10367      CC = ISD::SETGT;
10368      break;
10369    case Intrinsic::x86_sse_comige_ss:
10370    case Intrinsic::x86_sse2_comige_sd:
10371      Opc = X86ISD::COMI;
10372      CC = ISD::SETGE;
10373      break;
10374    case Intrinsic::x86_sse_comineq_ss:
10375    case Intrinsic::x86_sse2_comineq_sd:
10376      Opc = X86ISD::COMI;
10377      CC = ISD::SETNE;
10378      break;
10379    case Intrinsic::x86_sse_ucomieq_ss:
10380    case Intrinsic::x86_sse2_ucomieq_sd:
10381      Opc = X86ISD::UCOMI;
10382      CC = ISD::SETEQ;
10383      break;
10384    case Intrinsic::x86_sse_ucomilt_ss:
10385    case Intrinsic::x86_sse2_ucomilt_sd:
10386      Opc = X86ISD::UCOMI;
10387      CC = ISD::SETLT;
10388      break;
10389    case Intrinsic::x86_sse_ucomile_ss:
10390    case Intrinsic::x86_sse2_ucomile_sd:
10391      Opc = X86ISD::UCOMI;
10392      CC = ISD::SETLE;
10393      break;
10394    case Intrinsic::x86_sse_ucomigt_ss:
10395    case Intrinsic::x86_sse2_ucomigt_sd:
10396      Opc = X86ISD::UCOMI;
10397      CC = ISD::SETGT;
10398      break;
10399    case Intrinsic::x86_sse_ucomige_ss:
10400    case Intrinsic::x86_sse2_ucomige_sd:
10401      Opc = X86ISD::UCOMI;
10402      CC = ISD::SETGE;
10403      break;
10404    case Intrinsic::x86_sse_ucomineq_ss:
10405    case Intrinsic::x86_sse2_ucomineq_sd:
10406      Opc = X86ISD::UCOMI;
10407      CC = ISD::SETNE;
10408      break;
10409    }
10410
10411    SDValue LHS = Op.getOperand(1);
10412    SDValue RHS = Op.getOperand(2);
10413    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10414    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10415    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10416    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10417                                DAG.getConstant(X86CC, MVT::i8), Cond);
10418    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10419  }
10420
10421  // Arithmetic intrinsics.
10422  case Intrinsic::x86_sse2_pmulu_dq:
10423  case Intrinsic::x86_avx2_pmulu_dq:
10424    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10425                       Op.getOperand(1), Op.getOperand(2));
10426
10427  // SSE2/AVX2 sub with unsigned saturation intrinsics
10428  case Intrinsic::x86_sse2_psubus_b:
10429  case Intrinsic::x86_sse2_psubus_w:
10430  case Intrinsic::x86_avx2_psubus_b:
10431  case Intrinsic::x86_avx2_psubus_w:
10432    return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10433                       Op.getOperand(1), Op.getOperand(2));
10434
10435  // SSE3/AVX horizontal add/sub intrinsics
10436  case Intrinsic::x86_sse3_hadd_ps:
10437  case Intrinsic::x86_sse3_hadd_pd:
10438  case Intrinsic::x86_avx_hadd_ps_256:
10439  case Intrinsic::x86_avx_hadd_pd_256:
10440  case Intrinsic::x86_sse3_hsub_ps:
10441  case Intrinsic::x86_sse3_hsub_pd:
10442  case Intrinsic::x86_avx_hsub_ps_256:
10443  case Intrinsic::x86_avx_hsub_pd_256:
10444  case Intrinsic::x86_ssse3_phadd_w_128:
10445  case Intrinsic::x86_ssse3_phadd_d_128:
10446  case Intrinsic::x86_avx2_phadd_w:
10447  case Intrinsic::x86_avx2_phadd_d:
10448  case Intrinsic::x86_ssse3_phsub_w_128:
10449  case Intrinsic::x86_ssse3_phsub_d_128:
10450  case Intrinsic::x86_avx2_phsub_w:
10451  case Intrinsic::x86_avx2_phsub_d: {
10452    unsigned Opcode;
10453    switch (IntNo) {
10454    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10455    case Intrinsic::x86_sse3_hadd_ps:
10456    case Intrinsic::x86_sse3_hadd_pd:
10457    case Intrinsic::x86_avx_hadd_ps_256:
10458    case Intrinsic::x86_avx_hadd_pd_256:
10459      Opcode = X86ISD::FHADD;
10460      break;
10461    case Intrinsic::x86_sse3_hsub_ps:
10462    case Intrinsic::x86_sse3_hsub_pd:
10463    case Intrinsic::x86_avx_hsub_ps_256:
10464    case Intrinsic::x86_avx_hsub_pd_256:
10465      Opcode = X86ISD::FHSUB;
10466      break;
10467    case Intrinsic::x86_ssse3_phadd_w_128:
10468    case Intrinsic::x86_ssse3_phadd_d_128:
10469    case Intrinsic::x86_avx2_phadd_w:
10470    case Intrinsic::x86_avx2_phadd_d:
10471      Opcode = X86ISD::HADD;
10472      break;
10473    case Intrinsic::x86_ssse3_phsub_w_128:
10474    case Intrinsic::x86_ssse3_phsub_d_128:
10475    case Intrinsic::x86_avx2_phsub_w:
10476    case Intrinsic::x86_avx2_phsub_d:
10477      Opcode = X86ISD::HSUB;
10478      break;
10479    }
10480    return DAG.getNode(Opcode, dl, Op.getValueType(),
10481                       Op.getOperand(1), Op.getOperand(2));
10482  }
10483
10484  // SSE2/SSE41/AVX2 integer max/min intrinsics.
10485  case Intrinsic::x86_sse2_pmaxu_b:
10486  case Intrinsic::x86_sse41_pmaxuw:
10487  case Intrinsic::x86_sse41_pmaxud:
10488  case Intrinsic::x86_avx2_pmaxu_b:
10489  case Intrinsic::x86_avx2_pmaxu_w:
10490  case Intrinsic::x86_avx2_pmaxu_d:
10491  case Intrinsic::x86_sse2_pminu_b:
10492  case Intrinsic::x86_sse41_pminuw:
10493  case Intrinsic::x86_sse41_pminud:
10494  case Intrinsic::x86_avx2_pminu_b:
10495  case Intrinsic::x86_avx2_pminu_w:
10496  case Intrinsic::x86_avx2_pminu_d:
10497  case Intrinsic::x86_sse41_pmaxsb:
10498  case Intrinsic::x86_sse2_pmaxs_w:
10499  case Intrinsic::x86_sse41_pmaxsd:
10500  case Intrinsic::x86_avx2_pmaxs_b:
10501  case Intrinsic::x86_avx2_pmaxs_w:
10502  case Intrinsic::x86_avx2_pmaxs_d:
10503  case Intrinsic::x86_sse41_pminsb:
10504  case Intrinsic::x86_sse2_pmins_w:
10505  case Intrinsic::x86_sse41_pminsd:
10506  case Intrinsic::x86_avx2_pmins_b:
10507  case Intrinsic::x86_avx2_pmins_w:
10508  case Intrinsic::x86_avx2_pmins_d: {
10509    unsigned Opcode;
10510    switch (IntNo) {
10511    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10512    case Intrinsic::x86_sse2_pmaxu_b:
10513    case Intrinsic::x86_sse41_pmaxuw:
10514    case Intrinsic::x86_sse41_pmaxud:
10515    case Intrinsic::x86_avx2_pmaxu_b:
10516    case Intrinsic::x86_avx2_pmaxu_w:
10517    case Intrinsic::x86_avx2_pmaxu_d:
10518      Opcode = X86ISD::UMAX;
10519      break;
10520    case Intrinsic::x86_sse2_pminu_b:
10521    case Intrinsic::x86_sse41_pminuw:
10522    case Intrinsic::x86_sse41_pminud:
10523    case Intrinsic::x86_avx2_pminu_b:
10524    case Intrinsic::x86_avx2_pminu_w:
10525    case Intrinsic::x86_avx2_pminu_d:
10526      Opcode = X86ISD::UMIN;
10527      break;
10528    case Intrinsic::x86_sse41_pmaxsb:
10529    case Intrinsic::x86_sse2_pmaxs_w:
10530    case Intrinsic::x86_sse41_pmaxsd:
10531    case Intrinsic::x86_avx2_pmaxs_b:
10532    case Intrinsic::x86_avx2_pmaxs_w:
10533    case Intrinsic::x86_avx2_pmaxs_d:
10534      Opcode = X86ISD::SMAX;
10535      break;
10536    case Intrinsic::x86_sse41_pminsb:
10537    case Intrinsic::x86_sse2_pmins_w:
10538    case Intrinsic::x86_sse41_pminsd:
10539    case Intrinsic::x86_avx2_pmins_b:
10540    case Intrinsic::x86_avx2_pmins_w:
10541    case Intrinsic::x86_avx2_pmins_d:
10542      Opcode = X86ISD::SMIN;
10543      break;
10544    }
10545    return DAG.getNode(Opcode, dl, Op.getValueType(),
10546                       Op.getOperand(1), Op.getOperand(2));
10547  }
10548
10549  // SSE/SSE2/AVX floating point max/min intrinsics.
10550  case Intrinsic::x86_sse_max_ps:
10551  case Intrinsic::x86_sse2_max_pd:
10552  case Intrinsic::x86_avx_max_ps_256:
10553  case Intrinsic::x86_avx_max_pd_256:
10554  case Intrinsic::x86_sse_min_ps:
10555  case Intrinsic::x86_sse2_min_pd:
10556  case Intrinsic::x86_avx_min_ps_256:
10557  case Intrinsic::x86_avx_min_pd_256: {
10558    unsigned Opcode;
10559    switch (IntNo) {
10560    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10561    case Intrinsic::x86_sse_max_ps:
10562    case Intrinsic::x86_sse2_max_pd:
10563    case Intrinsic::x86_avx_max_ps_256:
10564    case Intrinsic::x86_avx_max_pd_256:
10565      Opcode = X86ISD::FMAX;
10566      break;
10567    case Intrinsic::x86_sse_min_ps:
10568    case Intrinsic::x86_sse2_min_pd:
10569    case Intrinsic::x86_avx_min_ps_256:
10570    case Intrinsic::x86_avx_min_pd_256:
10571      Opcode = X86ISD::FMIN;
10572      break;
10573    }
10574    return DAG.getNode(Opcode, dl, Op.getValueType(),
10575                       Op.getOperand(1), Op.getOperand(2));
10576  }
10577
10578  // AVX2 variable shift intrinsics
10579  case Intrinsic::x86_avx2_psllv_d:
10580  case Intrinsic::x86_avx2_psllv_q:
10581  case Intrinsic::x86_avx2_psllv_d_256:
10582  case Intrinsic::x86_avx2_psllv_q_256:
10583  case Intrinsic::x86_avx2_psrlv_d:
10584  case Intrinsic::x86_avx2_psrlv_q:
10585  case Intrinsic::x86_avx2_psrlv_d_256:
10586  case Intrinsic::x86_avx2_psrlv_q_256:
10587  case Intrinsic::x86_avx2_psrav_d:
10588  case Intrinsic::x86_avx2_psrav_d_256: {
10589    unsigned Opcode;
10590    switch (IntNo) {
10591    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10592    case Intrinsic::x86_avx2_psllv_d:
10593    case Intrinsic::x86_avx2_psllv_q:
10594    case Intrinsic::x86_avx2_psllv_d_256:
10595    case Intrinsic::x86_avx2_psllv_q_256:
10596      Opcode = ISD::SHL;
10597      break;
10598    case Intrinsic::x86_avx2_psrlv_d:
10599    case Intrinsic::x86_avx2_psrlv_q:
10600    case Intrinsic::x86_avx2_psrlv_d_256:
10601    case Intrinsic::x86_avx2_psrlv_q_256:
10602      Opcode = ISD::SRL;
10603      break;
10604    case Intrinsic::x86_avx2_psrav_d:
10605    case Intrinsic::x86_avx2_psrav_d_256:
10606      Opcode = ISD::SRA;
10607      break;
10608    }
10609    return DAG.getNode(Opcode, dl, Op.getValueType(),
10610                       Op.getOperand(1), Op.getOperand(2));
10611  }
10612
10613  case Intrinsic::x86_ssse3_pshuf_b_128:
10614  case Intrinsic::x86_avx2_pshuf_b:
10615    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10616                       Op.getOperand(1), Op.getOperand(2));
10617
10618  case Intrinsic::x86_ssse3_psign_b_128:
10619  case Intrinsic::x86_ssse3_psign_w_128:
10620  case Intrinsic::x86_ssse3_psign_d_128:
10621  case Intrinsic::x86_avx2_psign_b:
10622  case Intrinsic::x86_avx2_psign_w:
10623  case Intrinsic::x86_avx2_psign_d:
10624    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10625                       Op.getOperand(1), Op.getOperand(2));
10626
10627  case Intrinsic::x86_sse41_insertps:
10628    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10629                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10630
10631  case Intrinsic::x86_avx_vperm2f128_ps_256:
10632  case Intrinsic::x86_avx_vperm2f128_pd_256:
10633  case Intrinsic::x86_avx_vperm2f128_si_256:
10634  case Intrinsic::x86_avx2_vperm2i128:
10635    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10636                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10637
10638  case Intrinsic::x86_avx2_permd:
10639  case Intrinsic::x86_avx2_permps:
10640    // Operands intentionally swapped. Mask is last operand to intrinsic,
10641    // but second operand for node/intruction.
10642    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10643                       Op.getOperand(2), Op.getOperand(1));
10644
10645  case Intrinsic::x86_sse_sqrt_ps:
10646  case Intrinsic::x86_sse2_sqrt_pd:
10647  case Intrinsic::x86_avx_sqrt_ps_256:
10648  case Intrinsic::x86_avx_sqrt_pd_256:
10649    return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10650
10651  // ptest and testp intrinsics. The intrinsic these come from are designed to
10652  // return an integer value, not just an instruction so lower it to the ptest
10653  // or testp pattern and a setcc for the result.
10654  case Intrinsic::x86_sse41_ptestz:
10655  case Intrinsic::x86_sse41_ptestc:
10656  case Intrinsic::x86_sse41_ptestnzc:
10657  case Intrinsic::x86_avx_ptestz_256:
10658  case Intrinsic::x86_avx_ptestc_256:
10659  case Intrinsic::x86_avx_ptestnzc_256:
10660  case Intrinsic::x86_avx_vtestz_ps:
10661  case Intrinsic::x86_avx_vtestc_ps:
10662  case Intrinsic::x86_avx_vtestnzc_ps:
10663  case Intrinsic::x86_avx_vtestz_pd:
10664  case Intrinsic::x86_avx_vtestc_pd:
10665  case Intrinsic::x86_avx_vtestnzc_pd:
10666  case Intrinsic::x86_avx_vtestz_ps_256:
10667  case Intrinsic::x86_avx_vtestc_ps_256:
10668  case Intrinsic::x86_avx_vtestnzc_ps_256:
10669  case Intrinsic::x86_avx_vtestz_pd_256:
10670  case Intrinsic::x86_avx_vtestc_pd_256:
10671  case Intrinsic::x86_avx_vtestnzc_pd_256: {
10672    bool IsTestPacked = false;
10673    unsigned X86CC;
10674    switch (IntNo) {
10675    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10676    case Intrinsic::x86_avx_vtestz_ps:
10677    case Intrinsic::x86_avx_vtestz_pd:
10678    case Intrinsic::x86_avx_vtestz_ps_256:
10679    case Intrinsic::x86_avx_vtestz_pd_256:
10680      IsTestPacked = true; // Fallthrough
10681    case Intrinsic::x86_sse41_ptestz:
10682    case Intrinsic::x86_avx_ptestz_256:
10683      // ZF = 1
10684      X86CC = X86::COND_E;
10685      break;
10686    case Intrinsic::x86_avx_vtestc_ps:
10687    case Intrinsic::x86_avx_vtestc_pd:
10688    case Intrinsic::x86_avx_vtestc_ps_256:
10689    case Intrinsic::x86_avx_vtestc_pd_256:
10690      IsTestPacked = true; // Fallthrough
10691    case Intrinsic::x86_sse41_ptestc:
10692    case Intrinsic::x86_avx_ptestc_256:
10693      // CF = 1
10694      X86CC = X86::COND_B;
10695      break;
10696    case Intrinsic::x86_avx_vtestnzc_ps:
10697    case Intrinsic::x86_avx_vtestnzc_pd:
10698    case Intrinsic::x86_avx_vtestnzc_ps_256:
10699    case Intrinsic::x86_avx_vtestnzc_pd_256:
10700      IsTestPacked = true; // Fallthrough
10701    case Intrinsic::x86_sse41_ptestnzc:
10702    case Intrinsic::x86_avx_ptestnzc_256:
10703      // ZF and CF = 0
10704      X86CC = X86::COND_A;
10705      break;
10706    }
10707
10708    SDValue LHS = Op.getOperand(1);
10709    SDValue RHS = Op.getOperand(2);
10710    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10711    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10712    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10713    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10714    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10715  }
10716
10717  // SSE/AVX shift intrinsics
10718  case Intrinsic::x86_sse2_psll_w:
10719  case Intrinsic::x86_sse2_psll_d:
10720  case Intrinsic::x86_sse2_psll_q:
10721  case Intrinsic::x86_avx2_psll_w:
10722  case Intrinsic::x86_avx2_psll_d:
10723  case Intrinsic::x86_avx2_psll_q:
10724  case Intrinsic::x86_sse2_psrl_w:
10725  case Intrinsic::x86_sse2_psrl_d:
10726  case Intrinsic::x86_sse2_psrl_q:
10727  case Intrinsic::x86_avx2_psrl_w:
10728  case Intrinsic::x86_avx2_psrl_d:
10729  case Intrinsic::x86_avx2_psrl_q:
10730  case Intrinsic::x86_sse2_psra_w:
10731  case Intrinsic::x86_sse2_psra_d:
10732  case Intrinsic::x86_avx2_psra_w:
10733  case Intrinsic::x86_avx2_psra_d: {
10734    unsigned Opcode;
10735    switch (IntNo) {
10736    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10737    case Intrinsic::x86_sse2_psll_w:
10738    case Intrinsic::x86_sse2_psll_d:
10739    case Intrinsic::x86_sse2_psll_q:
10740    case Intrinsic::x86_avx2_psll_w:
10741    case Intrinsic::x86_avx2_psll_d:
10742    case Intrinsic::x86_avx2_psll_q:
10743      Opcode = X86ISD::VSHL;
10744      break;
10745    case Intrinsic::x86_sse2_psrl_w:
10746    case Intrinsic::x86_sse2_psrl_d:
10747    case Intrinsic::x86_sse2_psrl_q:
10748    case Intrinsic::x86_avx2_psrl_w:
10749    case Intrinsic::x86_avx2_psrl_d:
10750    case Intrinsic::x86_avx2_psrl_q:
10751      Opcode = X86ISD::VSRL;
10752      break;
10753    case Intrinsic::x86_sse2_psra_w:
10754    case Intrinsic::x86_sse2_psra_d:
10755    case Intrinsic::x86_avx2_psra_w:
10756    case Intrinsic::x86_avx2_psra_d:
10757      Opcode = X86ISD::VSRA;
10758      break;
10759    }
10760    return DAG.getNode(Opcode, dl, Op.getValueType(),
10761                       Op.getOperand(1), Op.getOperand(2));
10762  }
10763
10764  // SSE/AVX immediate shift intrinsics
10765  case Intrinsic::x86_sse2_pslli_w:
10766  case Intrinsic::x86_sse2_pslli_d:
10767  case Intrinsic::x86_sse2_pslli_q:
10768  case Intrinsic::x86_avx2_pslli_w:
10769  case Intrinsic::x86_avx2_pslli_d:
10770  case Intrinsic::x86_avx2_pslli_q:
10771  case Intrinsic::x86_sse2_psrli_w:
10772  case Intrinsic::x86_sse2_psrli_d:
10773  case Intrinsic::x86_sse2_psrli_q:
10774  case Intrinsic::x86_avx2_psrli_w:
10775  case Intrinsic::x86_avx2_psrli_d:
10776  case Intrinsic::x86_avx2_psrli_q:
10777  case Intrinsic::x86_sse2_psrai_w:
10778  case Intrinsic::x86_sse2_psrai_d:
10779  case Intrinsic::x86_avx2_psrai_w:
10780  case Intrinsic::x86_avx2_psrai_d: {
10781    unsigned Opcode;
10782    switch (IntNo) {
10783    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10784    case Intrinsic::x86_sse2_pslli_w:
10785    case Intrinsic::x86_sse2_pslli_d:
10786    case Intrinsic::x86_sse2_pslli_q:
10787    case Intrinsic::x86_avx2_pslli_w:
10788    case Intrinsic::x86_avx2_pslli_d:
10789    case Intrinsic::x86_avx2_pslli_q:
10790      Opcode = X86ISD::VSHLI;
10791      break;
10792    case Intrinsic::x86_sse2_psrli_w:
10793    case Intrinsic::x86_sse2_psrli_d:
10794    case Intrinsic::x86_sse2_psrli_q:
10795    case Intrinsic::x86_avx2_psrli_w:
10796    case Intrinsic::x86_avx2_psrli_d:
10797    case Intrinsic::x86_avx2_psrli_q:
10798      Opcode = X86ISD::VSRLI;
10799      break;
10800    case Intrinsic::x86_sse2_psrai_w:
10801    case Intrinsic::x86_sse2_psrai_d:
10802    case Intrinsic::x86_avx2_psrai_w:
10803    case Intrinsic::x86_avx2_psrai_d:
10804      Opcode = X86ISD::VSRAI;
10805      break;
10806    }
10807    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10808                               Op.getOperand(1), Op.getOperand(2), DAG);
10809  }
10810
10811  case Intrinsic::x86_sse42_pcmpistria128:
10812  case Intrinsic::x86_sse42_pcmpestria128:
10813  case Intrinsic::x86_sse42_pcmpistric128:
10814  case Intrinsic::x86_sse42_pcmpestric128:
10815  case Intrinsic::x86_sse42_pcmpistrio128:
10816  case Intrinsic::x86_sse42_pcmpestrio128:
10817  case Intrinsic::x86_sse42_pcmpistris128:
10818  case Intrinsic::x86_sse42_pcmpestris128:
10819  case Intrinsic::x86_sse42_pcmpistriz128:
10820  case Intrinsic::x86_sse42_pcmpestriz128: {
10821    unsigned Opcode;
10822    unsigned X86CC;
10823    switch (IntNo) {
10824    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10825    case Intrinsic::x86_sse42_pcmpistria128:
10826      Opcode = X86ISD::PCMPISTRI;
10827      X86CC = X86::COND_A;
10828      break;
10829    case Intrinsic::x86_sse42_pcmpestria128:
10830      Opcode = X86ISD::PCMPESTRI;
10831      X86CC = X86::COND_A;
10832      break;
10833    case Intrinsic::x86_sse42_pcmpistric128:
10834      Opcode = X86ISD::PCMPISTRI;
10835      X86CC = X86::COND_B;
10836      break;
10837    case Intrinsic::x86_sse42_pcmpestric128:
10838      Opcode = X86ISD::PCMPESTRI;
10839      X86CC = X86::COND_B;
10840      break;
10841    case Intrinsic::x86_sse42_pcmpistrio128:
10842      Opcode = X86ISD::PCMPISTRI;
10843      X86CC = X86::COND_O;
10844      break;
10845    case Intrinsic::x86_sse42_pcmpestrio128:
10846      Opcode = X86ISD::PCMPESTRI;
10847      X86CC = X86::COND_O;
10848      break;
10849    case Intrinsic::x86_sse42_pcmpistris128:
10850      Opcode = X86ISD::PCMPISTRI;
10851      X86CC = X86::COND_S;
10852      break;
10853    case Intrinsic::x86_sse42_pcmpestris128:
10854      Opcode = X86ISD::PCMPESTRI;
10855      X86CC = X86::COND_S;
10856      break;
10857    case Intrinsic::x86_sse42_pcmpistriz128:
10858      Opcode = X86ISD::PCMPISTRI;
10859      X86CC = X86::COND_E;
10860      break;
10861    case Intrinsic::x86_sse42_pcmpestriz128:
10862      Opcode = X86ISD::PCMPESTRI;
10863      X86CC = X86::COND_E;
10864      break;
10865    }
10866    SmallVector<SDValue, 5> NewOps;
10867    NewOps.append(Op->op_begin()+1, Op->op_end());
10868    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10869    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10870    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10871                                DAG.getConstant(X86CC, MVT::i8),
10872                                SDValue(PCMP.getNode(), 1));
10873    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10874  }
10875
10876  case Intrinsic::x86_sse42_pcmpistri128:
10877  case Intrinsic::x86_sse42_pcmpestri128: {
10878    unsigned Opcode;
10879    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10880      Opcode = X86ISD::PCMPISTRI;
10881    else
10882      Opcode = X86ISD::PCMPESTRI;
10883
10884    SmallVector<SDValue, 5> NewOps;
10885    NewOps.append(Op->op_begin()+1, Op->op_end());
10886    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10887    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10888  }
10889  case Intrinsic::x86_fma_vfmadd_ps:
10890  case Intrinsic::x86_fma_vfmadd_pd:
10891  case Intrinsic::x86_fma_vfmsub_ps:
10892  case Intrinsic::x86_fma_vfmsub_pd:
10893  case Intrinsic::x86_fma_vfnmadd_ps:
10894  case Intrinsic::x86_fma_vfnmadd_pd:
10895  case Intrinsic::x86_fma_vfnmsub_ps:
10896  case Intrinsic::x86_fma_vfnmsub_pd:
10897  case Intrinsic::x86_fma_vfmaddsub_ps:
10898  case Intrinsic::x86_fma_vfmaddsub_pd:
10899  case Intrinsic::x86_fma_vfmsubadd_ps:
10900  case Intrinsic::x86_fma_vfmsubadd_pd:
10901  case Intrinsic::x86_fma_vfmadd_ps_256:
10902  case Intrinsic::x86_fma_vfmadd_pd_256:
10903  case Intrinsic::x86_fma_vfmsub_ps_256:
10904  case Intrinsic::x86_fma_vfmsub_pd_256:
10905  case Intrinsic::x86_fma_vfnmadd_ps_256:
10906  case Intrinsic::x86_fma_vfnmadd_pd_256:
10907  case Intrinsic::x86_fma_vfnmsub_ps_256:
10908  case Intrinsic::x86_fma_vfnmsub_pd_256:
10909  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10910  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10911  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10912  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10913    unsigned Opc;
10914    switch (IntNo) {
10915    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10916    case Intrinsic::x86_fma_vfmadd_ps:
10917    case Intrinsic::x86_fma_vfmadd_pd:
10918    case Intrinsic::x86_fma_vfmadd_ps_256:
10919    case Intrinsic::x86_fma_vfmadd_pd_256:
10920      Opc = X86ISD::FMADD;
10921      break;
10922    case Intrinsic::x86_fma_vfmsub_ps:
10923    case Intrinsic::x86_fma_vfmsub_pd:
10924    case Intrinsic::x86_fma_vfmsub_ps_256:
10925    case Intrinsic::x86_fma_vfmsub_pd_256:
10926      Opc = X86ISD::FMSUB;
10927      break;
10928    case Intrinsic::x86_fma_vfnmadd_ps:
10929    case Intrinsic::x86_fma_vfnmadd_pd:
10930    case Intrinsic::x86_fma_vfnmadd_ps_256:
10931    case Intrinsic::x86_fma_vfnmadd_pd_256:
10932      Opc = X86ISD::FNMADD;
10933      break;
10934    case Intrinsic::x86_fma_vfnmsub_ps:
10935    case Intrinsic::x86_fma_vfnmsub_pd:
10936    case Intrinsic::x86_fma_vfnmsub_ps_256:
10937    case Intrinsic::x86_fma_vfnmsub_pd_256:
10938      Opc = X86ISD::FNMSUB;
10939      break;
10940    case Intrinsic::x86_fma_vfmaddsub_ps:
10941    case Intrinsic::x86_fma_vfmaddsub_pd:
10942    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10943    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10944      Opc = X86ISD::FMADDSUB;
10945      break;
10946    case Intrinsic::x86_fma_vfmsubadd_ps:
10947    case Intrinsic::x86_fma_vfmsubadd_pd:
10948    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10949    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10950      Opc = X86ISD::FMSUBADD;
10951      break;
10952    }
10953
10954    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10955                       Op.getOperand(2), Op.getOperand(3));
10956  }
10957  }
10958}
10959
10960static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10961  DebugLoc dl = Op.getDebugLoc();
10962  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10963  switch (IntNo) {
10964  default: return SDValue();    // Don't custom lower most intrinsics.
10965
10966  // RDRAND/RDSEED intrinsics.
10967  case Intrinsic::x86_rdrand_16:
10968  case Intrinsic::x86_rdrand_32:
10969  case Intrinsic::x86_rdrand_64:
10970  case Intrinsic::x86_rdseed_16:
10971  case Intrinsic::x86_rdseed_32:
10972  case Intrinsic::x86_rdseed_64: {
10973    unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10974                       IntNo == Intrinsic::x86_rdseed_32 ||
10975                       IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10976                                                            X86ISD::RDRAND;
10977    // Emit the node with the right value type.
10978    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10979    SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10980
10981    // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10982    // Otherwise return the value from Rand, which is always 0, casted to i32.
10983    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10984                      DAG.getConstant(1, Op->getValueType(1)),
10985                      DAG.getConstant(X86::COND_B, MVT::i32),
10986                      SDValue(Result.getNode(), 1) };
10987    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10988                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10989                                  Ops, array_lengthof(Ops));
10990
10991    // Return { result, isValid, chain }.
10992    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10993                       SDValue(Result.getNode(), 2));
10994  }
10995
10996  // XTEST intrinsics.
10997  case Intrinsic::x86_xtest: {
10998    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10999    SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11000    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11001                                DAG.getConstant(X86::COND_NE, MVT::i8),
11002                                InTrans);
11003    SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11004    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11005                       Ret, SDValue(InTrans.getNode(), 1));
11006  }
11007  }
11008}
11009
11010SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11011                                           SelectionDAG &DAG) const {
11012  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11013  MFI->setReturnAddressIsTaken(true);
11014
11015  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11016  DebugLoc dl = Op.getDebugLoc();
11017  EVT PtrVT = getPointerTy();
11018
11019  if (Depth > 0) {
11020    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11021    SDValue Offset =
11022      DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11023    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11024                       DAG.getNode(ISD::ADD, dl, PtrVT,
11025                                   FrameAddr, Offset),
11026                       MachinePointerInfo(), false, false, false, 0);
11027  }
11028
11029  // Just load the return address.
11030  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11031  return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11032                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11033}
11034
11035SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11036  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11037  MFI->setFrameAddressIsTaken(true);
11038
11039  EVT VT = Op.getValueType();
11040  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11041  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11042  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
11043  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11044  while (Depth--)
11045    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11046                            MachinePointerInfo(),
11047                            false, false, false, 0);
11048  return FrameAddr;
11049}
11050
11051SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11052                                                     SelectionDAG &DAG) const {
11053  return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11054}
11055
11056SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11057  SDValue Chain     = Op.getOperand(0);
11058  SDValue Offset    = Op.getOperand(1);
11059  SDValue Handler   = Op.getOperand(2);
11060  DebugLoc dl       = Op.getDebugLoc();
11061
11062  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
11063                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
11064                                     getPointerTy());
11065  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
11066
11067  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11068                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11069  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11070  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11071                       false, false, 0);
11072  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11073
11074  return DAG.getNode(X86ISD::EH_RETURN, dl,
11075                     MVT::Other,
11076                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11077}
11078
11079SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11080                                               SelectionDAG &DAG) const {
11081  DebugLoc DL = Op.getDebugLoc();
11082  return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11083                     DAG.getVTList(MVT::i32, MVT::Other),
11084                     Op.getOperand(0), Op.getOperand(1));
11085}
11086
11087SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11088                                                SelectionDAG &DAG) const {
11089  DebugLoc DL = Op.getDebugLoc();
11090  return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11091                     Op.getOperand(0), Op.getOperand(1));
11092}
11093
11094static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11095  return Op.getOperand(0);
11096}
11097
11098SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11099                                                SelectionDAG &DAG) const {
11100  SDValue Root = Op.getOperand(0);
11101  SDValue Trmp = Op.getOperand(1); // trampoline
11102  SDValue FPtr = Op.getOperand(2); // nested function
11103  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11104  DebugLoc dl  = Op.getDebugLoc();
11105
11106  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11107  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11108
11109  if (Subtarget->is64Bit()) {
11110    SDValue OutChains[6];
11111
11112    // Large code-model.
11113    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11114    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11115
11116    const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11117    const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11118
11119    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11120
11121    // Load the pointer to the nested function into R11.
11122    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11123    SDValue Addr = Trmp;
11124    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11125                                Addr, MachinePointerInfo(TrmpAddr),
11126                                false, false, 0);
11127
11128    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11129                       DAG.getConstant(2, MVT::i64));
11130    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11131                                MachinePointerInfo(TrmpAddr, 2),
11132                                false, false, 2);
11133
11134    // Load the 'nest' parameter value into R10.
11135    // R10 is specified in X86CallingConv.td
11136    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11137    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11138                       DAG.getConstant(10, MVT::i64));
11139    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11140                                Addr, MachinePointerInfo(TrmpAddr, 10),
11141                                false, false, 0);
11142
11143    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11144                       DAG.getConstant(12, MVT::i64));
11145    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11146                                MachinePointerInfo(TrmpAddr, 12),
11147                                false, false, 2);
11148
11149    // Jump to the nested function.
11150    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11151    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11152                       DAG.getConstant(20, MVT::i64));
11153    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11154                                Addr, MachinePointerInfo(TrmpAddr, 20),
11155                                false, false, 0);
11156
11157    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11158    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11159                       DAG.getConstant(22, MVT::i64));
11160    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11161                                MachinePointerInfo(TrmpAddr, 22),
11162                                false, false, 0);
11163
11164    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11165  } else {
11166    const Function *Func =
11167      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11168    CallingConv::ID CC = Func->getCallingConv();
11169    unsigned NestReg;
11170
11171    switch (CC) {
11172    default:
11173      llvm_unreachable("Unsupported calling convention");
11174    case CallingConv::C:
11175    case CallingConv::X86_StdCall: {
11176      // Pass 'nest' parameter in ECX.
11177      // Must be kept in sync with X86CallingConv.td
11178      NestReg = X86::ECX;
11179
11180      // Check that ECX wasn't needed by an 'inreg' parameter.
11181      FunctionType *FTy = Func->getFunctionType();
11182      const AttributeSet &Attrs = Func->getAttributes();
11183
11184      if (!Attrs.isEmpty() && !Func->isVarArg()) {
11185        unsigned InRegCount = 0;
11186        unsigned Idx = 1;
11187
11188        for (FunctionType::param_iterator I = FTy->param_begin(),
11189             E = FTy->param_end(); I != E; ++I, ++Idx)
11190          if (Attrs.hasAttribute(Idx, Attribute::InReg))
11191            // FIXME: should only count parameters that are lowered to integers.
11192            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11193
11194        if (InRegCount > 2) {
11195          report_fatal_error("Nest register in use - reduce number of inreg"
11196                             " parameters!");
11197        }
11198      }
11199      break;
11200    }
11201    case CallingConv::X86_FastCall:
11202    case CallingConv::X86_ThisCall:
11203    case CallingConv::Fast:
11204      // Pass 'nest' parameter in EAX.
11205      // Must be kept in sync with X86CallingConv.td
11206      NestReg = X86::EAX;
11207      break;
11208    }
11209
11210    SDValue OutChains[4];
11211    SDValue Addr, Disp;
11212
11213    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11214                       DAG.getConstant(10, MVT::i32));
11215    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11216
11217    // This is storing the opcode for MOV32ri.
11218    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11219    const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11220    OutChains[0] = DAG.getStore(Root, dl,
11221                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11222                                Trmp, MachinePointerInfo(TrmpAddr),
11223                                false, false, 0);
11224
11225    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11226                       DAG.getConstant(1, MVT::i32));
11227    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11228                                MachinePointerInfo(TrmpAddr, 1),
11229                                false, false, 1);
11230
11231    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11232    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11233                       DAG.getConstant(5, MVT::i32));
11234    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11235                                MachinePointerInfo(TrmpAddr, 5),
11236                                false, false, 1);
11237
11238    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11239                       DAG.getConstant(6, MVT::i32));
11240    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11241                                MachinePointerInfo(TrmpAddr, 6),
11242                                false, false, 1);
11243
11244    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11245  }
11246}
11247
11248SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11249                                            SelectionDAG &DAG) const {
11250  /*
11251   The rounding mode is in bits 11:10 of FPSR, and has the following
11252   settings:
11253     00 Round to nearest
11254     01 Round to -inf
11255     10 Round to +inf
11256     11 Round to 0
11257
11258  FLT_ROUNDS, on the other hand, expects the following:
11259    -1 Undefined
11260     0 Round to 0
11261     1 Round to nearest
11262     2 Round to +inf
11263     3 Round to -inf
11264
11265  To perform the conversion, we do:
11266    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11267  */
11268
11269  MachineFunction &MF = DAG.getMachineFunction();
11270  const TargetMachine &TM = MF.getTarget();
11271  const TargetFrameLowering &TFI = *TM.getFrameLowering();
11272  unsigned StackAlignment = TFI.getStackAlignment();
11273  EVT VT = Op.getValueType();
11274  DebugLoc DL = Op.getDebugLoc();
11275
11276  // Save FP Control Word to stack slot
11277  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11278  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11279
11280  MachineMemOperand *MMO =
11281   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11282                           MachineMemOperand::MOStore, 2, 2);
11283
11284  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11285  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11286                                          DAG.getVTList(MVT::Other),
11287                                          Ops, array_lengthof(Ops), MVT::i16,
11288                                          MMO);
11289
11290  // Load FP Control Word from stack slot
11291  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11292                            MachinePointerInfo(), false, false, false, 0);
11293
11294  // Transform as necessary
11295  SDValue CWD1 =
11296    DAG.getNode(ISD::SRL, DL, MVT::i16,
11297                DAG.getNode(ISD::AND, DL, MVT::i16,
11298                            CWD, DAG.getConstant(0x800, MVT::i16)),
11299                DAG.getConstant(11, MVT::i8));
11300  SDValue CWD2 =
11301    DAG.getNode(ISD::SRL, DL, MVT::i16,
11302                DAG.getNode(ISD::AND, DL, MVT::i16,
11303                            CWD, DAG.getConstant(0x400, MVT::i16)),
11304                DAG.getConstant(9, MVT::i8));
11305
11306  SDValue RetVal =
11307    DAG.getNode(ISD::AND, DL, MVT::i16,
11308                DAG.getNode(ISD::ADD, DL, MVT::i16,
11309                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11310                            DAG.getConstant(1, MVT::i16)),
11311                DAG.getConstant(3, MVT::i16));
11312
11313  return DAG.getNode((VT.getSizeInBits() < 16 ?
11314                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11315}
11316
11317static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11318  EVT VT = Op.getValueType();
11319  EVT OpVT = VT;
11320  unsigned NumBits = VT.getSizeInBits();
11321  DebugLoc dl = Op.getDebugLoc();
11322
11323  Op = Op.getOperand(0);
11324  if (VT == MVT::i8) {
11325    // Zero extend to i32 since there is not an i8 bsr.
11326    OpVT = MVT::i32;
11327    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11328  }
11329
11330  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11331  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11332  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11333
11334  // If src is zero (i.e. bsr sets ZF), returns NumBits.
11335  SDValue Ops[] = {
11336    Op,
11337    DAG.getConstant(NumBits+NumBits-1, OpVT),
11338    DAG.getConstant(X86::COND_E, MVT::i8),
11339    Op.getValue(1)
11340  };
11341  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11342
11343  // Finally xor with NumBits-1.
11344  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11345
11346  if (VT == MVT::i8)
11347    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11348  return Op;
11349}
11350
11351static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11352  EVT VT = Op.getValueType();
11353  EVT OpVT = VT;
11354  unsigned NumBits = VT.getSizeInBits();
11355  DebugLoc dl = Op.getDebugLoc();
11356
11357  Op = Op.getOperand(0);
11358  if (VT == MVT::i8) {
11359    // Zero extend to i32 since there is not an i8 bsr.
11360    OpVT = MVT::i32;
11361    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11362  }
11363
11364  // Issue a bsr (scan bits in reverse).
11365  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11366  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11367
11368  // And xor with NumBits-1.
11369  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11370
11371  if (VT == MVT::i8)
11372    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11373  return Op;
11374}
11375
11376static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11377  EVT VT = Op.getValueType();
11378  unsigned NumBits = VT.getSizeInBits();
11379  DebugLoc dl = Op.getDebugLoc();
11380  Op = Op.getOperand(0);
11381
11382  // Issue a bsf (scan bits forward) which also sets EFLAGS.
11383  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11384  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11385
11386  // If src is zero (i.e. bsf sets ZF), returns NumBits.
11387  SDValue Ops[] = {
11388    Op,
11389    DAG.getConstant(NumBits, VT),
11390    DAG.getConstant(X86::COND_E, MVT::i8),
11391    Op.getValue(1)
11392  };
11393  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11394}
11395
11396// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11397// ones, and then concatenate the result back.
11398static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11399  EVT VT = Op.getValueType();
11400
11401  assert(VT.is256BitVector() && VT.isInteger() &&
11402         "Unsupported value type for operation");
11403
11404  unsigned NumElems = VT.getVectorNumElements();
11405  DebugLoc dl = Op.getDebugLoc();
11406
11407  // Extract the LHS vectors
11408  SDValue LHS = Op.getOperand(0);
11409  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11410  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11411
11412  // Extract the RHS vectors
11413  SDValue RHS = Op.getOperand(1);
11414  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11415  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11416
11417  MVT EltVT = VT.getVectorElementType().getSimpleVT();
11418  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11419
11420  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11421                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11422                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11423}
11424
11425static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11426  assert(Op.getValueType().is256BitVector() &&
11427         Op.getValueType().isInteger() &&
11428         "Only handle AVX 256-bit vector integer operation");
11429  return Lower256IntArith(Op, DAG);
11430}
11431
11432static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11433  assert(Op.getValueType().is256BitVector() &&
11434         Op.getValueType().isInteger() &&
11435         "Only handle AVX 256-bit vector integer operation");
11436  return Lower256IntArith(Op, DAG);
11437}
11438
11439static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11440                        SelectionDAG &DAG) {
11441  DebugLoc dl = Op.getDebugLoc();
11442  EVT VT = Op.getValueType();
11443
11444  // Decompose 256-bit ops into smaller 128-bit ops.
11445  if (VT.is256BitVector() && !Subtarget->hasInt256())
11446    return Lower256IntArith(Op, DAG);
11447
11448  SDValue A = Op.getOperand(0);
11449  SDValue B = Op.getOperand(1);
11450
11451  // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11452  if (VT == MVT::v4i32) {
11453    assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11454           "Should not custom lower when pmuldq is available!");
11455
11456    // Extract the odd parts.
11457    const int UnpackMask[] = { 1, -1, 3, -1 };
11458    SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11459    SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11460
11461    // Multiply the even parts.
11462    SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11463    // Now multiply odd parts.
11464    SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11465
11466    Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11467    Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11468
11469    // Merge the two vectors back together with a shuffle. This expands into 2
11470    // shuffles.
11471    const int ShufMask[] = { 0, 4, 2, 6 };
11472    return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11473  }
11474
11475  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11476         "Only know how to lower V2I64/V4I64 multiply");
11477
11478  //  Ahi = psrlqi(a, 32);
11479  //  Bhi = psrlqi(b, 32);
11480  //
11481  //  AloBlo = pmuludq(a, b);
11482  //  AloBhi = pmuludq(a, Bhi);
11483  //  AhiBlo = pmuludq(Ahi, b);
11484
11485  //  AloBhi = psllqi(AloBhi, 32);
11486  //  AhiBlo = psllqi(AhiBlo, 32);
11487  //  return AloBlo + AloBhi + AhiBlo;
11488
11489  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11490
11491  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11492  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11493
11494  // Bit cast to 32-bit vectors for MULUDQ
11495  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11496  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11497  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11498  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11499  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11500
11501  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11502  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11503  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11504
11505  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11506  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11507
11508  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11509  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11510}
11511
11512SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11513  EVT VT = Op.getValueType();
11514  EVT EltTy = VT.getVectorElementType();
11515  unsigned NumElts = VT.getVectorNumElements();
11516  SDValue N0 = Op.getOperand(0);
11517  DebugLoc dl = Op.getDebugLoc();
11518
11519  // Lower sdiv X, pow2-const.
11520  BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11521  if (!C)
11522    return SDValue();
11523
11524  APInt SplatValue, SplatUndef;
11525  unsigned MinSplatBits;
11526  bool HasAnyUndefs;
11527  if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11528    return SDValue();
11529
11530  if ((SplatValue != 0) &&
11531      (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11532    unsigned lg2 = SplatValue.countTrailingZeros();
11533    // Splat the sign bit.
11534    SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11535    SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11536    // Add (N0 < 0) ? abs2 - 1 : 0;
11537    SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11538    SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11539    SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11540    SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11541    SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11542
11543    // If we're dividing by a positive value, we're done.  Otherwise, we must
11544    // negate the result.
11545    if (SplatValue.isNonNegative())
11546      return SRA;
11547
11548    SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11549    SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11550    return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11551  }
11552  return SDValue();
11553}
11554
11555static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11556                                         const X86Subtarget *Subtarget) {
11557  EVT VT = Op.getValueType();
11558  DebugLoc dl = Op.getDebugLoc();
11559  SDValue R = Op.getOperand(0);
11560  SDValue Amt = Op.getOperand(1);
11561
11562  // Optimize shl/srl/sra with constant shift amount.
11563  if (isSplatVector(Amt.getNode())) {
11564    SDValue SclrAmt = Amt->getOperand(0);
11565    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11566      uint64_t ShiftAmt = C->getZExtValue();
11567
11568      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11569          (Subtarget->hasInt256() &&
11570           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11571        if (Op.getOpcode() == ISD::SHL)
11572          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11573                             DAG.getConstant(ShiftAmt, MVT::i32));
11574        if (Op.getOpcode() == ISD::SRL)
11575          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11576                             DAG.getConstant(ShiftAmt, MVT::i32));
11577        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11578          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11579                             DAG.getConstant(ShiftAmt, MVT::i32));
11580      }
11581
11582      if (VT == MVT::v16i8) {
11583        if (Op.getOpcode() == ISD::SHL) {
11584          // Make a large shift.
11585          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11586                                    DAG.getConstant(ShiftAmt, MVT::i32));
11587          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11588          // Zero out the rightmost bits.
11589          SmallVector<SDValue, 16> V(16,
11590                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11591                                                     MVT::i8));
11592          return DAG.getNode(ISD::AND, dl, VT, SHL,
11593                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11594        }
11595        if (Op.getOpcode() == ISD::SRL) {
11596          // Make a large shift.
11597          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11598                                    DAG.getConstant(ShiftAmt, MVT::i32));
11599          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11600          // Zero out the leftmost bits.
11601          SmallVector<SDValue, 16> V(16,
11602                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11603                                                     MVT::i8));
11604          return DAG.getNode(ISD::AND, dl, VT, SRL,
11605                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11606        }
11607        if (Op.getOpcode() == ISD::SRA) {
11608          if (ShiftAmt == 7) {
11609            // R s>> 7  ===  R s< 0
11610            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11611            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11612          }
11613
11614          // R s>> a === ((R u>> a) ^ m) - m
11615          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11616          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11617                                                         MVT::i8));
11618          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11619          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11620          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11621          return Res;
11622        }
11623        llvm_unreachable("Unknown shift opcode.");
11624      }
11625
11626      if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11627        if (Op.getOpcode() == ISD::SHL) {
11628          // Make a large shift.
11629          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11630                                    DAG.getConstant(ShiftAmt, MVT::i32));
11631          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11632          // Zero out the rightmost bits.
11633          SmallVector<SDValue, 32> V(32,
11634                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11635                                                     MVT::i8));
11636          return DAG.getNode(ISD::AND, dl, VT, SHL,
11637                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11638        }
11639        if (Op.getOpcode() == ISD::SRL) {
11640          // Make a large shift.
11641          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11642                                    DAG.getConstant(ShiftAmt, MVT::i32));
11643          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11644          // Zero out the leftmost bits.
11645          SmallVector<SDValue, 32> V(32,
11646                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11647                                                     MVT::i8));
11648          return DAG.getNode(ISD::AND, dl, VT, SRL,
11649                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11650        }
11651        if (Op.getOpcode() == ISD::SRA) {
11652          if (ShiftAmt == 7) {
11653            // R s>> 7  ===  R s< 0
11654            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11655            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11656          }
11657
11658          // R s>> a === ((R u>> a) ^ m) - m
11659          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11660          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11661                                                         MVT::i8));
11662          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11663          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11664          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11665          return Res;
11666        }
11667        llvm_unreachable("Unknown shift opcode.");
11668      }
11669    }
11670  }
11671
11672  // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11673  if (!Subtarget->is64Bit() &&
11674      (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11675      Amt.getOpcode() == ISD::BITCAST &&
11676      Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11677    Amt = Amt.getOperand(0);
11678    unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11679                     VT.getVectorNumElements();
11680    unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11681    uint64_t ShiftAmt = 0;
11682    for (unsigned i = 0; i != Ratio; ++i) {
11683      ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11684      if (C == 0)
11685        return SDValue();
11686      // 6 == Log2(64)
11687      ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11688    }
11689    // Check remaining shift amounts.
11690    for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11691      uint64_t ShAmt = 0;
11692      for (unsigned j = 0; j != Ratio; ++j) {
11693        ConstantSDNode *C =
11694          dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11695        if (C == 0)
11696          return SDValue();
11697        // 6 == Log2(64)
11698        ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11699      }
11700      if (ShAmt != ShiftAmt)
11701        return SDValue();
11702    }
11703    switch (Op.getOpcode()) {
11704    default:
11705      llvm_unreachable("Unknown shift opcode!");
11706    case ISD::SHL:
11707      return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11708                         DAG.getConstant(ShiftAmt, MVT::i32));
11709    case ISD::SRL:
11710      return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11711                         DAG.getConstant(ShiftAmt, MVT::i32));
11712    case ISD::SRA:
11713      return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11714                         DAG.getConstant(ShiftAmt, MVT::i32));
11715    }
11716  }
11717
11718  return SDValue();
11719}
11720
11721static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11722                                        const X86Subtarget* Subtarget) {
11723  EVT VT = Op.getValueType();
11724  DebugLoc dl = Op.getDebugLoc();
11725  SDValue R = Op.getOperand(0);
11726  SDValue Amt = Op.getOperand(1);
11727
11728  if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11729      VT == MVT::v4i32 || VT == MVT::v8i16 ||
11730      (Subtarget->hasInt256() &&
11731       ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11732        VT == MVT::v8i32 || VT == MVT::v16i16))) {
11733    SDValue BaseShAmt;
11734    EVT EltVT = VT.getVectorElementType();
11735
11736    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11737      unsigned NumElts = VT.getVectorNumElements();
11738      unsigned i, j;
11739      for (i = 0; i != NumElts; ++i) {
11740        if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11741          continue;
11742        break;
11743      }
11744      for (j = i; j != NumElts; ++j) {
11745        SDValue Arg = Amt.getOperand(j);
11746        if (Arg.getOpcode() == ISD::UNDEF) continue;
11747        if (Arg != Amt.getOperand(i))
11748          break;
11749      }
11750      if (i != NumElts && j == NumElts)
11751        BaseShAmt = Amt.getOperand(i);
11752    } else {
11753      if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11754        Amt = Amt.getOperand(0);
11755      if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11756               cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11757        SDValue InVec = Amt.getOperand(0);
11758        if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11759          unsigned NumElts = InVec.getValueType().getVectorNumElements();
11760          unsigned i = 0;
11761          for (; i != NumElts; ++i) {
11762            SDValue Arg = InVec.getOperand(i);
11763            if (Arg.getOpcode() == ISD::UNDEF) continue;
11764            BaseShAmt = Arg;
11765            break;
11766          }
11767        } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11768           if (ConstantSDNode *C =
11769               dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11770             unsigned SplatIdx =
11771               cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11772             if (C->getZExtValue() == SplatIdx)
11773               BaseShAmt = InVec.getOperand(1);
11774           }
11775        }
11776        if (BaseShAmt.getNode() == 0)
11777          BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11778                                  DAG.getIntPtrConstant(0));
11779      }
11780    }
11781
11782    if (BaseShAmt.getNode()) {
11783      if (EltVT.bitsGT(MVT::i32))
11784        BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11785      else if (EltVT.bitsLT(MVT::i32))
11786        BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11787
11788      switch (Op.getOpcode()) {
11789      default:
11790        llvm_unreachable("Unknown shift opcode!");
11791      case ISD::SHL:
11792        switch (VT.getSimpleVT().SimpleTy) {
11793        default: return SDValue();
11794        case MVT::v2i64:
11795        case MVT::v4i32:
11796        case MVT::v8i16:
11797        case MVT::v4i64:
11798        case MVT::v8i32:
11799        case MVT::v16i16:
11800          return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11801        }
11802      case ISD::SRA:
11803        switch (VT.getSimpleVT().SimpleTy) {
11804        default: return SDValue();
11805        case MVT::v4i32:
11806        case MVT::v8i16:
11807        case MVT::v8i32:
11808        case MVT::v16i16:
11809          return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11810        }
11811      case ISD::SRL:
11812        switch (VT.getSimpleVT().SimpleTy) {
11813        default: return SDValue();
11814        case MVT::v2i64:
11815        case MVT::v4i32:
11816        case MVT::v8i16:
11817        case MVT::v4i64:
11818        case MVT::v8i32:
11819        case MVT::v16i16:
11820          return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11821        }
11822      }
11823    }
11824  }
11825
11826  // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11827  if (!Subtarget->is64Bit() &&
11828      (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11829      Amt.getOpcode() == ISD::BITCAST &&
11830      Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11831    Amt = Amt.getOperand(0);
11832    unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11833                     VT.getVectorNumElements();
11834    std::vector<SDValue> Vals(Ratio);
11835    for (unsigned i = 0; i != Ratio; ++i)
11836      Vals[i] = Amt.getOperand(i);
11837    for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11838      for (unsigned j = 0; j != Ratio; ++j)
11839        if (Vals[j] != Amt.getOperand(i + j))
11840          return SDValue();
11841    }
11842    switch (Op.getOpcode()) {
11843    default:
11844      llvm_unreachable("Unknown shift opcode!");
11845    case ISD::SHL:
11846      return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11847    case ISD::SRL:
11848      return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11849    case ISD::SRA:
11850      return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11851    }
11852  }
11853
11854  return SDValue();
11855}
11856
11857SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11858
11859  EVT VT = Op.getValueType();
11860  DebugLoc dl = Op.getDebugLoc();
11861  SDValue R = Op.getOperand(0);
11862  SDValue Amt = Op.getOperand(1);
11863  SDValue V;
11864
11865  if (!Subtarget->hasSSE2())
11866    return SDValue();
11867
11868  V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11869  if (V.getNode())
11870    return V;
11871
11872  V = LowerScalarVariableShift(Op, DAG, Subtarget);
11873  if (V.getNode())
11874      return V;
11875
11876  // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11877  if (Subtarget->hasInt256()) {
11878    if (Op.getOpcode() == ISD::SRL &&
11879        (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11880         VT == MVT::v4i64 || VT == MVT::v8i32))
11881      return Op;
11882    if (Op.getOpcode() == ISD::SHL &&
11883        (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11884         VT == MVT::v4i64 || VT == MVT::v8i32))
11885      return Op;
11886    if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11887      return Op;
11888  }
11889
11890  // Lower SHL with variable shift amount.
11891  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11892    Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11893
11894    Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11895    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11896    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11897    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11898  }
11899  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11900    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11901
11902    // a = a << 5;
11903    Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11904    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11905
11906    // Turn 'a' into a mask suitable for VSELECT
11907    SDValue VSelM = DAG.getConstant(0x80, VT);
11908    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11909    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11910
11911    SDValue CM1 = DAG.getConstant(0x0f, VT);
11912    SDValue CM2 = DAG.getConstant(0x3f, VT);
11913
11914    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11915    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11916    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11917                            DAG.getConstant(4, MVT::i32), DAG);
11918    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11919    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11920
11921    // a += a
11922    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11923    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11924    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11925
11926    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11927    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11928    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11929                            DAG.getConstant(2, MVT::i32), DAG);
11930    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11931    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11932
11933    // a += a
11934    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11935    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11936    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11937
11938    // return VSELECT(r, r+r, a);
11939    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11940                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11941    return R;
11942  }
11943
11944  // Decompose 256-bit shifts into smaller 128-bit shifts.
11945  if (VT.is256BitVector()) {
11946    unsigned NumElems = VT.getVectorNumElements();
11947    MVT EltVT = VT.getVectorElementType().getSimpleVT();
11948    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11949
11950    // Extract the two vectors
11951    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11952    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11953
11954    // Recreate the shift amount vectors
11955    SDValue Amt1, Amt2;
11956    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11957      // Constant shift amount
11958      SmallVector<SDValue, 4> Amt1Csts;
11959      SmallVector<SDValue, 4> Amt2Csts;
11960      for (unsigned i = 0; i != NumElems/2; ++i)
11961        Amt1Csts.push_back(Amt->getOperand(i));
11962      for (unsigned i = NumElems/2; i != NumElems; ++i)
11963        Amt2Csts.push_back(Amt->getOperand(i));
11964
11965      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11966                                 &Amt1Csts[0], NumElems/2);
11967      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11968                                 &Amt2Csts[0], NumElems/2);
11969    } else {
11970      // Variable shift amount
11971      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11972      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11973    }
11974
11975    // Issue new vector shifts for the smaller types
11976    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11977    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11978
11979    // Concatenate the result back
11980    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11981  }
11982
11983  return SDValue();
11984}
11985
11986static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11987  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11988  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11989  // looks for this combo and may remove the "setcc" instruction if the "setcc"
11990  // has only one use.
11991  SDNode *N = Op.getNode();
11992  SDValue LHS = N->getOperand(0);
11993  SDValue RHS = N->getOperand(1);
11994  unsigned BaseOp = 0;
11995  unsigned Cond = 0;
11996  DebugLoc DL = Op.getDebugLoc();
11997  switch (Op.getOpcode()) {
11998  default: llvm_unreachable("Unknown ovf instruction!");
11999  case ISD::SADDO:
12000    // A subtract of one will be selected as a INC. Note that INC doesn't
12001    // set CF, so we can't do this for UADDO.
12002    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12003      if (C->isOne()) {
12004        BaseOp = X86ISD::INC;
12005        Cond = X86::COND_O;
12006        break;
12007      }
12008    BaseOp = X86ISD::ADD;
12009    Cond = X86::COND_O;
12010    break;
12011  case ISD::UADDO:
12012    BaseOp = X86ISD::ADD;
12013    Cond = X86::COND_B;
12014    break;
12015  case ISD::SSUBO:
12016    // A subtract of one will be selected as a DEC. Note that DEC doesn't
12017    // set CF, so we can't do this for USUBO.
12018    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12019      if (C->isOne()) {
12020        BaseOp = X86ISD::DEC;
12021        Cond = X86::COND_O;
12022        break;
12023      }
12024    BaseOp = X86ISD::SUB;
12025    Cond = X86::COND_O;
12026    break;
12027  case ISD::USUBO:
12028    BaseOp = X86ISD::SUB;
12029    Cond = X86::COND_B;
12030    break;
12031  case ISD::SMULO:
12032    BaseOp = X86ISD::SMUL;
12033    Cond = X86::COND_O;
12034    break;
12035  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12036    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12037                                 MVT::i32);
12038    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12039
12040    SDValue SetCC =
12041      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12042                  DAG.getConstant(X86::COND_O, MVT::i32),
12043                  SDValue(Sum.getNode(), 2));
12044
12045    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12046  }
12047  }
12048
12049  // Also sets EFLAGS.
12050  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12051  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12052
12053  SDValue SetCC =
12054    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12055                DAG.getConstant(Cond, MVT::i32),
12056                SDValue(Sum.getNode(), 1));
12057
12058  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12059}
12060
12061SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12062                                                  SelectionDAG &DAG) const {
12063  DebugLoc dl = Op.getDebugLoc();
12064  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12065  EVT VT = Op.getValueType();
12066
12067  if (!Subtarget->hasSSE2() || !VT.isVector())
12068    return SDValue();
12069
12070  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12071                      ExtraVT.getScalarType().getSizeInBits();
12072  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12073
12074  switch (VT.getSimpleVT().SimpleTy) {
12075    default: return SDValue();
12076    case MVT::v8i32:
12077    case MVT::v16i16:
12078      if (!Subtarget->hasFp256())
12079        return SDValue();
12080      if (!Subtarget->hasInt256()) {
12081        // needs to be split
12082        unsigned NumElems = VT.getVectorNumElements();
12083
12084        // Extract the LHS vectors
12085        SDValue LHS = Op.getOperand(0);
12086        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12087        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12088
12089        MVT EltVT = VT.getVectorElementType().getSimpleVT();
12090        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12091
12092        EVT ExtraEltVT = ExtraVT.getVectorElementType();
12093        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12094        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12095                                   ExtraNumElems/2);
12096        SDValue Extra = DAG.getValueType(ExtraVT);
12097
12098        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12099        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12100
12101        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12102      }
12103      // fall through
12104    case MVT::v4i32:
12105    case MVT::v8i16: {
12106      // (sext (vzext x)) -> (vsext x)
12107      SDValue Op0 = Op.getOperand(0);
12108      SDValue Op00 = Op0.getOperand(0);
12109      SDValue Tmp1;
12110      // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12111      if (Op0.getOpcode() == ISD::BITCAST &&
12112          Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12113        Tmp1 = LowerVectorIntExtend(Op00, DAG);
12114      if (Tmp1.getNode()) {
12115        SDValue Tmp1Op0 = Tmp1.getOperand(0);
12116        assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12117               "This optimization is invalid without a VZEXT.");
12118        return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12119      }
12120
12121      // If the above didn't work, then just use Shift-Left + Shift-Right.
12122      Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12123      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12124    }
12125  }
12126}
12127
12128static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
12129                              SelectionDAG &DAG) {
12130  DebugLoc dl = Op.getDebugLoc();
12131
12132  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
12133  // There isn't any reason to disable it if the target processor supports it.
12134  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
12135    SDValue Chain = Op.getOperand(0);
12136    SDValue Zero = DAG.getConstant(0, MVT::i32);
12137    SDValue Ops[] = {
12138      DAG.getRegister(X86::ESP, MVT::i32), // Base
12139      DAG.getTargetConstant(1, MVT::i8),   // Scale
12140      DAG.getRegister(0, MVT::i32),        // Index
12141      DAG.getTargetConstant(0, MVT::i32),  // Disp
12142      DAG.getRegister(0, MVT::i32),        // Segment.
12143      Zero,
12144      Chain
12145    };
12146    SDNode *Res =
12147      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12148                          array_lengthof(Ops));
12149    return SDValue(Res, 0);
12150  }
12151
12152  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
12153  if (!isDev)
12154    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12155
12156  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12157  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12158  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
12159  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
12160
12161  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
12162  if (!Op1 && !Op2 && !Op3 && Op4)
12163    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
12164
12165  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
12166  if (Op1 && !Op2 && !Op3 && !Op4)
12167    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
12168
12169  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
12170  //           (MFENCE)>;
12171  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12172}
12173
12174static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12175                                 SelectionDAG &DAG) {
12176  DebugLoc dl = Op.getDebugLoc();
12177  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12178    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12179  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12180    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12181
12182  // The only fence that needs an instruction is a sequentially-consistent
12183  // cross-thread fence.
12184  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12185    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12186    // no-sse2). There isn't any reason to disable it if the target processor
12187    // supports it.
12188    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12189      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12190
12191    SDValue Chain = Op.getOperand(0);
12192    SDValue Zero = DAG.getConstant(0, MVT::i32);
12193    SDValue Ops[] = {
12194      DAG.getRegister(X86::ESP, MVT::i32), // Base
12195      DAG.getTargetConstant(1, MVT::i8),   // Scale
12196      DAG.getRegister(0, MVT::i32),        // Index
12197      DAG.getTargetConstant(0, MVT::i32),  // Disp
12198      DAG.getRegister(0, MVT::i32),        // Segment.
12199      Zero,
12200      Chain
12201    };
12202    SDNode *Res =
12203      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12204                         array_lengthof(Ops));
12205    return SDValue(Res, 0);
12206  }
12207
12208  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12209  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12210}
12211
12212static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12213                             SelectionDAG &DAG) {
12214  EVT T = Op.getValueType();
12215  DebugLoc DL = Op.getDebugLoc();
12216  unsigned Reg = 0;
12217  unsigned size = 0;
12218  switch(T.getSimpleVT().SimpleTy) {
12219  default: llvm_unreachable("Invalid value type!");
12220  case MVT::i8:  Reg = X86::AL;  size = 1; break;
12221  case MVT::i16: Reg = X86::AX;  size = 2; break;
12222  case MVT::i32: Reg = X86::EAX; size = 4; break;
12223  case MVT::i64:
12224    assert(Subtarget->is64Bit() && "Node not type legal!");
12225    Reg = X86::RAX; size = 8;
12226    break;
12227  }
12228  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12229                                    Op.getOperand(2), SDValue());
12230  SDValue Ops[] = { cpIn.getValue(0),
12231                    Op.getOperand(1),
12232                    Op.getOperand(3),
12233                    DAG.getTargetConstant(size, MVT::i8),
12234                    cpIn.getValue(1) };
12235  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12236  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12237  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12238                                           Ops, array_lengthof(Ops), T, MMO);
12239  SDValue cpOut =
12240    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12241  return cpOut;
12242}
12243
12244static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12245                                     SelectionDAG &DAG) {
12246  assert(Subtarget->is64Bit() && "Result not type legalized?");
12247  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12248  SDValue TheChain = Op.getOperand(0);
12249  DebugLoc dl = Op.getDebugLoc();
12250  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12251  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12252  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12253                                   rax.getValue(2));
12254  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12255                            DAG.getConstant(32, MVT::i8));
12256  SDValue Ops[] = {
12257    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12258    rdx.getValue(1)
12259  };
12260  return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12261}
12262
12263SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12264  EVT SrcVT = Op.getOperand(0).getValueType();
12265  EVT DstVT = Op.getValueType();
12266  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12267         Subtarget->hasMMX() && "Unexpected custom BITCAST");
12268  assert((DstVT == MVT::i64 ||
12269          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12270         "Unexpected custom BITCAST");
12271  // i64 <=> MMX conversions are Legal.
12272  if (SrcVT==MVT::i64 && DstVT.isVector())
12273    return Op;
12274  if (DstVT==MVT::i64 && SrcVT.isVector())
12275    return Op;
12276  // MMX <=> MMX conversions are Legal.
12277  if (SrcVT.isVector() && DstVT.isVector())
12278    return Op;
12279  // All other conversions need to be expanded.
12280  return SDValue();
12281}
12282
12283static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12284  SDNode *Node = Op.getNode();
12285  DebugLoc dl = Node->getDebugLoc();
12286  EVT T = Node->getValueType(0);
12287  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12288                              DAG.getConstant(0, T), Node->getOperand(2));
12289  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12290                       cast<AtomicSDNode>(Node)->getMemoryVT(),
12291                       Node->getOperand(0),
12292                       Node->getOperand(1), negOp,
12293                       cast<AtomicSDNode>(Node)->getSrcValue(),
12294                       cast<AtomicSDNode>(Node)->getAlignment(),
12295                       cast<AtomicSDNode>(Node)->getOrdering(),
12296                       cast<AtomicSDNode>(Node)->getSynchScope());
12297}
12298
12299static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12300  SDNode *Node = Op.getNode();
12301  DebugLoc dl = Node->getDebugLoc();
12302  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12303
12304  // Convert seq_cst store -> xchg
12305  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12306  // FIXME: On 32-bit, store -> fist or movq would be more efficient
12307  //        (The only way to get a 16-byte store is cmpxchg16b)
12308  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12309  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12310      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12311    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12312                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
12313                                 Node->getOperand(0),
12314                                 Node->getOperand(1), Node->getOperand(2),
12315                                 cast<AtomicSDNode>(Node)->getMemOperand(),
12316                                 cast<AtomicSDNode>(Node)->getOrdering(),
12317                                 cast<AtomicSDNode>(Node)->getSynchScope());
12318    return Swap.getValue(1);
12319  }
12320  // Other atomic stores have a simple pattern.
12321  return Op;
12322}
12323
12324static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12325  EVT VT = Op.getNode()->getValueType(0);
12326
12327  // Let legalize expand this if it isn't a legal type yet.
12328  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12329    return SDValue();
12330
12331  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12332
12333  unsigned Opc;
12334  bool ExtraOp = false;
12335  switch (Op.getOpcode()) {
12336  default: llvm_unreachable("Invalid code");
12337  case ISD::ADDC: Opc = X86ISD::ADD; break;
12338  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12339  case ISD::SUBC: Opc = X86ISD::SUB; break;
12340  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12341  }
12342
12343  if (!ExtraOp)
12344    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12345                       Op.getOperand(1));
12346  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12347                     Op.getOperand(1), Op.getOperand(2));
12348}
12349
12350SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12351  assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12352
12353  // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12354  // which returns the values as { float, float } (in XMM0) or
12355  // { double, double } (which is returned in XMM0, XMM1).
12356  DebugLoc dl = Op.getDebugLoc();
12357  SDValue Arg = Op.getOperand(0);
12358  EVT ArgVT = Arg.getValueType();
12359  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12360
12361  ArgListTy Args;
12362  ArgListEntry Entry;
12363
12364  Entry.Node = Arg;
12365  Entry.Ty = ArgTy;
12366  Entry.isSExt = false;
12367  Entry.isZExt = false;
12368  Args.push_back(Entry);
12369
12370  bool isF64 = ArgVT == MVT::f64;
12371  // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12372  // the small struct {f32, f32} is returned in (eax, edx). For f64,
12373  // the results are returned via SRet in memory.
12374  const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12375  SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12376
12377  Type *RetTy = isF64
12378    ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12379    : (Type*)VectorType::get(ArgTy, 4);
12380  TargetLowering::
12381    CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12382                         false, false, false, false, 0,
12383                         CallingConv::C, /*isTaillCall=*/false,
12384                         /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12385                         Callee, Args, DAG, dl);
12386  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12387
12388  if (isF64)
12389    // Returned in xmm0 and xmm1.
12390    return CallResult.first;
12391
12392  // Returned in bits 0:31 and 32:64 xmm0.
12393  SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12394                               CallResult.first, DAG.getIntPtrConstant(0));
12395  SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12396                               CallResult.first, DAG.getIntPtrConstant(1));
12397  SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12398  return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12399}
12400
12401/// LowerOperation - Provide custom lowering hooks for some operations.
12402///
12403SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12404  switch (Op.getOpcode()) {
12405  default: llvm_unreachable("Should not custom lower this!");
12406  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12407  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12408  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12409  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12410  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12411  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12412  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12413  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12414  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12415  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12416  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12417  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12418  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12419  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12420  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12421  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12422  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12423  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12424  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12425  case ISD::SHL_PARTS:
12426  case ISD::SRA_PARTS:
12427  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12428  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12429  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12430  case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12431  case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12432  case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12433  case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12434  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12435  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12436  case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12437  case ISD::FABS:               return LowerFABS(Op, DAG);
12438  case ISD::FNEG:               return LowerFNEG(Op, DAG);
12439  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12440  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12441  case ISD::SETCC:              return LowerSETCC(Op, DAG);
12442  case ISD::SELECT:             return LowerSELECT(Op, DAG);
12443  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12444  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12445  case ISD::VASTART:            return LowerVASTART(Op, DAG);
12446  case ISD::VAARG:              return LowerVAARG(Op, DAG);
12447  case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12448  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12449  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12450  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12451  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12452  case ISD::FRAME_TO_ARGS_OFFSET:
12453                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12454  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12455  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12456  case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12457  case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12458  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12459  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12460  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12461  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12462  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12463  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12464  case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12465  case ISD::SRA:
12466  case ISD::SRL:
12467  case ISD::SHL:                return LowerShift(Op, DAG);
12468  case ISD::SADDO:
12469  case ISD::UADDO:
12470  case ISD::SSUBO:
12471  case ISD::USUBO:
12472  case ISD::SMULO:
12473  case ISD::UMULO:              return LowerXALUO(Op, DAG);
12474  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12475  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12476  case ISD::ADDC:
12477  case ISD::ADDE:
12478  case ISD::SUBC:
12479  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12480  case ISD::ADD:                return LowerADD(Op, DAG);
12481  case ISD::SUB:                return LowerSUB(Op, DAG);
12482  case ISD::SDIV:               return LowerSDIV(Op, DAG);
12483  case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12484  }
12485}
12486
12487static void ReplaceATOMIC_LOAD(SDNode *Node,
12488                                  SmallVectorImpl<SDValue> &Results,
12489                                  SelectionDAG &DAG) {
12490  DebugLoc dl = Node->getDebugLoc();
12491  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12492
12493  // Convert wide load -> cmpxchg8b/cmpxchg16b
12494  // FIXME: On 32-bit, load -> fild or movq would be more efficient
12495  //        (The only way to get a 16-byte load is cmpxchg16b)
12496  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12497  SDValue Zero = DAG.getConstant(0, VT);
12498  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12499                               Node->getOperand(0),
12500                               Node->getOperand(1), Zero, Zero,
12501                               cast<AtomicSDNode>(Node)->getMemOperand(),
12502                               cast<AtomicSDNode>(Node)->getOrdering(),
12503                               cast<AtomicSDNode>(Node)->getSynchScope());
12504  Results.push_back(Swap.getValue(0));
12505  Results.push_back(Swap.getValue(1));
12506}
12507
12508static void
12509ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12510                        SelectionDAG &DAG, unsigned NewOp) {
12511  DebugLoc dl = Node->getDebugLoc();
12512  assert (Node->getValueType(0) == MVT::i64 &&
12513          "Only know how to expand i64 atomics");
12514
12515  SDValue Chain = Node->getOperand(0);
12516  SDValue In1 = Node->getOperand(1);
12517  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12518                             Node->getOperand(2), DAG.getIntPtrConstant(0));
12519  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12520                             Node->getOperand(2), DAG.getIntPtrConstant(1));
12521  SDValue Ops[] = { Chain, In1, In2L, In2H };
12522  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12523  SDValue Result =
12524    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12525                            cast<MemSDNode>(Node)->getMemOperand());
12526  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12527  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12528  Results.push_back(Result.getValue(2));
12529}
12530
12531/// ReplaceNodeResults - Replace a node with an illegal result type
12532/// with a new node built out of custom code.
12533void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12534                                           SmallVectorImpl<SDValue>&Results,
12535                                           SelectionDAG &DAG) const {
12536  DebugLoc dl = N->getDebugLoc();
12537  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12538  switch (N->getOpcode()) {
12539  default:
12540    llvm_unreachable("Do not know how to custom type legalize this operation!");
12541  case ISD::SIGN_EXTEND_INREG:
12542  case ISD::ADDC:
12543  case ISD::ADDE:
12544  case ISD::SUBC:
12545  case ISD::SUBE:
12546    // We don't want to expand or promote these.
12547    return;
12548  case ISD::FP_TO_SINT:
12549  case ISD::FP_TO_UINT: {
12550    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12551
12552    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12553      return;
12554
12555    std::pair<SDValue,SDValue> Vals =
12556        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12557    SDValue FIST = Vals.first, StackSlot = Vals.second;
12558    if (FIST.getNode() != 0) {
12559      EVT VT = N->getValueType(0);
12560      // Return a load from the stack slot.
12561      if (StackSlot.getNode() != 0)
12562        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12563                                      MachinePointerInfo(),
12564                                      false, false, false, 0));
12565      else
12566        Results.push_back(FIST);
12567    }
12568    return;
12569  }
12570  case ISD::UINT_TO_FP: {
12571    assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12572    if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12573        N->getValueType(0) != MVT::v2f32)
12574      return;
12575    SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12576                                 N->getOperand(0));
12577    SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12578                                     MVT::f64);
12579    SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12580    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12581                             DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12582    Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12583    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12584    Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12585    return;
12586  }
12587  case ISD::FP_ROUND: {
12588    if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12589        return;
12590    SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12591    Results.push_back(V);
12592    return;
12593  }
12594  case ISD::READCYCLECOUNTER: {
12595    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12596    SDValue TheChain = N->getOperand(0);
12597    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12598    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12599                                     rd.getValue(1));
12600    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12601                                     eax.getValue(2));
12602    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12603    SDValue Ops[] = { eax, edx };
12604    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12605                                  array_lengthof(Ops)));
12606    Results.push_back(edx.getValue(1));
12607    return;
12608  }
12609  case ISD::ATOMIC_CMP_SWAP: {
12610    EVT T = N->getValueType(0);
12611    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12612    bool Regs64bit = T == MVT::i128;
12613    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12614    SDValue cpInL, cpInH;
12615    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12616                        DAG.getConstant(0, HalfT));
12617    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12618                        DAG.getConstant(1, HalfT));
12619    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12620                             Regs64bit ? X86::RAX : X86::EAX,
12621                             cpInL, SDValue());
12622    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12623                             Regs64bit ? X86::RDX : X86::EDX,
12624                             cpInH, cpInL.getValue(1));
12625    SDValue swapInL, swapInH;
12626    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12627                          DAG.getConstant(0, HalfT));
12628    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12629                          DAG.getConstant(1, HalfT));
12630    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12631                               Regs64bit ? X86::RBX : X86::EBX,
12632                               swapInL, cpInH.getValue(1));
12633    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12634                               Regs64bit ? X86::RCX : X86::ECX,
12635                               swapInH, swapInL.getValue(1));
12636    SDValue Ops[] = { swapInH.getValue(0),
12637                      N->getOperand(1),
12638                      swapInH.getValue(1) };
12639    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12640    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12641    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12642                                  X86ISD::LCMPXCHG8_DAG;
12643    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12644                                             Ops, array_lengthof(Ops), T, MMO);
12645    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12646                                        Regs64bit ? X86::RAX : X86::EAX,
12647                                        HalfT, Result.getValue(1));
12648    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12649                                        Regs64bit ? X86::RDX : X86::EDX,
12650                                        HalfT, cpOutL.getValue(2));
12651    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12652    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12653    Results.push_back(cpOutH.getValue(1));
12654    return;
12655  }
12656  case ISD::ATOMIC_LOAD_ADD:
12657  case ISD::ATOMIC_LOAD_AND:
12658  case ISD::ATOMIC_LOAD_NAND:
12659  case ISD::ATOMIC_LOAD_OR:
12660  case ISD::ATOMIC_LOAD_SUB:
12661  case ISD::ATOMIC_LOAD_XOR:
12662  case ISD::ATOMIC_LOAD_MAX:
12663  case ISD::ATOMIC_LOAD_MIN:
12664  case ISD::ATOMIC_LOAD_UMAX:
12665  case ISD::ATOMIC_LOAD_UMIN:
12666  case ISD::ATOMIC_SWAP: {
12667    unsigned Opc;
12668    switch (N->getOpcode()) {
12669    default: llvm_unreachable("Unexpected opcode");
12670    case ISD::ATOMIC_LOAD_ADD:
12671      Opc = X86ISD::ATOMADD64_DAG;
12672      break;
12673    case ISD::ATOMIC_LOAD_AND:
12674      Opc = X86ISD::ATOMAND64_DAG;
12675      break;
12676    case ISD::ATOMIC_LOAD_NAND:
12677      Opc = X86ISD::ATOMNAND64_DAG;
12678      break;
12679    case ISD::ATOMIC_LOAD_OR:
12680      Opc = X86ISD::ATOMOR64_DAG;
12681      break;
12682    case ISD::ATOMIC_LOAD_SUB:
12683      Opc = X86ISD::ATOMSUB64_DAG;
12684      break;
12685    case ISD::ATOMIC_LOAD_XOR:
12686      Opc = X86ISD::ATOMXOR64_DAG;
12687      break;
12688    case ISD::ATOMIC_LOAD_MAX:
12689      Opc = X86ISD::ATOMMAX64_DAG;
12690      break;
12691    case ISD::ATOMIC_LOAD_MIN:
12692      Opc = X86ISD::ATOMMIN64_DAG;
12693      break;
12694    case ISD::ATOMIC_LOAD_UMAX:
12695      Opc = X86ISD::ATOMUMAX64_DAG;
12696      break;
12697    case ISD::ATOMIC_LOAD_UMIN:
12698      Opc = X86ISD::ATOMUMIN64_DAG;
12699      break;
12700    case ISD::ATOMIC_SWAP:
12701      Opc = X86ISD::ATOMSWAP64_DAG;
12702      break;
12703    }
12704    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12705    return;
12706  }
12707  case ISD::ATOMIC_LOAD:
12708    ReplaceATOMIC_LOAD(N, Results, DAG);
12709  }
12710}
12711
12712const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12713  switch (Opcode) {
12714  default: return NULL;
12715  case X86ISD::BSF:                return "X86ISD::BSF";
12716  case X86ISD::BSR:                return "X86ISD::BSR";
12717  case X86ISD::SHLD:               return "X86ISD::SHLD";
12718  case X86ISD::SHRD:               return "X86ISD::SHRD";
12719  case X86ISD::FAND:               return "X86ISD::FAND";
12720  case X86ISD::FOR:                return "X86ISD::FOR";
12721  case X86ISD::FXOR:               return "X86ISD::FXOR";
12722  case X86ISD::FSRL:               return "X86ISD::FSRL";
12723  case X86ISD::FILD:               return "X86ISD::FILD";
12724  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12725  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12726  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12727  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12728  case X86ISD::FLD:                return "X86ISD::FLD";
12729  case X86ISD::FST:                return "X86ISD::FST";
12730  case X86ISD::CALL:               return "X86ISD::CALL";
12731  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12732  case X86ISD::BT:                 return "X86ISD::BT";
12733  case X86ISD::CMP:                return "X86ISD::CMP";
12734  case X86ISD::COMI:               return "X86ISD::COMI";
12735  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12736  case X86ISD::SETCC:              return "X86ISD::SETCC";
12737  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12738  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12739  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12740  case X86ISD::CMOV:               return "X86ISD::CMOV";
12741  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12742  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12743  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12744  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12745  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12746  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12747  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12748  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12749  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12750  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12751  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12752  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12753  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12754  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12755  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12756  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12757  case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12758  case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12759  case X86ISD::HADD:               return "X86ISD::HADD";
12760  case X86ISD::HSUB:               return "X86ISD::HSUB";
12761  case X86ISD::FHADD:              return "X86ISD::FHADD";
12762  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12763  case X86ISD::UMAX:               return "X86ISD::UMAX";
12764  case X86ISD::UMIN:               return "X86ISD::UMIN";
12765  case X86ISD::SMAX:               return "X86ISD::SMAX";
12766  case X86ISD::SMIN:               return "X86ISD::SMIN";
12767  case X86ISD::FMAX:               return "X86ISD::FMAX";
12768  case X86ISD::FMIN:               return "X86ISD::FMIN";
12769  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12770  case X86ISD::FMINC:              return "X86ISD::FMINC";
12771  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12772  case X86ISD::FRCP:               return "X86ISD::FRCP";
12773  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12774  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12775  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12776  case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12777  case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12778  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12779  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12780  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12781  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12782  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12783  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12784  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12785  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12786  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12787  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12788  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12789  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12790  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12791  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12792  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12793  case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12794  case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12795  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12796  case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12797  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12798  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12799  case X86ISD::VSHL:               return "X86ISD::VSHL";
12800  case X86ISD::VSRL:               return "X86ISD::VSRL";
12801  case X86ISD::VSRA:               return "X86ISD::VSRA";
12802  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12803  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12804  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12805  case X86ISD::CMPP:               return "X86ISD::CMPP";
12806  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12807  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12808  case X86ISD::ADD:                return "X86ISD::ADD";
12809  case X86ISD::SUB:                return "X86ISD::SUB";
12810  case X86ISD::ADC:                return "X86ISD::ADC";
12811  case X86ISD::SBB:                return "X86ISD::SBB";
12812  case X86ISD::SMUL:               return "X86ISD::SMUL";
12813  case X86ISD::UMUL:               return "X86ISD::UMUL";
12814  case X86ISD::INC:                return "X86ISD::INC";
12815  case X86ISD::DEC:                return "X86ISD::DEC";
12816  case X86ISD::OR:                 return "X86ISD::OR";
12817  case X86ISD::XOR:                return "X86ISD::XOR";
12818  case X86ISD::AND:                return "X86ISD::AND";
12819  case X86ISD::BLSI:               return "X86ISD::BLSI";
12820  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12821  case X86ISD::BLSR:               return "X86ISD::BLSR";
12822  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12823  case X86ISD::PTEST:              return "X86ISD::PTEST";
12824  case X86ISD::TESTP:              return "X86ISD::TESTP";
12825  case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12826  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12827  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12828  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12829  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12830  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12831  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12832  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12833  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12834  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12835  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12836  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12837  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12838  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12839  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12840  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12841  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12842  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12843  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12844  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12845  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12846  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12847  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12848  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12849  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12850  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12851  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12852  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12853  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12854  case X86ISD::SAHF:               return "X86ISD::SAHF";
12855  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12856  case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12857  case X86ISD::FMADD:              return "X86ISD::FMADD";
12858  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12859  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12860  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12861  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12862  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12863  case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12864  case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12865  case X86ISD::XTEST:              return "X86ISD::XTEST";
12866  }
12867}
12868
12869// isLegalAddressingMode - Return true if the addressing mode represented
12870// by AM is legal for this target, for a load/store of the specified type.
12871bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12872                                              Type *Ty) const {
12873  // X86 supports extremely general addressing modes.
12874  CodeModel::Model M = getTargetMachine().getCodeModel();
12875  Reloc::Model R = getTargetMachine().getRelocationModel();
12876
12877  // X86 allows a sign-extended 32-bit immediate field as a displacement.
12878  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12879    return false;
12880
12881  if (AM.BaseGV) {
12882    unsigned GVFlags =
12883      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12884
12885    // If a reference to this global requires an extra load, we can't fold it.
12886    if (isGlobalStubReference(GVFlags))
12887      return false;
12888
12889    // If BaseGV requires a register for the PIC base, we cannot also have a
12890    // BaseReg specified.
12891    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12892      return false;
12893
12894    // If lower 4G is not available, then we must use rip-relative addressing.
12895    if ((M != CodeModel::Small || R != Reloc::Static) &&
12896        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12897      return false;
12898  }
12899
12900  switch (AM.Scale) {
12901  case 0:
12902  case 1:
12903  case 2:
12904  case 4:
12905  case 8:
12906    // These scales always work.
12907    break;
12908  case 3:
12909  case 5:
12910  case 9:
12911    // These scales are formed with basereg+scalereg.  Only accept if there is
12912    // no basereg yet.
12913    if (AM.HasBaseReg)
12914      return false;
12915    break;
12916  default:  // Other stuff never works.
12917    return false;
12918  }
12919
12920  return true;
12921}
12922
12923bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12924  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12925    return false;
12926  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12927  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12928  return NumBits1 > NumBits2;
12929}
12930
12931bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12932  return isInt<32>(Imm);
12933}
12934
12935bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12936  // Can also use sub to handle negated immediates.
12937  return isInt<32>(Imm);
12938}
12939
12940bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12941  if (!VT1.isInteger() || !VT2.isInteger())
12942    return false;
12943  unsigned NumBits1 = VT1.getSizeInBits();
12944  unsigned NumBits2 = VT2.getSizeInBits();
12945  return NumBits1 > NumBits2;
12946}
12947
12948bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12949  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12950  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12951}
12952
12953bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12954  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12955  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12956}
12957
12958bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12959  EVT VT1 = Val.getValueType();
12960  if (isZExtFree(VT1, VT2))
12961    return true;
12962
12963  if (Val.getOpcode() != ISD::LOAD)
12964    return false;
12965
12966  if (!VT1.isSimple() || !VT1.isInteger() ||
12967      !VT2.isSimple() || !VT2.isInteger())
12968    return false;
12969
12970  switch (VT1.getSimpleVT().SimpleTy) {
12971  default: break;
12972  case MVT::i8:
12973  case MVT::i16:
12974  case MVT::i32:
12975    // X86 has 8, 16, and 32-bit zero-extending loads.
12976    return true;
12977  }
12978
12979  return false;
12980}
12981
12982bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12983  // i16 instructions are longer (0x66 prefix) and potentially slower.
12984  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12985}
12986
12987/// isShuffleMaskLegal - Targets can use this to indicate that they only
12988/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12989/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12990/// are assumed to be legal.
12991bool
12992X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12993                                      EVT VT) const {
12994  // Very little shuffling can be done for 64-bit vectors right now.
12995  if (VT.getSizeInBits() == 64)
12996    return false;
12997
12998  // FIXME: pshufb, blends, shifts.
12999  return (VT.getVectorNumElements() == 2 ||
13000          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13001          isMOVLMask(M, VT) ||
13002          isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13003          isPSHUFDMask(M, VT) ||
13004          isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13005          isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13006          isPALIGNRMask(M, VT, Subtarget) ||
13007          isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13008          isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13009          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13010          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13011}
13012
13013bool
13014X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13015                                          EVT VT) const {
13016  unsigned NumElts = VT.getVectorNumElements();
13017  // FIXME: This collection of masks seems suspect.
13018  if (NumElts == 2)
13019    return true;
13020  if (NumElts == 4 && VT.is128BitVector()) {
13021    return (isMOVLMask(Mask, VT)  ||
13022            isCommutedMOVLMask(Mask, VT, true) ||
13023            isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13024            isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13025  }
13026  return false;
13027}
13028
13029//===----------------------------------------------------------------------===//
13030//                           X86 Scheduler Hooks
13031//===----------------------------------------------------------------------===//
13032
13033/// Utility function to emit xbegin specifying the start of an RTM region.
13034static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13035                                     const TargetInstrInfo *TII) {
13036  DebugLoc DL = MI->getDebugLoc();
13037
13038  const BasicBlock *BB = MBB->getBasicBlock();
13039  MachineFunction::iterator I = MBB;
13040  ++I;
13041
13042  // For the v = xbegin(), we generate
13043  //
13044  // thisMBB:
13045  //  xbegin sinkMBB
13046  //
13047  // mainMBB:
13048  //  eax = -1
13049  //
13050  // sinkMBB:
13051  //  v = eax
13052
13053  MachineBasicBlock *thisMBB = MBB;
13054  MachineFunction *MF = MBB->getParent();
13055  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13056  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13057  MF->insert(I, mainMBB);
13058  MF->insert(I, sinkMBB);
13059
13060  // Transfer the remainder of BB and its successor edges to sinkMBB.
13061  sinkMBB->splice(sinkMBB->begin(), MBB,
13062                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13063  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13064
13065  // thisMBB:
13066  //  xbegin sinkMBB
13067  //  # fallthrough to mainMBB
13068  //  # abortion to sinkMBB
13069  BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13070  thisMBB->addSuccessor(mainMBB);
13071  thisMBB->addSuccessor(sinkMBB);
13072
13073  // mainMBB:
13074  //  EAX = -1
13075  BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13076  mainMBB->addSuccessor(sinkMBB);
13077
13078  // sinkMBB:
13079  // EAX is live into the sinkMBB
13080  sinkMBB->addLiveIn(X86::EAX);
13081  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13082          TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13083    .addReg(X86::EAX);
13084
13085  MI->eraseFromParent();
13086  return sinkMBB;
13087}
13088
13089// Get CMPXCHG opcode for the specified data type.
13090static unsigned getCmpXChgOpcode(EVT VT) {
13091  switch (VT.getSimpleVT().SimpleTy) {
13092  case MVT::i8:  return X86::LCMPXCHG8;
13093  case MVT::i16: return X86::LCMPXCHG16;
13094  case MVT::i32: return X86::LCMPXCHG32;
13095  case MVT::i64: return X86::LCMPXCHG64;
13096  default:
13097    break;
13098  }
13099  llvm_unreachable("Invalid operand size!");
13100}
13101
13102// Get LOAD opcode for the specified data type.
13103static unsigned getLoadOpcode(EVT VT) {
13104  switch (VT.getSimpleVT().SimpleTy) {
13105  case MVT::i8:  return X86::MOV8rm;
13106  case MVT::i16: return X86::MOV16rm;
13107  case MVT::i32: return X86::MOV32rm;
13108  case MVT::i64: return X86::MOV64rm;
13109  default:
13110    break;
13111  }
13112  llvm_unreachable("Invalid operand size!");
13113}
13114
13115// Get opcode of the non-atomic one from the specified atomic instruction.
13116static unsigned getNonAtomicOpcode(unsigned Opc) {
13117  switch (Opc) {
13118  case X86::ATOMAND8:  return X86::AND8rr;
13119  case X86::ATOMAND16: return X86::AND16rr;
13120  case X86::ATOMAND32: return X86::AND32rr;
13121  case X86::ATOMAND64: return X86::AND64rr;
13122  case X86::ATOMOR8:   return X86::OR8rr;
13123  case X86::ATOMOR16:  return X86::OR16rr;
13124  case X86::ATOMOR32:  return X86::OR32rr;
13125  case X86::ATOMOR64:  return X86::OR64rr;
13126  case X86::ATOMXOR8:  return X86::XOR8rr;
13127  case X86::ATOMXOR16: return X86::XOR16rr;
13128  case X86::ATOMXOR32: return X86::XOR32rr;
13129  case X86::ATOMXOR64: return X86::XOR64rr;
13130  }
13131  llvm_unreachable("Unhandled atomic-load-op opcode!");
13132}
13133
13134// Get opcode of the non-atomic one from the specified atomic instruction with
13135// extra opcode.
13136static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13137                                               unsigned &ExtraOpc) {
13138  switch (Opc) {
13139  case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13140  case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13141  case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13142  case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13143  case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13144  case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13145  case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13146  case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13147  case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13148  case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13149  case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13150  case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13151  case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13152  case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13153  case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13154  case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13155  case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13156  case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13157  case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13158  case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13159  }
13160  llvm_unreachable("Unhandled atomic-load-op opcode!");
13161}
13162
13163// Get opcode of the non-atomic one from the specified atomic instruction for
13164// 64-bit data type on 32-bit target.
13165static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13166  switch (Opc) {
13167  case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13168  case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13169  case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13170  case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13171  case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13172  case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13173  case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13174  case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13175  case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13176  case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13177  }
13178  llvm_unreachable("Unhandled atomic-load-op opcode!");
13179}
13180
13181// Get opcode of the non-atomic one from the specified atomic instruction for
13182// 64-bit data type on 32-bit target with extra opcode.
13183static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13184                                                   unsigned &HiOpc,
13185                                                   unsigned &ExtraOpc) {
13186  switch (Opc) {
13187  case X86::ATOMNAND6432:
13188    ExtraOpc = X86::NOT32r;
13189    HiOpc = X86::AND32rr;
13190    return X86::AND32rr;
13191  }
13192  llvm_unreachable("Unhandled atomic-load-op opcode!");
13193}
13194
13195// Get pseudo CMOV opcode from the specified data type.
13196static unsigned getPseudoCMOVOpc(EVT VT) {
13197  switch (VT.getSimpleVT().SimpleTy) {
13198  case MVT::i8:  return X86::CMOV_GR8;
13199  case MVT::i16: return X86::CMOV_GR16;
13200  case MVT::i32: return X86::CMOV_GR32;
13201  default:
13202    break;
13203  }
13204  llvm_unreachable("Unknown CMOV opcode!");
13205}
13206
13207// EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13208// They will be translated into a spin-loop or compare-exchange loop from
13209//
13210//    ...
13211//    dst = atomic-fetch-op MI.addr, MI.val
13212//    ...
13213//
13214// to
13215//
13216//    ...
13217//    t1 = LOAD MI.addr
13218// loop:
13219//    t4 = phi(t1, t3 / loop)
13220//    t2 = OP MI.val, t4
13221//    EAX = t4
13222//    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13223//    t3 = EAX
13224//    JNE loop
13225// sink:
13226//    dst = t3
13227//    ...
13228MachineBasicBlock *
13229X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13230                                       MachineBasicBlock *MBB) const {
13231  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13232  DebugLoc DL = MI->getDebugLoc();
13233
13234  MachineFunction *MF = MBB->getParent();
13235  MachineRegisterInfo &MRI = MF->getRegInfo();
13236
13237  const BasicBlock *BB = MBB->getBasicBlock();
13238  MachineFunction::iterator I = MBB;
13239  ++I;
13240
13241  assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13242         "Unexpected number of operands");
13243
13244  assert(MI->hasOneMemOperand() &&
13245         "Expected atomic-load-op to have one memoperand");
13246
13247  // Memory Reference
13248  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13249  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13250
13251  unsigned DstReg, SrcReg;
13252  unsigned MemOpndSlot;
13253
13254  unsigned CurOp = 0;
13255
13256  DstReg = MI->getOperand(CurOp++).getReg();
13257  MemOpndSlot = CurOp;
13258  CurOp += X86::AddrNumOperands;
13259  SrcReg = MI->getOperand(CurOp++).getReg();
13260
13261  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13262  MVT::SimpleValueType VT = *RC->vt_begin();
13263  unsigned t1 = MRI.createVirtualRegister(RC);
13264  unsigned t2 = MRI.createVirtualRegister(RC);
13265  unsigned t3 = MRI.createVirtualRegister(RC);
13266  unsigned t4 = MRI.createVirtualRegister(RC);
13267  unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13268
13269  unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13270  unsigned LOADOpc = getLoadOpcode(VT);
13271
13272  // For the atomic load-arith operator, we generate
13273  //
13274  //  thisMBB:
13275  //    t1 = LOAD [MI.addr]
13276  //  mainMBB:
13277  //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13278  //    t1 = OP MI.val, EAX
13279  //    EAX = t4
13280  //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13281  //    t3 = EAX
13282  //    JNE mainMBB
13283  //  sinkMBB:
13284  //    dst = t3
13285
13286  MachineBasicBlock *thisMBB = MBB;
13287  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13288  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13289  MF->insert(I, mainMBB);
13290  MF->insert(I, sinkMBB);
13291
13292  MachineInstrBuilder MIB;
13293
13294  // Transfer the remainder of BB and its successor edges to sinkMBB.
13295  sinkMBB->splice(sinkMBB->begin(), MBB,
13296                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13297  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13298
13299  // thisMBB:
13300  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13301  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13302    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13303    if (NewMO.isReg())
13304      NewMO.setIsKill(false);
13305    MIB.addOperand(NewMO);
13306  }
13307  for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13308    unsigned flags = (*MMOI)->getFlags();
13309    flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13310    MachineMemOperand *MMO =
13311      MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13312                               (*MMOI)->getSize(),
13313                               (*MMOI)->getBaseAlignment(),
13314                               (*MMOI)->getTBAAInfo(),
13315                               (*MMOI)->getRanges());
13316    MIB.addMemOperand(MMO);
13317  }
13318
13319  thisMBB->addSuccessor(mainMBB);
13320
13321  // mainMBB:
13322  MachineBasicBlock *origMainMBB = mainMBB;
13323
13324  // Add a PHI.
13325  MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13326                        .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13327
13328  unsigned Opc = MI->getOpcode();
13329  switch (Opc) {
13330  default:
13331    llvm_unreachable("Unhandled atomic-load-op opcode!");
13332  case X86::ATOMAND8:
13333  case X86::ATOMAND16:
13334  case X86::ATOMAND32:
13335  case X86::ATOMAND64:
13336  case X86::ATOMOR8:
13337  case X86::ATOMOR16:
13338  case X86::ATOMOR32:
13339  case X86::ATOMOR64:
13340  case X86::ATOMXOR8:
13341  case X86::ATOMXOR16:
13342  case X86::ATOMXOR32:
13343  case X86::ATOMXOR64: {
13344    unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13345    BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13346      .addReg(t4);
13347    break;
13348  }
13349  case X86::ATOMNAND8:
13350  case X86::ATOMNAND16:
13351  case X86::ATOMNAND32:
13352  case X86::ATOMNAND64: {
13353    unsigned Tmp = MRI.createVirtualRegister(RC);
13354    unsigned NOTOpc;
13355    unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13356    BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13357      .addReg(t4);
13358    BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13359    break;
13360  }
13361  case X86::ATOMMAX8:
13362  case X86::ATOMMAX16:
13363  case X86::ATOMMAX32:
13364  case X86::ATOMMAX64:
13365  case X86::ATOMMIN8:
13366  case X86::ATOMMIN16:
13367  case X86::ATOMMIN32:
13368  case X86::ATOMMIN64:
13369  case X86::ATOMUMAX8:
13370  case X86::ATOMUMAX16:
13371  case X86::ATOMUMAX32:
13372  case X86::ATOMUMAX64:
13373  case X86::ATOMUMIN8:
13374  case X86::ATOMUMIN16:
13375  case X86::ATOMUMIN32:
13376  case X86::ATOMUMIN64: {
13377    unsigned CMPOpc;
13378    unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13379
13380    BuildMI(mainMBB, DL, TII->get(CMPOpc))
13381      .addReg(SrcReg)
13382      .addReg(t4);
13383
13384    if (Subtarget->hasCMov()) {
13385      if (VT != MVT::i8) {
13386        // Native support
13387        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13388          .addReg(SrcReg)
13389          .addReg(t4);
13390      } else {
13391        // Promote i8 to i32 to use CMOV32
13392        const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13393        const TargetRegisterClass *RC32 =
13394          TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13395        unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13396        unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13397        unsigned Tmp = MRI.createVirtualRegister(RC32);
13398
13399        unsigned Undef = MRI.createVirtualRegister(RC32);
13400        BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13401
13402        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13403          .addReg(Undef)
13404          .addReg(SrcReg)
13405          .addImm(X86::sub_8bit);
13406        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13407          .addReg(Undef)
13408          .addReg(t4)
13409          .addImm(X86::sub_8bit);
13410
13411        BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13412          .addReg(SrcReg32)
13413          .addReg(AccReg32);
13414
13415        BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13416          .addReg(Tmp, 0, X86::sub_8bit);
13417      }
13418    } else {
13419      // Use pseudo select and lower them.
13420      assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13421             "Invalid atomic-load-op transformation!");
13422      unsigned SelOpc = getPseudoCMOVOpc(VT);
13423      X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13424      assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13425      MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13426              .addReg(SrcReg).addReg(t4)
13427              .addImm(CC);
13428      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13429      // Replace the original PHI node as mainMBB is changed after CMOV
13430      // lowering.
13431      BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13432        .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13433      Phi->eraseFromParent();
13434    }
13435    break;
13436  }
13437  }
13438
13439  // Copy PhyReg back from virtual register.
13440  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13441    .addReg(t4);
13442
13443  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13444  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13445    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13446    if (NewMO.isReg())
13447      NewMO.setIsKill(false);
13448    MIB.addOperand(NewMO);
13449  }
13450  MIB.addReg(t2);
13451  MIB.setMemRefs(MMOBegin, MMOEnd);
13452
13453  // Copy PhyReg back to virtual register.
13454  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13455    .addReg(PhyReg);
13456
13457  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13458
13459  mainMBB->addSuccessor(origMainMBB);
13460  mainMBB->addSuccessor(sinkMBB);
13461
13462  // sinkMBB:
13463  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13464          TII->get(TargetOpcode::COPY), DstReg)
13465    .addReg(t3);
13466
13467  MI->eraseFromParent();
13468  return sinkMBB;
13469}
13470
13471// EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13472// instructions. They will be translated into a spin-loop or compare-exchange
13473// loop from
13474//
13475//    ...
13476//    dst = atomic-fetch-op MI.addr, MI.val
13477//    ...
13478//
13479// to
13480//
13481//    ...
13482//    t1L = LOAD [MI.addr + 0]
13483//    t1H = LOAD [MI.addr + 4]
13484// loop:
13485//    t4L = phi(t1L, t3L / loop)
13486//    t4H = phi(t1H, t3H / loop)
13487//    t2L = OP MI.val.lo, t4L
13488//    t2H = OP MI.val.hi, t4H
13489//    EAX = t4L
13490//    EDX = t4H
13491//    EBX = t2L
13492//    ECX = t2H
13493//    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13494//    t3L = EAX
13495//    t3H = EDX
13496//    JNE loop
13497// sink:
13498//    dstL = t3L
13499//    dstH = t3H
13500//    ...
13501MachineBasicBlock *
13502X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13503                                           MachineBasicBlock *MBB) const {
13504  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13505  DebugLoc DL = MI->getDebugLoc();
13506
13507  MachineFunction *MF = MBB->getParent();
13508  MachineRegisterInfo &MRI = MF->getRegInfo();
13509
13510  const BasicBlock *BB = MBB->getBasicBlock();
13511  MachineFunction::iterator I = MBB;
13512  ++I;
13513
13514  assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13515         "Unexpected number of operands");
13516
13517  assert(MI->hasOneMemOperand() &&
13518         "Expected atomic-load-op32 to have one memoperand");
13519
13520  // Memory Reference
13521  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13522  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13523
13524  unsigned DstLoReg, DstHiReg;
13525  unsigned SrcLoReg, SrcHiReg;
13526  unsigned MemOpndSlot;
13527
13528  unsigned CurOp = 0;
13529
13530  DstLoReg = MI->getOperand(CurOp++).getReg();
13531  DstHiReg = MI->getOperand(CurOp++).getReg();
13532  MemOpndSlot = CurOp;
13533  CurOp += X86::AddrNumOperands;
13534  SrcLoReg = MI->getOperand(CurOp++).getReg();
13535  SrcHiReg = MI->getOperand(CurOp++).getReg();
13536
13537  const TargetRegisterClass *RC = &X86::GR32RegClass;
13538  const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13539
13540  unsigned t1L = MRI.createVirtualRegister(RC);
13541  unsigned t1H = MRI.createVirtualRegister(RC);
13542  unsigned t2L = MRI.createVirtualRegister(RC);
13543  unsigned t2H = MRI.createVirtualRegister(RC);
13544  unsigned t3L = MRI.createVirtualRegister(RC);
13545  unsigned t3H = MRI.createVirtualRegister(RC);
13546  unsigned t4L = MRI.createVirtualRegister(RC);
13547  unsigned t4H = MRI.createVirtualRegister(RC);
13548
13549  unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13550  unsigned LOADOpc = X86::MOV32rm;
13551
13552  // For the atomic load-arith operator, we generate
13553  //
13554  //  thisMBB:
13555  //    t1L = LOAD [MI.addr + 0]
13556  //    t1H = LOAD [MI.addr + 4]
13557  //  mainMBB:
13558  //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13559  //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13560  //    t2L = OP MI.val.lo, t4L
13561  //    t2H = OP MI.val.hi, t4H
13562  //    EBX = t2L
13563  //    ECX = t2H
13564  //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13565  //    t3L = EAX
13566  //    t3H = EDX
13567  //    JNE loop
13568  //  sinkMBB:
13569  //    dstL = t3L
13570  //    dstH = t3H
13571
13572  MachineBasicBlock *thisMBB = MBB;
13573  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13574  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13575  MF->insert(I, mainMBB);
13576  MF->insert(I, sinkMBB);
13577
13578  MachineInstrBuilder MIB;
13579
13580  // Transfer the remainder of BB and its successor edges to sinkMBB.
13581  sinkMBB->splice(sinkMBB->begin(), MBB,
13582                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13583  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13584
13585  // thisMBB:
13586  // Lo
13587  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13588  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13589    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13590    if (NewMO.isReg())
13591      NewMO.setIsKill(false);
13592    MIB.addOperand(NewMO);
13593  }
13594  for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13595    unsigned flags = (*MMOI)->getFlags();
13596    flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13597    MachineMemOperand *MMO =
13598      MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13599                               (*MMOI)->getSize(),
13600                               (*MMOI)->getBaseAlignment(),
13601                               (*MMOI)->getTBAAInfo(),
13602                               (*MMOI)->getRanges());
13603    MIB.addMemOperand(MMO);
13604  };
13605  MachineInstr *LowMI = MIB;
13606
13607  // Hi
13608  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13609  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13610    if (i == X86::AddrDisp) {
13611      MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13612    } else {
13613      MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13614      if (NewMO.isReg())
13615        NewMO.setIsKill(false);
13616      MIB.addOperand(NewMO);
13617    }
13618  }
13619  MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13620
13621  thisMBB->addSuccessor(mainMBB);
13622
13623  // mainMBB:
13624  MachineBasicBlock *origMainMBB = mainMBB;
13625
13626  // Add PHIs.
13627  MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13628                        .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13629  MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13630                        .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13631
13632  unsigned Opc = MI->getOpcode();
13633  switch (Opc) {
13634  default:
13635    llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13636  case X86::ATOMAND6432:
13637  case X86::ATOMOR6432:
13638  case X86::ATOMXOR6432:
13639  case X86::ATOMADD6432:
13640  case X86::ATOMSUB6432: {
13641    unsigned HiOpc;
13642    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13643    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13644      .addReg(SrcLoReg);
13645    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13646      .addReg(SrcHiReg);
13647    break;
13648  }
13649  case X86::ATOMNAND6432: {
13650    unsigned HiOpc, NOTOpc;
13651    unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13652    unsigned TmpL = MRI.createVirtualRegister(RC);
13653    unsigned TmpH = MRI.createVirtualRegister(RC);
13654    BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13655      .addReg(t4L);
13656    BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13657      .addReg(t4H);
13658    BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13659    BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13660    break;
13661  }
13662  case X86::ATOMMAX6432:
13663  case X86::ATOMMIN6432:
13664  case X86::ATOMUMAX6432:
13665  case X86::ATOMUMIN6432: {
13666    unsigned HiOpc;
13667    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13668    unsigned cL = MRI.createVirtualRegister(RC8);
13669    unsigned cH = MRI.createVirtualRegister(RC8);
13670    unsigned cL32 = MRI.createVirtualRegister(RC);
13671    unsigned cH32 = MRI.createVirtualRegister(RC);
13672    unsigned cc = MRI.createVirtualRegister(RC);
13673    // cl := cmp src_lo, lo
13674    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13675      .addReg(SrcLoReg).addReg(t4L);
13676    BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13677    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13678    // ch := cmp src_hi, hi
13679    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13680      .addReg(SrcHiReg).addReg(t4H);
13681    BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13682    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13683    // cc := if (src_hi == hi) ? cl : ch;
13684    if (Subtarget->hasCMov()) {
13685      BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13686        .addReg(cH32).addReg(cL32);
13687    } else {
13688      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13689              .addReg(cH32).addReg(cL32)
13690              .addImm(X86::COND_E);
13691      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13692    }
13693    BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13694    if (Subtarget->hasCMov()) {
13695      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13696        .addReg(SrcLoReg).addReg(t4L);
13697      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13698        .addReg(SrcHiReg).addReg(t4H);
13699    } else {
13700      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13701              .addReg(SrcLoReg).addReg(t4L)
13702              .addImm(X86::COND_NE);
13703      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13704      // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13705      // 2nd CMOV lowering.
13706      mainMBB->addLiveIn(X86::EFLAGS);
13707      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13708              .addReg(SrcHiReg).addReg(t4H)
13709              .addImm(X86::COND_NE);
13710      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13711      // Replace the original PHI node as mainMBB is changed after CMOV
13712      // lowering.
13713      BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13714        .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13715      BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13716        .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13717      PhiL->eraseFromParent();
13718      PhiH->eraseFromParent();
13719    }
13720    break;
13721  }
13722  case X86::ATOMSWAP6432: {
13723    unsigned HiOpc;
13724    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13725    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13726    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13727    break;
13728  }
13729  }
13730
13731  // Copy EDX:EAX back from HiReg:LoReg
13732  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13733  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13734  // Copy ECX:EBX from t1H:t1L
13735  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13736  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13737
13738  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13739  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13740    MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13741    if (NewMO.isReg())
13742      NewMO.setIsKill(false);
13743    MIB.addOperand(NewMO);
13744  }
13745  MIB.setMemRefs(MMOBegin, MMOEnd);
13746
13747  // Copy EDX:EAX back to t3H:t3L
13748  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13749  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13750
13751  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13752
13753  mainMBB->addSuccessor(origMainMBB);
13754  mainMBB->addSuccessor(sinkMBB);
13755
13756  // sinkMBB:
13757  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13758          TII->get(TargetOpcode::COPY), DstLoReg)
13759    .addReg(t3L);
13760  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13761          TII->get(TargetOpcode::COPY), DstHiReg)
13762    .addReg(t3H);
13763
13764  MI->eraseFromParent();
13765  return sinkMBB;
13766}
13767
13768// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13769// or XMM0_V32I8 in AVX all of this code can be replaced with that
13770// in the .td file.
13771static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13772                                       const TargetInstrInfo *TII) {
13773  unsigned Opc;
13774  switch (MI->getOpcode()) {
13775  default: llvm_unreachable("illegal opcode!");
13776  case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13777  case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13778  case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13779  case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13780  case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13781  case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13782  case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13783  case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13784  }
13785
13786  DebugLoc dl = MI->getDebugLoc();
13787  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13788
13789  unsigned NumArgs = MI->getNumOperands();
13790  for (unsigned i = 1; i < NumArgs; ++i) {
13791    MachineOperand &Op = MI->getOperand(i);
13792    if (!(Op.isReg() && Op.isImplicit()))
13793      MIB.addOperand(Op);
13794  }
13795  if (MI->hasOneMemOperand())
13796    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13797
13798  BuildMI(*BB, MI, dl,
13799    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13800    .addReg(X86::XMM0);
13801
13802  MI->eraseFromParent();
13803  return BB;
13804}
13805
13806// FIXME: Custom handling because TableGen doesn't support multiple implicit
13807// defs in an instruction pattern
13808static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13809                                       const TargetInstrInfo *TII) {
13810  unsigned Opc;
13811  switch (MI->getOpcode()) {
13812  default: llvm_unreachable("illegal opcode!");
13813  case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13814  case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13815  case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13816  case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13817  case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13818  case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13819  case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13820  case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13821  }
13822
13823  DebugLoc dl = MI->getDebugLoc();
13824  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13825
13826  unsigned NumArgs = MI->getNumOperands(); // remove the results
13827  for (unsigned i = 1; i < NumArgs; ++i) {
13828    MachineOperand &Op = MI->getOperand(i);
13829    if (!(Op.isReg() && Op.isImplicit()))
13830      MIB.addOperand(Op);
13831  }
13832  if (MI->hasOneMemOperand())
13833    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13834
13835  BuildMI(*BB, MI, dl,
13836    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13837    .addReg(X86::ECX);
13838
13839  MI->eraseFromParent();
13840  return BB;
13841}
13842
13843static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13844                                       const TargetInstrInfo *TII,
13845                                       const X86Subtarget* Subtarget) {
13846  DebugLoc dl = MI->getDebugLoc();
13847
13848  // Address into RAX/EAX, other two args into ECX, EDX.
13849  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13850  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13851  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13852  for (int i = 0; i < X86::AddrNumOperands; ++i)
13853    MIB.addOperand(MI->getOperand(i));
13854
13855  unsigned ValOps = X86::AddrNumOperands;
13856  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13857    .addReg(MI->getOperand(ValOps).getReg());
13858  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13859    .addReg(MI->getOperand(ValOps+1).getReg());
13860
13861  // The instruction doesn't actually take any operands though.
13862  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13863
13864  MI->eraseFromParent(); // The pseudo is gone now.
13865  return BB;
13866}
13867
13868MachineBasicBlock *
13869X86TargetLowering::EmitVAARG64WithCustomInserter(
13870                   MachineInstr *MI,
13871                   MachineBasicBlock *MBB) const {
13872  // Emit va_arg instruction on X86-64.
13873
13874  // Operands to this pseudo-instruction:
13875  // 0  ) Output        : destination address (reg)
13876  // 1-5) Input         : va_list address (addr, i64mem)
13877  // 6  ) ArgSize       : Size (in bytes) of vararg type
13878  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13879  // 8  ) Align         : Alignment of type
13880  // 9  ) EFLAGS (implicit-def)
13881
13882  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13883  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13884
13885  unsigned DestReg = MI->getOperand(0).getReg();
13886  MachineOperand &Base = MI->getOperand(1);
13887  MachineOperand &Scale = MI->getOperand(2);
13888  MachineOperand &Index = MI->getOperand(3);
13889  MachineOperand &Disp = MI->getOperand(4);
13890  MachineOperand &Segment = MI->getOperand(5);
13891  unsigned ArgSize = MI->getOperand(6).getImm();
13892  unsigned ArgMode = MI->getOperand(7).getImm();
13893  unsigned Align = MI->getOperand(8).getImm();
13894
13895  // Memory Reference
13896  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13897  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13898  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13899
13900  // Machine Information
13901  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13902  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13903  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13904  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13905  DebugLoc DL = MI->getDebugLoc();
13906
13907  // struct va_list {
13908  //   i32   gp_offset
13909  //   i32   fp_offset
13910  //   i64   overflow_area (address)
13911  //   i64   reg_save_area (address)
13912  // }
13913  // sizeof(va_list) = 24
13914  // alignment(va_list) = 8
13915
13916  unsigned TotalNumIntRegs = 6;
13917  unsigned TotalNumXMMRegs = 8;
13918  bool UseGPOffset = (ArgMode == 1);
13919  bool UseFPOffset = (ArgMode == 2);
13920  unsigned MaxOffset = TotalNumIntRegs * 8 +
13921                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13922
13923  /* Align ArgSize to a multiple of 8 */
13924  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13925  bool NeedsAlign = (Align > 8);
13926
13927  MachineBasicBlock *thisMBB = MBB;
13928  MachineBasicBlock *overflowMBB;
13929  MachineBasicBlock *offsetMBB;
13930  MachineBasicBlock *endMBB;
13931
13932  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13933  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13934  unsigned OffsetReg = 0;
13935
13936  if (!UseGPOffset && !UseFPOffset) {
13937    // If we only pull from the overflow region, we don't create a branch.
13938    // We don't need to alter control flow.
13939    OffsetDestReg = 0; // unused
13940    OverflowDestReg = DestReg;
13941
13942    offsetMBB = NULL;
13943    overflowMBB = thisMBB;
13944    endMBB = thisMBB;
13945  } else {
13946    // First emit code to check if gp_offset (or fp_offset) is below the bound.
13947    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13948    // If not, pull from overflow_area. (branch to overflowMBB)
13949    //
13950    //       thisMBB
13951    //         |     .
13952    //         |        .
13953    //     offsetMBB   overflowMBB
13954    //         |        .
13955    //         |     .
13956    //        endMBB
13957
13958    // Registers for the PHI in endMBB
13959    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13960    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13961
13962    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13963    MachineFunction *MF = MBB->getParent();
13964    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13965    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13966    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13967
13968    MachineFunction::iterator MBBIter = MBB;
13969    ++MBBIter;
13970
13971    // Insert the new basic blocks
13972    MF->insert(MBBIter, offsetMBB);
13973    MF->insert(MBBIter, overflowMBB);
13974    MF->insert(MBBIter, endMBB);
13975
13976    // Transfer the remainder of MBB and its successor edges to endMBB.
13977    endMBB->splice(endMBB->begin(), thisMBB,
13978                    llvm::next(MachineBasicBlock::iterator(MI)),
13979                    thisMBB->end());
13980    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13981
13982    // Make offsetMBB and overflowMBB successors of thisMBB
13983    thisMBB->addSuccessor(offsetMBB);
13984    thisMBB->addSuccessor(overflowMBB);
13985
13986    // endMBB is a successor of both offsetMBB and overflowMBB
13987    offsetMBB->addSuccessor(endMBB);
13988    overflowMBB->addSuccessor(endMBB);
13989
13990    // Load the offset value into a register
13991    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13992    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13993      .addOperand(Base)
13994      .addOperand(Scale)
13995      .addOperand(Index)
13996      .addDisp(Disp, UseFPOffset ? 4 : 0)
13997      .addOperand(Segment)
13998      .setMemRefs(MMOBegin, MMOEnd);
13999
14000    // Check if there is enough room left to pull this argument.
14001    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14002      .addReg(OffsetReg)
14003      .addImm(MaxOffset + 8 - ArgSizeA8);
14004
14005    // Branch to "overflowMBB" if offset >= max
14006    // Fall through to "offsetMBB" otherwise
14007    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14008      .addMBB(overflowMBB);
14009  }
14010
14011  // In offsetMBB, emit code to use the reg_save_area.
14012  if (offsetMBB) {
14013    assert(OffsetReg != 0);
14014
14015    // Read the reg_save_area address.
14016    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14017    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14018      .addOperand(Base)
14019      .addOperand(Scale)
14020      .addOperand(Index)
14021      .addDisp(Disp, 16)
14022      .addOperand(Segment)
14023      .setMemRefs(MMOBegin, MMOEnd);
14024
14025    // Zero-extend the offset
14026    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14027      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14028        .addImm(0)
14029        .addReg(OffsetReg)
14030        .addImm(X86::sub_32bit);
14031
14032    // Add the offset to the reg_save_area to get the final address.
14033    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14034      .addReg(OffsetReg64)
14035      .addReg(RegSaveReg);
14036
14037    // Compute the offset for the next argument
14038    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14039    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14040      .addReg(OffsetReg)
14041      .addImm(UseFPOffset ? 16 : 8);
14042
14043    // Store it back into the va_list.
14044    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14045      .addOperand(Base)
14046      .addOperand(Scale)
14047      .addOperand(Index)
14048      .addDisp(Disp, UseFPOffset ? 4 : 0)
14049      .addOperand(Segment)
14050      .addReg(NextOffsetReg)
14051      .setMemRefs(MMOBegin, MMOEnd);
14052
14053    // Jump to endMBB
14054    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14055      .addMBB(endMBB);
14056  }
14057
14058  //
14059  // Emit code to use overflow area
14060  //
14061
14062  // Load the overflow_area address into a register.
14063  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14064  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14065    .addOperand(Base)
14066    .addOperand(Scale)
14067    .addOperand(Index)
14068    .addDisp(Disp, 8)
14069    .addOperand(Segment)
14070    .setMemRefs(MMOBegin, MMOEnd);
14071
14072  // If we need to align it, do so. Otherwise, just copy the address
14073  // to OverflowDestReg.
14074  if (NeedsAlign) {
14075    // Align the overflow address
14076    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14077    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14078
14079    // aligned_addr = (addr + (align-1)) & ~(align-1)
14080    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14081      .addReg(OverflowAddrReg)
14082      .addImm(Align-1);
14083
14084    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14085      .addReg(TmpReg)
14086      .addImm(~(uint64_t)(Align-1));
14087  } else {
14088    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14089      .addReg(OverflowAddrReg);
14090  }
14091
14092  // Compute the next overflow address after this argument.
14093  // (the overflow address should be kept 8-byte aligned)
14094  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14095  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14096    .addReg(OverflowDestReg)
14097    .addImm(ArgSizeA8);
14098
14099  // Store the new overflow address.
14100  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14101    .addOperand(Base)
14102    .addOperand(Scale)
14103    .addOperand(Index)
14104    .addDisp(Disp, 8)
14105    .addOperand(Segment)
14106    .addReg(NextAddrReg)
14107    .setMemRefs(MMOBegin, MMOEnd);
14108
14109  // If we branched, emit the PHI to the front of endMBB.
14110  if (offsetMBB) {
14111    BuildMI(*endMBB, endMBB->begin(), DL,
14112            TII->get(X86::PHI), DestReg)
14113      .addReg(OffsetDestReg).addMBB(offsetMBB)
14114      .addReg(OverflowDestReg).addMBB(overflowMBB);
14115  }
14116
14117  // Erase the pseudo instruction
14118  MI->eraseFromParent();
14119
14120  return endMBB;
14121}
14122
14123MachineBasicBlock *
14124X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14125                                                 MachineInstr *MI,
14126                                                 MachineBasicBlock *MBB) const {
14127  // Emit code to save XMM registers to the stack. The ABI says that the
14128  // number of registers to save is given in %al, so it's theoretically
14129  // possible to do an indirect jump trick to avoid saving all of them,
14130  // however this code takes a simpler approach and just executes all
14131  // of the stores if %al is non-zero. It's less code, and it's probably
14132  // easier on the hardware branch predictor, and stores aren't all that
14133  // expensive anyway.
14134
14135  // Create the new basic blocks. One block contains all the XMM stores,
14136  // and one block is the final destination regardless of whether any
14137  // stores were performed.
14138  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14139  MachineFunction *F = MBB->getParent();
14140  MachineFunction::iterator MBBIter = MBB;
14141  ++MBBIter;
14142  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14143  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14144  F->insert(MBBIter, XMMSaveMBB);
14145  F->insert(MBBIter, EndMBB);
14146
14147  // Transfer the remainder of MBB and its successor edges to EndMBB.
14148  EndMBB->splice(EndMBB->begin(), MBB,
14149                 llvm::next(MachineBasicBlock::iterator(MI)),
14150                 MBB->end());
14151  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14152
14153  // The original block will now fall through to the XMM save block.
14154  MBB->addSuccessor(XMMSaveMBB);
14155  // The XMMSaveMBB will fall through to the end block.
14156  XMMSaveMBB->addSuccessor(EndMBB);
14157
14158  // Now add the instructions.
14159  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14160  DebugLoc DL = MI->getDebugLoc();
14161
14162  unsigned CountReg = MI->getOperand(0).getReg();
14163  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14164  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14165
14166  if (!Subtarget->isTargetWin64()) {
14167    // If %al is 0, branch around the XMM save block.
14168    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14169    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14170    MBB->addSuccessor(EndMBB);
14171  }
14172
14173  unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14174  // In the XMM save block, save all the XMM argument registers.
14175  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14176    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14177    MachineMemOperand *MMO =
14178      F->getMachineMemOperand(
14179          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14180        MachineMemOperand::MOStore,
14181        /*Size=*/16, /*Align=*/16);
14182    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14183      .addFrameIndex(RegSaveFrameIndex)
14184      .addImm(/*Scale=*/1)
14185      .addReg(/*IndexReg=*/0)
14186      .addImm(/*Disp=*/Offset)
14187      .addReg(/*Segment=*/0)
14188      .addReg(MI->getOperand(i).getReg())
14189      .addMemOperand(MMO);
14190  }
14191
14192  MI->eraseFromParent();   // The pseudo instruction is gone now.
14193
14194  return EndMBB;
14195}
14196
14197// The EFLAGS operand of SelectItr might be missing a kill marker
14198// because there were multiple uses of EFLAGS, and ISel didn't know
14199// which to mark. Figure out whether SelectItr should have had a
14200// kill marker, and set it if it should. Returns the correct kill
14201// marker value.
14202static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14203                                     MachineBasicBlock* BB,
14204                                     const TargetRegisterInfo* TRI) {
14205  // Scan forward through BB for a use/def of EFLAGS.
14206  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14207  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14208    const MachineInstr& mi = *miI;
14209    if (mi.readsRegister(X86::EFLAGS))
14210      return false;
14211    if (mi.definesRegister(X86::EFLAGS))
14212      break; // Should have kill-flag - update below.
14213  }
14214
14215  // If we hit the end of the block, check whether EFLAGS is live into a
14216  // successor.
14217  if (miI == BB->end()) {
14218    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14219                                          sEnd = BB->succ_end();
14220         sItr != sEnd; ++sItr) {
14221      MachineBasicBlock* succ = *sItr;
14222      if (succ->isLiveIn(X86::EFLAGS))
14223        return false;
14224    }
14225  }
14226
14227  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14228  // out. SelectMI should have a kill flag on EFLAGS.
14229  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14230  return true;
14231}
14232
14233MachineBasicBlock *
14234X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14235                                     MachineBasicBlock *BB) const {
14236  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14237  DebugLoc DL = MI->getDebugLoc();
14238
14239  // To "insert" a SELECT_CC instruction, we actually have to insert the
14240  // diamond control-flow pattern.  The incoming instruction knows the
14241  // destination vreg to set, the condition code register to branch on, the
14242  // true/false values to select between, and a branch opcode to use.
14243  const BasicBlock *LLVM_BB = BB->getBasicBlock();
14244  MachineFunction::iterator It = BB;
14245  ++It;
14246
14247  //  thisMBB:
14248  //  ...
14249  //   TrueVal = ...
14250  //   cmpTY ccX, r1, r2
14251  //   bCC copy1MBB
14252  //   fallthrough --> copy0MBB
14253  MachineBasicBlock *thisMBB = BB;
14254  MachineFunction *F = BB->getParent();
14255  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14256  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14257  F->insert(It, copy0MBB);
14258  F->insert(It, sinkMBB);
14259
14260  // If the EFLAGS register isn't dead in the terminator, then claim that it's
14261  // live into the sink and copy blocks.
14262  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14263  if (!MI->killsRegister(X86::EFLAGS) &&
14264      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14265    copy0MBB->addLiveIn(X86::EFLAGS);
14266    sinkMBB->addLiveIn(X86::EFLAGS);
14267  }
14268
14269  // Transfer the remainder of BB and its successor edges to sinkMBB.
14270  sinkMBB->splice(sinkMBB->begin(), BB,
14271                  llvm::next(MachineBasicBlock::iterator(MI)),
14272                  BB->end());
14273  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14274
14275  // Add the true and fallthrough blocks as its successors.
14276  BB->addSuccessor(copy0MBB);
14277  BB->addSuccessor(sinkMBB);
14278
14279  // Create the conditional branch instruction.
14280  unsigned Opc =
14281    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14282  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14283
14284  //  copy0MBB:
14285  //   %FalseValue = ...
14286  //   # fallthrough to sinkMBB
14287  copy0MBB->addSuccessor(sinkMBB);
14288
14289  //  sinkMBB:
14290  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14291  //  ...
14292  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14293          TII->get(X86::PHI), MI->getOperand(0).getReg())
14294    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14295    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14296
14297  MI->eraseFromParent();   // The pseudo instruction is gone now.
14298  return sinkMBB;
14299}
14300
14301MachineBasicBlock *
14302X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14303                                        bool Is64Bit) const {
14304  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14305  DebugLoc DL = MI->getDebugLoc();
14306  MachineFunction *MF = BB->getParent();
14307  const BasicBlock *LLVM_BB = BB->getBasicBlock();
14308
14309  assert(getTargetMachine().Options.EnableSegmentedStacks);
14310
14311  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14312  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14313
14314  // BB:
14315  //  ... [Till the alloca]
14316  // If stacklet is not large enough, jump to mallocMBB
14317  //
14318  // bumpMBB:
14319  //  Allocate by subtracting from RSP
14320  //  Jump to continueMBB
14321  //
14322  // mallocMBB:
14323  //  Allocate by call to runtime
14324  //
14325  // continueMBB:
14326  //  ...
14327  //  [rest of original BB]
14328  //
14329
14330  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14331  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14332  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14333
14334  MachineRegisterInfo &MRI = MF->getRegInfo();
14335  const TargetRegisterClass *AddrRegClass =
14336    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14337
14338  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14339    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14340    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14341    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14342    sizeVReg = MI->getOperand(1).getReg(),
14343    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14344
14345  MachineFunction::iterator MBBIter = BB;
14346  ++MBBIter;
14347
14348  MF->insert(MBBIter, bumpMBB);
14349  MF->insert(MBBIter, mallocMBB);
14350  MF->insert(MBBIter, continueMBB);
14351
14352  continueMBB->splice(continueMBB->begin(), BB, llvm::next
14353                      (MachineBasicBlock::iterator(MI)), BB->end());
14354  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14355
14356  // Add code to the main basic block to check if the stack limit has been hit,
14357  // and if so, jump to mallocMBB otherwise to bumpMBB.
14358  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14359  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14360    .addReg(tmpSPVReg).addReg(sizeVReg);
14361  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14362    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14363    .addReg(SPLimitVReg);
14364  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14365
14366  // bumpMBB simply decreases the stack pointer, since we know the current
14367  // stacklet has enough space.
14368  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14369    .addReg(SPLimitVReg);
14370  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14371    .addReg(SPLimitVReg);
14372  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14373
14374  // Calls into a routine in libgcc to allocate more space from the heap.
14375  const uint32_t *RegMask =
14376    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14377  if (Is64Bit) {
14378    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14379      .addReg(sizeVReg);
14380    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14381      .addExternalSymbol("__morestack_allocate_stack_space")
14382      .addRegMask(RegMask)
14383      .addReg(X86::RDI, RegState::Implicit)
14384      .addReg(X86::RAX, RegState::ImplicitDefine);
14385  } else {
14386    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14387      .addImm(12);
14388    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14389    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14390      .addExternalSymbol("__morestack_allocate_stack_space")
14391      .addRegMask(RegMask)
14392      .addReg(X86::EAX, RegState::ImplicitDefine);
14393  }
14394
14395  if (!Is64Bit)
14396    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14397      .addImm(16);
14398
14399  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14400    .addReg(Is64Bit ? X86::RAX : X86::EAX);
14401  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14402
14403  // Set up the CFG correctly.
14404  BB->addSuccessor(bumpMBB);
14405  BB->addSuccessor(mallocMBB);
14406  mallocMBB->addSuccessor(continueMBB);
14407  bumpMBB->addSuccessor(continueMBB);
14408
14409  // Take care of the PHI nodes.
14410  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14411          MI->getOperand(0).getReg())
14412    .addReg(mallocPtrVReg).addMBB(mallocMBB)
14413    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14414
14415  // Delete the original pseudo instruction.
14416  MI->eraseFromParent();
14417
14418  // And we're done.
14419  return continueMBB;
14420}
14421
14422MachineBasicBlock *
14423X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14424                                          MachineBasicBlock *BB) const {
14425  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14426  DebugLoc DL = MI->getDebugLoc();
14427
14428  assert(!Subtarget->isTargetEnvMacho());
14429
14430  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14431  // non-trivial part is impdef of ESP.
14432
14433  if (Subtarget->isTargetWin64()) {
14434    if (Subtarget->isTargetCygMing()) {
14435      // ___chkstk(Mingw64):
14436      // Clobbers R10, R11, RAX and EFLAGS.
14437      // Updates RSP.
14438      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14439        .addExternalSymbol("___chkstk")
14440        .addReg(X86::RAX, RegState::Implicit)
14441        .addReg(X86::RSP, RegState::Implicit)
14442        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14443        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14444        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14445    } else {
14446      // __chkstk(MSVCRT): does not update stack pointer.
14447      // Clobbers R10, R11 and EFLAGS.
14448      // FIXME: RAX(allocated size) might be reused and not killed.
14449      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14450        .addExternalSymbol("__chkstk")
14451        .addReg(X86::RAX, RegState::Implicit)
14452        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14453      // RAX has the offset to subtracted from RSP.
14454      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14455        .addReg(X86::RSP)
14456        .addReg(X86::RAX);
14457    }
14458  } else {
14459    const char *StackProbeSymbol =
14460      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14461
14462    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14463      .addExternalSymbol(StackProbeSymbol)
14464      .addReg(X86::EAX, RegState::Implicit)
14465      .addReg(X86::ESP, RegState::Implicit)
14466      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14467      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14468      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14469  }
14470
14471  MI->eraseFromParent();   // The pseudo instruction is gone now.
14472  return BB;
14473}
14474
14475MachineBasicBlock *
14476X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14477                                      MachineBasicBlock *BB) const {
14478  // This is pretty easy.  We're taking the value that we received from
14479  // our load from the relocation, sticking it in either RDI (x86-64)
14480  // or EAX and doing an indirect call.  The return value will then
14481  // be in the normal return register.
14482  const X86InstrInfo *TII
14483    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14484  DebugLoc DL = MI->getDebugLoc();
14485  MachineFunction *F = BB->getParent();
14486
14487  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14488  assert(MI->getOperand(3).isGlobal() && "This should be a global");
14489
14490  // Get a register mask for the lowered call.
14491  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14492  // proper register mask.
14493  const uint32_t *RegMask =
14494    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14495  if (Subtarget->is64Bit()) {
14496    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14497                                      TII->get(X86::MOV64rm), X86::RDI)
14498    .addReg(X86::RIP)
14499    .addImm(0).addReg(0)
14500    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14501                      MI->getOperand(3).getTargetFlags())
14502    .addReg(0);
14503    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14504    addDirectMem(MIB, X86::RDI);
14505    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14506  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14507    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14508                                      TII->get(X86::MOV32rm), X86::EAX)
14509    .addReg(0)
14510    .addImm(0).addReg(0)
14511    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14512                      MI->getOperand(3).getTargetFlags())
14513    .addReg(0);
14514    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14515    addDirectMem(MIB, X86::EAX);
14516    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14517  } else {
14518    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14519                                      TII->get(X86::MOV32rm), X86::EAX)
14520    .addReg(TII->getGlobalBaseReg(F))
14521    .addImm(0).addReg(0)
14522    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14523                      MI->getOperand(3).getTargetFlags())
14524    .addReg(0);
14525    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14526    addDirectMem(MIB, X86::EAX);
14527    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14528  }
14529
14530  MI->eraseFromParent(); // The pseudo instruction is gone now.
14531  return BB;
14532}
14533
14534MachineBasicBlock *
14535X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14536                                    MachineBasicBlock *MBB) const {
14537  DebugLoc DL = MI->getDebugLoc();
14538  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14539
14540  MachineFunction *MF = MBB->getParent();
14541  MachineRegisterInfo &MRI = MF->getRegInfo();
14542
14543  const BasicBlock *BB = MBB->getBasicBlock();
14544  MachineFunction::iterator I = MBB;
14545  ++I;
14546
14547  // Memory Reference
14548  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14549  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14550
14551  unsigned DstReg;
14552  unsigned MemOpndSlot = 0;
14553
14554  unsigned CurOp = 0;
14555
14556  DstReg = MI->getOperand(CurOp++).getReg();
14557  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14558  assert(RC->hasType(MVT::i32) && "Invalid destination!");
14559  unsigned mainDstReg = MRI.createVirtualRegister(RC);
14560  unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14561
14562  MemOpndSlot = CurOp;
14563
14564  MVT PVT = getPointerTy();
14565  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14566         "Invalid Pointer Size!");
14567
14568  // For v = setjmp(buf), we generate
14569  //
14570  // thisMBB:
14571  //  buf[LabelOffset] = restoreMBB
14572  //  SjLjSetup restoreMBB
14573  //
14574  // mainMBB:
14575  //  v_main = 0
14576  //
14577  // sinkMBB:
14578  //  v = phi(main, restore)
14579  //
14580  // restoreMBB:
14581  //  v_restore = 1
14582
14583  MachineBasicBlock *thisMBB = MBB;
14584  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14585  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14586  MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14587  MF->insert(I, mainMBB);
14588  MF->insert(I, sinkMBB);
14589  MF->push_back(restoreMBB);
14590
14591  MachineInstrBuilder MIB;
14592
14593  // Transfer the remainder of BB and its successor edges to sinkMBB.
14594  sinkMBB->splice(sinkMBB->begin(), MBB,
14595                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14596  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14597
14598  // thisMBB:
14599  unsigned PtrStoreOpc = 0;
14600  unsigned LabelReg = 0;
14601  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14602  Reloc::Model RM = getTargetMachine().getRelocationModel();
14603  bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14604                     (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14605
14606  // Prepare IP either in reg or imm.
14607  if (!UseImmLabel) {
14608    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14609    const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14610    LabelReg = MRI.createVirtualRegister(PtrRC);
14611    if (Subtarget->is64Bit()) {
14612      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14613              .addReg(X86::RIP)
14614              .addImm(0)
14615              .addReg(0)
14616              .addMBB(restoreMBB)
14617              .addReg(0);
14618    } else {
14619      const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14620      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14621              .addReg(XII->getGlobalBaseReg(MF))
14622              .addImm(0)
14623              .addReg(0)
14624              .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14625              .addReg(0);
14626    }
14627  } else
14628    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14629  // Store IP
14630  MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14631  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14632    if (i == X86::AddrDisp)
14633      MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14634    else
14635      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14636  }
14637  if (!UseImmLabel)
14638    MIB.addReg(LabelReg);
14639  else
14640    MIB.addMBB(restoreMBB);
14641  MIB.setMemRefs(MMOBegin, MMOEnd);
14642  // Setup
14643  MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14644          .addMBB(restoreMBB);
14645  MIB.addRegMask(RegInfo->getNoPreservedMask());
14646  thisMBB->addSuccessor(mainMBB);
14647  thisMBB->addSuccessor(restoreMBB);
14648
14649  // mainMBB:
14650  //  EAX = 0
14651  BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14652  mainMBB->addSuccessor(sinkMBB);
14653
14654  // sinkMBB:
14655  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14656          TII->get(X86::PHI), DstReg)
14657    .addReg(mainDstReg).addMBB(mainMBB)
14658    .addReg(restoreDstReg).addMBB(restoreMBB);
14659
14660  // restoreMBB:
14661  BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14662  BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14663  restoreMBB->addSuccessor(sinkMBB);
14664
14665  MI->eraseFromParent();
14666  return sinkMBB;
14667}
14668
14669MachineBasicBlock *
14670X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14671                                     MachineBasicBlock *MBB) const {
14672  DebugLoc DL = MI->getDebugLoc();
14673  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14674
14675  MachineFunction *MF = MBB->getParent();
14676  MachineRegisterInfo &MRI = MF->getRegInfo();
14677
14678  // Memory Reference
14679  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14680  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14681
14682  MVT PVT = getPointerTy();
14683  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14684         "Invalid Pointer Size!");
14685
14686  const TargetRegisterClass *RC =
14687    (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14688  unsigned Tmp = MRI.createVirtualRegister(RC);
14689  // Since FP is only updated here but NOT referenced, it's treated as GPR.
14690  unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14691  unsigned SP = RegInfo->getStackRegister();
14692
14693  MachineInstrBuilder MIB;
14694
14695  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14696  const int64_t SPOffset = 2 * PVT.getStoreSize();
14697
14698  unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14699  unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14700
14701  // Reload FP
14702  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14703  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14704    MIB.addOperand(MI->getOperand(i));
14705  MIB.setMemRefs(MMOBegin, MMOEnd);
14706  // Reload IP
14707  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14708  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14709    if (i == X86::AddrDisp)
14710      MIB.addDisp(MI->getOperand(i), LabelOffset);
14711    else
14712      MIB.addOperand(MI->getOperand(i));
14713  }
14714  MIB.setMemRefs(MMOBegin, MMOEnd);
14715  // Reload SP
14716  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14717  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14718    if (i == X86::AddrDisp)
14719      MIB.addDisp(MI->getOperand(i), SPOffset);
14720    else
14721      MIB.addOperand(MI->getOperand(i));
14722  }
14723  MIB.setMemRefs(MMOBegin, MMOEnd);
14724  // Jump
14725  BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14726
14727  MI->eraseFromParent();
14728  return MBB;
14729}
14730
14731MachineBasicBlock *
14732X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14733                                               MachineBasicBlock *BB) const {
14734  switch (MI->getOpcode()) {
14735  default: llvm_unreachable("Unexpected instr type to insert");
14736  case X86::TAILJMPd64:
14737  case X86::TAILJMPr64:
14738  case X86::TAILJMPm64:
14739    llvm_unreachable("TAILJMP64 would not be touched here.");
14740  case X86::TCRETURNdi64:
14741  case X86::TCRETURNri64:
14742  case X86::TCRETURNmi64:
14743    return BB;
14744  case X86::WIN_ALLOCA:
14745    return EmitLoweredWinAlloca(MI, BB);
14746  case X86::SEG_ALLOCA_32:
14747    return EmitLoweredSegAlloca(MI, BB, false);
14748  case X86::SEG_ALLOCA_64:
14749    return EmitLoweredSegAlloca(MI, BB, true);
14750  case X86::TLSCall_32:
14751  case X86::TLSCall_64:
14752    return EmitLoweredTLSCall(MI, BB);
14753  case X86::CMOV_GR8:
14754  case X86::CMOV_FR32:
14755  case X86::CMOV_FR64:
14756  case X86::CMOV_V4F32:
14757  case X86::CMOV_V2F64:
14758  case X86::CMOV_V2I64:
14759  case X86::CMOV_V8F32:
14760  case X86::CMOV_V4F64:
14761  case X86::CMOV_V4I64:
14762  case X86::CMOV_GR16:
14763  case X86::CMOV_GR32:
14764  case X86::CMOV_RFP32:
14765  case X86::CMOV_RFP64:
14766  case X86::CMOV_RFP80:
14767    return EmitLoweredSelect(MI, BB);
14768
14769  case X86::FP32_TO_INT16_IN_MEM:
14770  case X86::FP32_TO_INT32_IN_MEM:
14771  case X86::FP32_TO_INT64_IN_MEM:
14772  case X86::FP64_TO_INT16_IN_MEM:
14773  case X86::FP64_TO_INT32_IN_MEM:
14774  case X86::FP64_TO_INT64_IN_MEM:
14775  case X86::FP80_TO_INT16_IN_MEM:
14776  case X86::FP80_TO_INT32_IN_MEM:
14777  case X86::FP80_TO_INT64_IN_MEM: {
14778    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14779    DebugLoc DL = MI->getDebugLoc();
14780
14781    // Change the floating point control register to use "round towards zero"
14782    // mode when truncating to an integer value.
14783    MachineFunction *F = BB->getParent();
14784    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14785    addFrameReference(BuildMI(*BB, MI, DL,
14786                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
14787
14788    // Load the old value of the high byte of the control word...
14789    unsigned OldCW =
14790      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14791    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14792                      CWFrameIdx);
14793
14794    // Set the high part to be round to zero...
14795    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14796      .addImm(0xC7F);
14797
14798    // Reload the modified control word now...
14799    addFrameReference(BuildMI(*BB, MI, DL,
14800                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14801
14802    // Restore the memory image of control word to original value
14803    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14804      .addReg(OldCW);
14805
14806    // Get the X86 opcode to use.
14807    unsigned Opc;
14808    switch (MI->getOpcode()) {
14809    default: llvm_unreachable("illegal opcode!");
14810    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14811    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14812    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14813    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14814    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14815    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14816    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14817    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14818    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14819    }
14820
14821    X86AddressMode AM;
14822    MachineOperand &Op = MI->getOperand(0);
14823    if (Op.isReg()) {
14824      AM.BaseType = X86AddressMode::RegBase;
14825      AM.Base.Reg = Op.getReg();
14826    } else {
14827      AM.BaseType = X86AddressMode::FrameIndexBase;
14828      AM.Base.FrameIndex = Op.getIndex();
14829    }
14830    Op = MI->getOperand(1);
14831    if (Op.isImm())
14832      AM.Scale = Op.getImm();
14833    Op = MI->getOperand(2);
14834    if (Op.isImm())
14835      AM.IndexReg = Op.getImm();
14836    Op = MI->getOperand(3);
14837    if (Op.isGlobal()) {
14838      AM.GV = Op.getGlobal();
14839    } else {
14840      AM.Disp = Op.getImm();
14841    }
14842    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14843                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14844
14845    // Reload the original control word now.
14846    addFrameReference(BuildMI(*BB, MI, DL,
14847                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14848
14849    MI->eraseFromParent();   // The pseudo instruction is gone now.
14850    return BB;
14851  }
14852    // String/text processing lowering.
14853  case X86::PCMPISTRM128REG:
14854  case X86::VPCMPISTRM128REG:
14855  case X86::PCMPISTRM128MEM:
14856  case X86::VPCMPISTRM128MEM:
14857  case X86::PCMPESTRM128REG:
14858  case X86::VPCMPESTRM128REG:
14859  case X86::PCMPESTRM128MEM:
14860  case X86::VPCMPESTRM128MEM:
14861    assert(Subtarget->hasSSE42() &&
14862           "Target must have SSE4.2 or AVX features enabled");
14863    return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14864
14865  // String/text processing lowering.
14866  case X86::PCMPISTRIREG:
14867  case X86::VPCMPISTRIREG:
14868  case X86::PCMPISTRIMEM:
14869  case X86::VPCMPISTRIMEM:
14870  case X86::PCMPESTRIREG:
14871  case X86::VPCMPESTRIREG:
14872  case X86::PCMPESTRIMEM:
14873  case X86::VPCMPESTRIMEM:
14874    assert(Subtarget->hasSSE42() &&
14875           "Target must have SSE4.2 or AVX features enabled");
14876    return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14877
14878  // Thread synchronization.
14879  case X86::MONITOR:
14880    return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14881
14882  // xbegin
14883  case X86::XBEGIN:
14884    return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14885
14886  // Atomic Lowering.
14887  case X86::ATOMAND8:
14888  case X86::ATOMAND16:
14889  case X86::ATOMAND32:
14890  case X86::ATOMAND64:
14891    // Fall through
14892  case X86::ATOMOR8:
14893  case X86::ATOMOR16:
14894  case X86::ATOMOR32:
14895  case X86::ATOMOR64:
14896    // Fall through
14897  case X86::ATOMXOR16:
14898  case X86::ATOMXOR8:
14899  case X86::ATOMXOR32:
14900  case X86::ATOMXOR64:
14901    // Fall through
14902  case X86::ATOMNAND8:
14903  case X86::ATOMNAND16:
14904  case X86::ATOMNAND32:
14905  case X86::ATOMNAND64:
14906    // Fall through
14907  case X86::ATOMMAX8:
14908  case X86::ATOMMAX16:
14909  case X86::ATOMMAX32:
14910  case X86::ATOMMAX64:
14911    // Fall through
14912  case X86::ATOMMIN8:
14913  case X86::ATOMMIN16:
14914  case X86::ATOMMIN32:
14915  case X86::ATOMMIN64:
14916    // Fall through
14917  case X86::ATOMUMAX8:
14918  case X86::ATOMUMAX16:
14919  case X86::ATOMUMAX32:
14920  case X86::ATOMUMAX64:
14921    // Fall through
14922  case X86::ATOMUMIN8:
14923  case X86::ATOMUMIN16:
14924  case X86::ATOMUMIN32:
14925  case X86::ATOMUMIN64:
14926    return EmitAtomicLoadArith(MI, BB);
14927
14928  // This group does 64-bit operations on a 32-bit host.
14929  case X86::ATOMAND6432:
14930  case X86::ATOMOR6432:
14931  case X86::ATOMXOR6432:
14932  case X86::ATOMNAND6432:
14933  case X86::ATOMADD6432:
14934  case X86::ATOMSUB6432:
14935  case X86::ATOMMAX6432:
14936  case X86::ATOMMIN6432:
14937  case X86::ATOMUMAX6432:
14938  case X86::ATOMUMIN6432:
14939  case X86::ATOMSWAP6432:
14940    return EmitAtomicLoadArith6432(MI, BB);
14941
14942  case X86::VASTART_SAVE_XMM_REGS:
14943    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14944
14945  case X86::VAARG_64:
14946    return EmitVAARG64WithCustomInserter(MI, BB);
14947
14948  case X86::EH_SjLj_SetJmp32:
14949  case X86::EH_SjLj_SetJmp64:
14950    return emitEHSjLjSetJmp(MI, BB);
14951
14952  case X86::EH_SjLj_LongJmp32:
14953  case X86::EH_SjLj_LongJmp64:
14954    return emitEHSjLjLongJmp(MI, BB);
14955  }
14956}
14957
14958//===----------------------------------------------------------------------===//
14959//                           X86 Optimization Hooks
14960//===----------------------------------------------------------------------===//
14961
14962void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14963                                                       APInt &KnownZero,
14964                                                       APInt &KnownOne,
14965                                                       const SelectionDAG &DAG,
14966                                                       unsigned Depth) const {
14967  unsigned BitWidth = KnownZero.getBitWidth();
14968  unsigned Opc = Op.getOpcode();
14969  assert((Opc >= ISD::BUILTIN_OP_END ||
14970          Opc == ISD::INTRINSIC_WO_CHAIN ||
14971          Opc == ISD::INTRINSIC_W_CHAIN ||
14972          Opc == ISD::INTRINSIC_VOID) &&
14973         "Should use MaskedValueIsZero if you don't know whether Op"
14974         " is a target node!");
14975
14976  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14977  switch (Opc) {
14978  default: break;
14979  case X86ISD::ADD:
14980  case X86ISD::SUB:
14981  case X86ISD::ADC:
14982  case X86ISD::SBB:
14983  case X86ISD::SMUL:
14984  case X86ISD::UMUL:
14985  case X86ISD::INC:
14986  case X86ISD::DEC:
14987  case X86ISD::OR:
14988  case X86ISD::XOR:
14989  case X86ISD::AND:
14990    // These nodes' second result is a boolean.
14991    if (Op.getResNo() == 0)
14992      break;
14993    // Fallthrough
14994  case X86ISD::SETCC:
14995    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14996    break;
14997  case ISD::INTRINSIC_WO_CHAIN: {
14998    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14999    unsigned NumLoBits = 0;
15000    switch (IntId) {
15001    default: break;
15002    case Intrinsic::x86_sse_movmsk_ps:
15003    case Intrinsic::x86_avx_movmsk_ps_256:
15004    case Intrinsic::x86_sse2_movmsk_pd:
15005    case Intrinsic::x86_avx_movmsk_pd_256:
15006    case Intrinsic::x86_mmx_pmovmskb:
15007    case Intrinsic::x86_sse2_pmovmskb_128:
15008    case Intrinsic::x86_avx2_pmovmskb: {
15009      // High bits of movmskp{s|d}, pmovmskb are known zero.
15010      switch (IntId) {
15011        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15012        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15013        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15014        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15015        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15016        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15017        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15018        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15019      }
15020      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15021      break;
15022    }
15023    }
15024    break;
15025  }
15026  }
15027}
15028
15029unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15030                                                         unsigned Depth) const {
15031  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15032  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15033    return Op.getValueType().getScalarType().getSizeInBits();
15034
15035  // Fallback case.
15036  return 1;
15037}
15038
15039/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15040/// node is a GlobalAddress + offset.
15041bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15042                                       const GlobalValue* &GA,
15043                                       int64_t &Offset) const {
15044  if (N->getOpcode() == X86ISD::Wrapper) {
15045    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15046      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15047      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15048      return true;
15049    }
15050  }
15051  return TargetLowering::isGAPlusOffset(N, GA, Offset);
15052}
15053
15054/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15055/// same as extracting the high 128-bit part of 256-bit vector and then
15056/// inserting the result into the low part of a new 256-bit vector
15057static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15058  EVT VT = SVOp->getValueType(0);
15059  unsigned NumElems = VT.getVectorNumElements();
15060
15061  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15062  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15063    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15064        SVOp->getMaskElt(j) >= 0)
15065      return false;
15066
15067  return true;
15068}
15069
15070/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15071/// same as extracting the low 128-bit part of 256-bit vector and then
15072/// inserting the result into the high part of a new 256-bit vector
15073static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15074  EVT VT = SVOp->getValueType(0);
15075  unsigned NumElems = VT.getVectorNumElements();
15076
15077  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15078  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15079    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15080        SVOp->getMaskElt(j) >= 0)
15081      return false;
15082
15083  return true;
15084}
15085
15086/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15087static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15088                                        TargetLowering::DAGCombinerInfo &DCI,
15089                                        const X86Subtarget* Subtarget) {
15090  DebugLoc dl = N->getDebugLoc();
15091  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15092  SDValue V1 = SVOp->getOperand(0);
15093  SDValue V2 = SVOp->getOperand(1);
15094  EVT VT = SVOp->getValueType(0);
15095  unsigned NumElems = VT.getVectorNumElements();
15096
15097  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15098      V2.getOpcode() == ISD::CONCAT_VECTORS) {
15099    //
15100    //                   0,0,0,...
15101    //                      |
15102    //    V      UNDEF    BUILD_VECTOR    UNDEF
15103    //     \      /           \           /
15104    //  CONCAT_VECTOR         CONCAT_VECTOR
15105    //         \                  /
15106    //          \                /
15107    //          RESULT: V + zero extended
15108    //
15109    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15110        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15111        V1.getOperand(1).getOpcode() != ISD::UNDEF)
15112      return SDValue();
15113
15114    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15115      return SDValue();
15116
15117    // To match the shuffle mask, the first half of the mask should
15118    // be exactly the first vector, and all the rest a splat with the
15119    // first element of the second one.
15120    for (unsigned i = 0; i != NumElems/2; ++i)
15121      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15122          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15123        return SDValue();
15124
15125    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15126    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15127      if (Ld->hasNUsesOfValue(1, 0)) {
15128        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15129        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15130        SDValue ResNode =
15131          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15132                                  array_lengthof(Ops),
15133                                  Ld->getMemoryVT(),
15134                                  Ld->getPointerInfo(),
15135                                  Ld->getAlignment(),
15136                                  false/*isVolatile*/, true/*ReadMem*/,
15137                                  false/*WriteMem*/);
15138
15139        // Make sure the newly-created LOAD is in the same position as Ld in
15140        // terms of dependency. We create a TokenFactor for Ld and ResNode,
15141        // and update uses of Ld's output chain to use the TokenFactor.
15142        if (Ld->hasAnyUseOfValue(1)) {
15143          SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15144                             SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15145          DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15146          DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15147                                 SDValue(ResNode.getNode(), 1));
15148        }
15149
15150        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15151      }
15152    }
15153
15154    // Emit a zeroed vector and insert the desired subvector on its
15155    // first half.
15156    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15157    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15158    return DCI.CombineTo(N, InsV);
15159  }
15160
15161  //===--------------------------------------------------------------------===//
15162  // Combine some shuffles into subvector extracts and inserts:
15163  //
15164
15165  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15166  if (isShuffleHigh128VectorInsertLow(SVOp)) {
15167    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15168    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15169    return DCI.CombineTo(N, InsV);
15170  }
15171
15172  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15173  if (isShuffleLow128VectorInsertHigh(SVOp)) {
15174    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15175    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15176    return DCI.CombineTo(N, InsV);
15177  }
15178
15179  return SDValue();
15180}
15181
15182/// PerformShuffleCombine - Performs several different shuffle combines.
15183static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15184                                     TargetLowering::DAGCombinerInfo &DCI,
15185                                     const X86Subtarget *Subtarget) {
15186  DebugLoc dl = N->getDebugLoc();
15187  EVT VT = N->getValueType(0);
15188
15189  // Don't create instructions with illegal types after legalize types has run.
15190  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15191  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15192    return SDValue();
15193
15194  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15195  if (Subtarget->hasFp256() && VT.is256BitVector() &&
15196      N->getOpcode() == ISD::VECTOR_SHUFFLE)
15197    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15198
15199  // Only handle 128 wide vector from here on.
15200  if (!VT.is128BitVector())
15201    return SDValue();
15202
15203  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15204  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15205  // consecutive, non-overlapping, and in the right order.
15206  SmallVector<SDValue, 16> Elts;
15207  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15208    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15209
15210  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15211}
15212
15213/// PerformTruncateCombine - Converts truncate operation to
15214/// a sequence of vector shuffle operations.
15215/// It is possible when we truncate 256-bit vector to 128-bit vector
15216static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15217                                      TargetLowering::DAGCombinerInfo &DCI,
15218                                      const X86Subtarget *Subtarget)  {
15219  return SDValue();
15220}
15221
15222/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15223/// specific shuffle of a load can be folded into a single element load.
15224/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15225/// shuffles have been customed lowered so we need to handle those here.
15226static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15227                                         TargetLowering::DAGCombinerInfo &DCI) {
15228  if (DCI.isBeforeLegalizeOps())
15229    return SDValue();
15230
15231  SDValue InVec = N->getOperand(0);
15232  SDValue EltNo = N->getOperand(1);
15233
15234  if (!isa<ConstantSDNode>(EltNo))
15235    return SDValue();
15236
15237  EVT VT = InVec.getValueType();
15238
15239  bool HasShuffleIntoBitcast = false;
15240  if (InVec.getOpcode() == ISD::BITCAST) {
15241    // Don't duplicate a load with other uses.
15242    if (!InVec.hasOneUse())
15243      return SDValue();
15244    EVT BCVT = InVec.getOperand(0).getValueType();
15245    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15246      return SDValue();
15247    InVec = InVec.getOperand(0);
15248    HasShuffleIntoBitcast = true;
15249  }
15250
15251  if (!isTargetShuffle(InVec.getOpcode()))
15252    return SDValue();
15253
15254  // Don't duplicate a load with other uses.
15255  if (!InVec.hasOneUse())
15256    return SDValue();
15257
15258  SmallVector<int, 16> ShuffleMask;
15259  bool UnaryShuffle;
15260  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15261                            UnaryShuffle))
15262    return SDValue();
15263
15264  // Select the input vector, guarding against out of range extract vector.
15265  unsigned NumElems = VT.getVectorNumElements();
15266  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15267  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15268  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15269                                         : InVec.getOperand(1);
15270
15271  // If inputs to shuffle are the same for both ops, then allow 2 uses
15272  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15273
15274  if (LdNode.getOpcode() == ISD::BITCAST) {
15275    // Don't duplicate a load with other uses.
15276    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15277      return SDValue();
15278
15279    AllowedUses = 1; // only allow 1 load use if we have a bitcast
15280    LdNode = LdNode.getOperand(0);
15281  }
15282
15283  if (!ISD::isNormalLoad(LdNode.getNode()))
15284    return SDValue();
15285
15286  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15287
15288  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15289    return SDValue();
15290
15291  if (HasShuffleIntoBitcast) {
15292    // If there's a bitcast before the shuffle, check if the load type and
15293    // alignment is valid.
15294    unsigned Align = LN0->getAlignment();
15295    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15296    unsigned NewAlign = TLI.getDataLayout()->
15297      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15298
15299    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15300      return SDValue();
15301  }
15302
15303  // All checks match so transform back to vector_shuffle so that DAG combiner
15304  // can finish the job
15305  DebugLoc dl = N->getDebugLoc();
15306
15307  // Create shuffle node taking into account the case that its a unary shuffle
15308  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15309  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15310                                 InVec.getOperand(0), Shuffle,
15311                                 &ShuffleMask[0]);
15312  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15313  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15314                     EltNo);
15315}
15316
15317/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15318/// generation and convert it from being a bunch of shuffles and extracts
15319/// to a simple store and scalar loads to extract the elements.
15320static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15321                                         TargetLowering::DAGCombinerInfo &DCI) {
15322  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15323  if (NewOp.getNode())
15324    return NewOp;
15325
15326  SDValue InputVector = N->getOperand(0);
15327  // Detect whether we are trying to convert from mmx to i32 and the bitcast
15328  // from mmx to v2i32 has a single usage.
15329  if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15330      InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15331      InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15332    return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15333                       N->getValueType(0),
15334                       InputVector.getNode()->getOperand(0));
15335
15336  // Only operate on vectors of 4 elements, where the alternative shuffling
15337  // gets to be more expensive.
15338  if (InputVector.getValueType() != MVT::v4i32)
15339    return SDValue();
15340
15341  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15342  // single use which is a sign-extend or zero-extend, and all elements are
15343  // used.
15344  SmallVector<SDNode *, 4> Uses;
15345  unsigned ExtractedElements = 0;
15346  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15347       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15348    if (UI.getUse().getResNo() != InputVector.getResNo())
15349      return SDValue();
15350
15351    SDNode *Extract = *UI;
15352    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15353      return SDValue();
15354
15355    if (Extract->getValueType(0) != MVT::i32)
15356      return SDValue();
15357    if (!Extract->hasOneUse())
15358      return SDValue();
15359    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15360        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15361      return SDValue();
15362    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15363      return SDValue();
15364
15365    // Record which element was extracted.
15366    ExtractedElements |=
15367      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15368
15369    Uses.push_back(Extract);
15370  }
15371
15372  // If not all the elements were used, this may not be worthwhile.
15373  if (ExtractedElements != 15)
15374    return SDValue();
15375
15376  // Ok, we've now decided to do the transformation.
15377  DebugLoc dl = InputVector.getDebugLoc();
15378
15379  // Store the value to a temporary stack slot.
15380  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15381  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15382                            MachinePointerInfo(), false, false, 0);
15383
15384  // Replace each use (extract) with a load of the appropriate element.
15385  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15386       UE = Uses.end(); UI != UE; ++UI) {
15387    SDNode *Extract = *UI;
15388
15389    // cOMpute the element's address.
15390    SDValue Idx = Extract->getOperand(1);
15391    unsigned EltSize =
15392        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15393    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15394    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15395    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15396
15397    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15398                                     StackPtr, OffsetVal);
15399
15400    // Load the scalar.
15401    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15402                                     ScalarAddr, MachinePointerInfo(),
15403                                     false, false, false, 0);
15404
15405    // Replace the exact with the load.
15406    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15407  }
15408
15409  // The replacement was made in place; don't return anything.
15410  return SDValue();
15411}
15412
15413/// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15414static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15415                                   SDValue RHS, SelectionDAG &DAG,
15416                                   const X86Subtarget *Subtarget) {
15417  if (!VT.isVector())
15418    return 0;
15419
15420  switch (VT.getSimpleVT().SimpleTy) {
15421  default: return 0;
15422  case MVT::v32i8:
15423  case MVT::v16i16:
15424  case MVT::v8i32:
15425    if (!Subtarget->hasAVX2())
15426      return 0;
15427  case MVT::v16i8:
15428  case MVT::v8i16:
15429  case MVT::v4i32:
15430    if (!Subtarget->hasSSE2())
15431      return 0;
15432  }
15433
15434  // SSE2 has only a small subset of the operations.
15435  bool hasUnsigned = Subtarget->hasSSE41() ||
15436                     (Subtarget->hasSSE2() && VT == MVT::v16i8);
15437  bool hasSigned = Subtarget->hasSSE41() ||
15438                   (Subtarget->hasSSE2() && VT == MVT::v8i16);
15439
15440  ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15441
15442  // Check for x CC y ? x : y.
15443  if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15444      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15445    switch (CC) {
15446    default: break;
15447    case ISD::SETULT:
15448    case ISD::SETULE:
15449      return hasUnsigned ? X86ISD::UMIN : 0;
15450    case ISD::SETUGT:
15451    case ISD::SETUGE:
15452      return hasUnsigned ? X86ISD::UMAX : 0;
15453    case ISD::SETLT:
15454    case ISD::SETLE:
15455      return hasSigned ? X86ISD::SMIN : 0;
15456    case ISD::SETGT:
15457    case ISD::SETGE:
15458      return hasSigned ? X86ISD::SMAX : 0;
15459    }
15460  // Check for x CC y ? y : x -- a min/max with reversed arms.
15461  } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15462             DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15463    switch (CC) {
15464    default: break;
15465    case ISD::SETULT:
15466    case ISD::SETULE:
15467      return hasUnsigned ? X86ISD::UMAX : 0;
15468    case ISD::SETUGT:
15469    case ISD::SETUGE:
15470      return hasUnsigned ? X86ISD::UMIN : 0;
15471    case ISD::SETLT:
15472    case ISD::SETLE:
15473      return hasSigned ? X86ISD::SMAX : 0;
15474    case ISD::SETGT:
15475    case ISD::SETGE:
15476      return hasSigned ? X86ISD::SMIN : 0;
15477    }
15478  }
15479
15480  return 0;
15481}
15482
15483/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15484/// nodes.
15485static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15486                                    TargetLowering::DAGCombinerInfo &DCI,
15487                                    const X86Subtarget *Subtarget) {
15488  DebugLoc DL = N->getDebugLoc();
15489  SDValue Cond = N->getOperand(0);
15490  // Get the LHS/RHS of the select.
15491  SDValue LHS = N->getOperand(1);
15492  SDValue RHS = N->getOperand(2);
15493  EVT VT = LHS.getValueType();
15494
15495  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15496  // instructions match the semantics of the common C idiom x<y?x:y but not
15497  // x<=y?x:y, because of how they handle negative zero (which can be
15498  // ignored in unsafe-math mode).
15499  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15500      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15501      (Subtarget->hasSSE2() ||
15502       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15503    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15504
15505    unsigned Opcode = 0;
15506    // Check for x CC y ? x : y.
15507    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15508        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15509      switch (CC) {
15510      default: break;
15511      case ISD::SETULT:
15512        // Converting this to a min would handle NaNs incorrectly, and swapping
15513        // the operands would cause it to handle comparisons between positive
15514        // and negative zero incorrectly.
15515        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15516          if (!DAG.getTarget().Options.UnsafeFPMath &&
15517              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15518            break;
15519          std::swap(LHS, RHS);
15520        }
15521        Opcode = X86ISD::FMIN;
15522        break;
15523      case ISD::SETOLE:
15524        // Converting this to a min would handle comparisons between positive
15525        // and negative zero incorrectly.
15526        if (!DAG.getTarget().Options.UnsafeFPMath &&
15527            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15528          break;
15529        Opcode = X86ISD::FMIN;
15530        break;
15531      case ISD::SETULE:
15532        // Converting this to a min would handle both negative zeros and NaNs
15533        // incorrectly, but we can swap the operands to fix both.
15534        std::swap(LHS, RHS);
15535      case ISD::SETOLT:
15536      case ISD::SETLT:
15537      case ISD::SETLE:
15538        Opcode = X86ISD::FMIN;
15539        break;
15540
15541      case ISD::SETOGE:
15542        // Converting this to a max would handle comparisons between positive
15543        // and negative zero incorrectly.
15544        if (!DAG.getTarget().Options.UnsafeFPMath &&
15545            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15546          break;
15547        Opcode = X86ISD::FMAX;
15548        break;
15549      case ISD::SETUGT:
15550        // Converting this to a max would handle NaNs incorrectly, and swapping
15551        // the operands would cause it to handle comparisons between positive
15552        // and negative zero incorrectly.
15553        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15554          if (!DAG.getTarget().Options.UnsafeFPMath &&
15555              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15556            break;
15557          std::swap(LHS, RHS);
15558        }
15559        Opcode = X86ISD::FMAX;
15560        break;
15561      case ISD::SETUGE:
15562        // Converting this to a max would handle both negative zeros and NaNs
15563        // incorrectly, but we can swap the operands to fix both.
15564        std::swap(LHS, RHS);
15565      case ISD::SETOGT:
15566      case ISD::SETGT:
15567      case ISD::SETGE:
15568        Opcode = X86ISD::FMAX;
15569        break;
15570      }
15571    // Check for x CC y ? y : x -- a min/max with reversed arms.
15572    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15573               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15574      switch (CC) {
15575      default: break;
15576      case ISD::SETOGE:
15577        // Converting this to a min would handle comparisons between positive
15578        // and negative zero incorrectly, and swapping the operands would
15579        // cause it to handle NaNs incorrectly.
15580        if (!DAG.getTarget().Options.UnsafeFPMath &&
15581            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15582          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15583            break;
15584          std::swap(LHS, RHS);
15585        }
15586        Opcode = X86ISD::FMIN;
15587        break;
15588      case ISD::SETUGT:
15589        // Converting this to a min would handle NaNs incorrectly.
15590        if (!DAG.getTarget().Options.UnsafeFPMath &&
15591            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15592          break;
15593        Opcode = X86ISD::FMIN;
15594        break;
15595      case ISD::SETUGE:
15596        // Converting this to a min would handle both negative zeros and NaNs
15597        // incorrectly, but we can swap the operands to fix both.
15598        std::swap(LHS, RHS);
15599      case ISD::SETOGT:
15600      case ISD::SETGT:
15601      case ISD::SETGE:
15602        Opcode = X86ISD::FMIN;
15603        break;
15604
15605      case ISD::SETULT:
15606        // Converting this to a max would handle NaNs incorrectly.
15607        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15608          break;
15609        Opcode = X86ISD::FMAX;
15610        break;
15611      case ISD::SETOLE:
15612        // Converting this to a max would handle comparisons between positive
15613        // and negative zero incorrectly, and swapping the operands would
15614        // cause it to handle NaNs incorrectly.
15615        if (!DAG.getTarget().Options.UnsafeFPMath &&
15616            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15617          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15618            break;
15619          std::swap(LHS, RHS);
15620        }
15621        Opcode = X86ISD::FMAX;
15622        break;
15623      case ISD::SETULE:
15624        // Converting this to a max would handle both negative zeros and NaNs
15625        // incorrectly, but we can swap the operands to fix both.
15626        std::swap(LHS, RHS);
15627      case ISD::SETOLT:
15628      case ISD::SETLT:
15629      case ISD::SETLE:
15630        Opcode = X86ISD::FMAX;
15631        break;
15632      }
15633    }
15634
15635    if (Opcode)
15636      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15637  }
15638
15639  // If this is a select between two integer constants, try to do some
15640  // optimizations.
15641  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15642    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15643      // Don't do this for crazy integer types.
15644      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15645        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15646        // so that TrueC (the true value) is larger than FalseC.
15647        bool NeedsCondInvert = false;
15648
15649        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15650            // Efficiently invertible.
15651            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15652             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15653              isa<ConstantSDNode>(Cond.getOperand(1))))) {
15654          NeedsCondInvert = true;
15655          std::swap(TrueC, FalseC);
15656        }
15657
15658        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15659        if (FalseC->getAPIntValue() == 0 &&
15660            TrueC->getAPIntValue().isPowerOf2()) {
15661          if (NeedsCondInvert) // Invert the condition if needed.
15662            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15663                               DAG.getConstant(1, Cond.getValueType()));
15664
15665          // Zero extend the condition if needed.
15666          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15667
15668          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15669          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15670                             DAG.getConstant(ShAmt, MVT::i8));
15671        }
15672
15673        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15674        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15675          if (NeedsCondInvert) // Invert the condition if needed.
15676            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15677                               DAG.getConstant(1, Cond.getValueType()));
15678
15679          // Zero extend the condition if needed.
15680          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15681                             FalseC->getValueType(0), Cond);
15682          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15683                             SDValue(FalseC, 0));
15684        }
15685
15686        // Optimize cases that will turn into an LEA instruction.  This requires
15687        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15688        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15689          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15690          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15691
15692          bool isFastMultiplier = false;
15693          if (Diff < 10) {
15694            switch ((unsigned char)Diff) {
15695              default: break;
15696              case 1:  // result = add base, cond
15697              case 2:  // result = lea base(    , cond*2)
15698              case 3:  // result = lea base(cond, cond*2)
15699              case 4:  // result = lea base(    , cond*4)
15700              case 5:  // result = lea base(cond, cond*4)
15701              case 8:  // result = lea base(    , cond*8)
15702              case 9:  // result = lea base(cond, cond*8)
15703                isFastMultiplier = true;
15704                break;
15705            }
15706          }
15707
15708          if (isFastMultiplier) {
15709            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15710            if (NeedsCondInvert) // Invert the condition if needed.
15711              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15712                                 DAG.getConstant(1, Cond.getValueType()));
15713
15714            // Zero extend the condition if needed.
15715            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15716                               Cond);
15717            // Scale the condition by the difference.
15718            if (Diff != 1)
15719              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15720                                 DAG.getConstant(Diff, Cond.getValueType()));
15721
15722            // Add the base if non-zero.
15723            if (FalseC->getAPIntValue() != 0)
15724              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15725                                 SDValue(FalseC, 0));
15726            return Cond;
15727          }
15728        }
15729      }
15730  }
15731
15732  // Canonicalize max and min:
15733  // (x > y) ? x : y -> (x >= y) ? x : y
15734  // (x < y) ? x : y -> (x <= y) ? x : y
15735  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15736  // the need for an extra compare
15737  // against zero. e.g.
15738  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15739  // subl   %esi, %edi
15740  // testl  %edi, %edi
15741  // movl   $0, %eax
15742  // cmovgl %edi, %eax
15743  // =>
15744  // xorl   %eax, %eax
15745  // subl   %esi, $edi
15746  // cmovsl %eax, %edi
15747  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15748      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15749      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15750    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15751    switch (CC) {
15752    default: break;
15753    case ISD::SETLT:
15754    case ISD::SETGT: {
15755      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15756      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15757                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
15758      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15759    }
15760    }
15761  }
15762
15763  // Match VSELECTs into subs with unsigned saturation.
15764  if (!DCI.isBeforeLegalize() &&
15765      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15766      // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15767      ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15768       (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15769    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15770
15771    // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15772    // left side invert the predicate to simplify logic below.
15773    SDValue Other;
15774    if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15775      Other = RHS;
15776      CC = ISD::getSetCCInverse(CC, true);
15777    } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15778      Other = LHS;
15779    }
15780
15781    if (Other.getNode() && Other->getNumOperands() == 2 &&
15782        DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15783      SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15784      SDValue CondRHS = Cond->getOperand(1);
15785
15786      // Look for a general sub with unsigned saturation first.
15787      // x >= y ? x-y : 0 --> subus x, y
15788      // x >  y ? x-y : 0 --> subus x, y
15789      if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15790          Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15791        return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15792
15793      // If the RHS is a constant we have to reverse the const canonicalization.
15794      // x > C-1 ? x+-C : 0 --> subus x, C
15795      if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15796          isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15797        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15798        if (CondRHS.getConstantOperandVal(0) == -A-1)
15799          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15800                             DAG.getConstant(-A, VT));
15801      }
15802
15803      // Another special case: If C was a sign bit, the sub has been
15804      // canonicalized into a xor.
15805      // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15806      //        it's safe to decanonicalize the xor?
15807      // x s< 0 ? x^C : 0 --> subus x, C
15808      if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15809          ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15810          isSplatVector(OpRHS.getNode())) {
15811        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15812        if (A.isSignBit())
15813          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15814      }
15815    }
15816  }
15817
15818  // Try to match a min/max vector operation.
15819  if (!DCI.isBeforeLegalize() &&
15820      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15821    if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15822      return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15823
15824  // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15825  if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15826      Cond.getOpcode() == ISD::SETCC) {
15827
15828    assert(Cond.getValueType().isVector() &&
15829           "vector select expects a vector selector!");
15830
15831    EVT IntVT = Cond.getValueType();
15832    bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15833    bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15834
15835    if (!TValIsAllOnes && !FValIsAllZeros) {
15836      // Try invert the condition if true value is not all 1s and false value
15837      // is not all 0s.
15838      bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15839      bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15840
15841      if (TValIsAllZeros || FValIsAllOnes) {
15842        SDValue CC = Cond.getOperand(2);
15843        ISD::CondCode NewCC =
15844          ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15845                               Cond.getOperand(0).getValueType().isInteger());
15846        Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15847        std::swap(LHS, RHS);
15848        TValIsAllOnes = FValIsAllOnes;
15849        FValIsAllZeros = TValIsAllZeros;
15850      }
15851    }
15852
15853    if (TValIsAllOnes || FValIsAllZeros) {
15854      SDValue Ret;
15855
15856      if (TValIsAllOnes && FValIsAllZeros)
15857        Ret = Cond;
15858      else if (TValIsAllOnes)
15859        Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15860                          DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15861      else if (FValIsAllZeros)
15862        Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15863                          DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15864
15865      return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15866    }
15867  }
15868
15869  // If we know that this node is legal then we know that it is going to be
15870  // matched by one of the SSE/AVX BLEND instructions. These instructions only
15871  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15872  // to simplify previous instructions.
15873  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15874  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15875      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15876    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15877
15878    // Don't optimize vector selects that map to mask-registers.
15879    if (BitWidth == 1)
15880      return SDValue();
15881
15882    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15883    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15884
15885    APInt KnownZero, KnownOne;
15886    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15887                                          DCI.isBeforeLegalizeOps());
15888    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15889        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15890      DCI.CommitTargetLoweringOpt(TLO);
15891  }
15892
15893  return SDValue();
15894}
15895
15896// Check whether a boolean test is testing a boolean value generated by
15897// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15898// code.
15899//
15900// Simplify the following patterns:
15901// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15902// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15903// to (Op EFLAGS Cond)
15904//
15905// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15906// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15907// to (Op EFLAGS !Cond)
15908//
15909// where Op could be BRCOND or CMOV.
15910//
15911static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15912  // Quit if not CMP and SUB with its value result used.
15913  if (Cmp.getOpcode() != X86ISD::CMP &&
15914      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15915      return SDValue();
15916
15917  // Quit if not used as a boolean value.
15918  if (CC != X86::COND_E && CC != X86::COND_NE)
15919    return SDValue();
15920
15921  // Check CMP operands. One of them should be 0 or 1 and the other should be
15922  // an SetCC or extended from it.
15923  SDValue Op1 = Cmp.getOperand(0);
15924  SDValue Op2 = Cmp.getOperand(1);
15925
15926  SDValue SetCC;
15927  const ConstantSDNode* C = 0;
15928  bool needOppositeCond = (CC == X86::COND_E);
15929  bool checkAgainstTrue = false; // Is it a comparison against 1?
15930
15931  if ((C = dyn_cast<ConstantSDNode>(Op1)))
15932    SetCC = Op2;
15933  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15934    SetCC = Op1;
15935  else // Quit if all operands are not constants.
15936    return SDValue();
15937
15938  if (C->getZExtValue() == 1) {
15939    needOppositeCond = !needOppositeCond;
15940    checkAgainstTrue = true;
15941  } else if (C->getZExtValue() != 0)
15942    // Quit if the constant is neither 0 or 1.
15943    return SDValue();
15944
15945  bool truncatedToBoolWithAnd = false;
15946  // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15947  while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15948         SetCC.getOpcode() == ISD::TRUNCATE ||
15949         SetCC.getOpcode() == ISD::AND) {
15950    if (SetCC.getOpcode() == ISD::AND) {
15951      int OpIdx = -1;
15952      ConstantSDNode *CS;
15953      if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15954          CS->getZExtValue() == 1)
15955        OpIdx = 1;
15956      if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15957          CS->getZExtValue() == 1)
15958        OpIdx = 0;
15959      if (OpIdx == -1)
15960        break;
15961      SetCC = SetCC.getOperand(OpIdx);
15962      truncatedToBoolWithAnd = true;
15963    } else
15964      SetCC = SetCC.getOperand(0);
15965  }
15966
15967  switch (SetCC.getOpcode()) {
15968  case X86ISD::SETCC_CARRY:
15969    // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15970    // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15971    // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15972    // truncated to i1 using 'and'.
15973    if (checkAgainstTrue && !truncatedToBoolWithAnd)
15974      break;
15975    assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15976           "Invalid use of SETCC_CARRY!");
15977    // FALL THROUGH
15978  case X86ISD::SETCC:
15979    // Set the condition code or opposite one if necessary.
15980    CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15981    if (needOppositeCond)
15982      CC = X86::GetOppositeBranchCondition(CC);
15983    return SetCC.getOperand(1);
15984  case X86ISD::CMOV: {
15985    // Check whether false/true value has canonical one, i.e. 0 or 1.
15986    ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15987    ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15988    // Quit if true value is not a constant.
15989    if (!TVal)
15990      return SDValue();
15991    // Quit if false value is not a constant.
15992    if (!FVal) {
15993      SDValue Op = SetCC.getOperand(0);
15994      // Skip 'zext' or 'trunc' node.
15995      if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15996          Op.getOpcode() == ISD::TRUNCATE)
15997        Op = Op.getOperand(0);
15998      // A special case for rdrand/rdseed, where 0 is set if false cond is
15999      // found.
16000      if ((Op.getOpcode() != X86ISD::RDRAND &&
16001           Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16002        return SDValue();
16003    }
16004    // Quit if false value is not the constant 0 or 1.
16005    bool FValIsFalse = true;
16006    if (FVal && FVal->getZExtValue() != 0) {
16007      if (FVal->getZExtValue() != 1)
16008        return SDValue();
16009      // If FVal is 1, opposite cond is needed.
16010      needOppositeCond = !needOppositeCond;
16011      FValIsFalse = false;
16012    }
16013    // Quit if TVal is not the constant opposite of FVal.
16014    if (FValIsFalse && TVal->getZExtValue() != 1)
16015      return SDValue();
16016    if (!FValIsFalse && TVal->getZExtValue() != 0)
16017      return SDValue();
16018    CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16019    if (needOppositeCond)
16020      CC = X86::GetOppositeBranchCondition(CC);
16021    return SetCC.getOperand(3);
16022  }
16023  }
16024
16025  return SDValue();
16026}
16027
16028/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16029static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16030                                  TargetLowering::DAGCombinerInfo &DCI,
16031                                  const X86Subtarget *Subtarget) {
16032  DebugLoc DL = N->getDebugLoc();
16033
16034  // If the flag operand isn't dead, don't touch this CMOV.
16035  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16036    return SDValue();
16037
16038  SDValue FalseOp = N->getOperand(0);
16039  SDValue TrueOp = N->getOperand(1);
16040  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16041  SDValue Cond = N->getOperand(3);
16042
16043  if (CC == X86::COND_E || CC == X86::COND_NE) {
16044    switch (Cond.getOpcode()) {
16045    default: break;
16046    case X86ISD::BSR:
16047    case X86ISD::BSF:
16048      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16049      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16050        return (CC == X86::COND_E) ? FalseOp : TrueOp;
16051    }
16052  }
16053
16054  SDValue Flags;
16055
16056  Flags = checkBoolTestSetCCCombine(Cond, CC);
16057  if (Flags.getNode() &&
16058      // Extra check as FCMOV only supports a subset of X86 cond.
16059      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16060    SDValue Ops[] = { FalseOp, TrueOp,
16061                      DAG.getConstant(CC, MVT::i8), Flags };
16062    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16063                       Ops, array_lengthof(Ops));
16064  }
16065
16066  // If this is a select between two integer constants, try to do some
16067  // optimizations.  Note that the operands are ordered the opposite of SELECT
16068  // operands.
16069  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16070    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16071      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16072      // larger than FalseC (the false value).
16073      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16074        CC = X86::GetOppositeBranchCondition(CC);
16075        std::swap(TrueC, FalseC);
16076        std::swap(TrueOp, FalseOp);
16077      }
16078
16079      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16080      // This is efficient for any integer data type (including i8/i16) and
16081      // shift amount.
16082      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16083        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16084                           DAG.getConstant(CC, MVT::i8), Cond);
16085
16086        // Zero extend the condition if needed.
16087        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16088
16089        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16090        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16091                           DAG.getConstant(ShAmt, MVT::i8));
16092        if (N->getNumValues() == 2)  // Dead flag value?
16093          return DCI.CombineTo(N, Cond, SDValue());
16094        return Cond;
16095      }
16096
16097      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16098      // for any integer data type, including i8/i16.
16099      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16100        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16101                           DAG.getConstant(CC, MVT::i8), Cond);
16102
16103        // Zero extend the condition if needed.
16104        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16105                           FalseC->getValueType(0), Cond);
16106        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16107                           SDValue(FalseC, 0));
16108
16109        if (N->getNumValues() == 2)  // Dead flag value?
16110          return DCI.CombineTo(N, Cond, SDValue());
16111        return Cond;
16112      }
16113
16114      // Optimize cases that will turn into an LEA instruction.  This requires
16115      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16116      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16117        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16118        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16119
16120        bool isFastMultiplier = false;
16121        if (Diff < 10) {
16122          switch ((unsigned char)Diff) {
16123          default: break;
16124          case 1:  // result = add base, cond
16125          case 2:  // result = lea base(    , cond*2)
16126          case 3:  // result = lea base(cond, cond*2)
16127          case 4:  // result = lea base(    , cond*4)
16128          case 5:  // result = lea base(cond, cond*4)
16129          case 8:  // result = lea base(    , cond*8)
16130          case 9:  // result = lea base(cond, cond*8)
16131            isFastMultiplier = true;
16132            break;
16133          }
16134        }
16135
16136        if (isFastMultiplier) {
16137          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16138          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16139                             DAG.getConstant(CC, MVT::i8), Cond);
16140          // Zero extend the condition if needed.
16141          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16142                             Cond);
16143          // Scale the condition by the difference.
16144          if (Diff != 1)
16145            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16146                               DAG.getConstant(Diff, Cond.getValueType()));
16147
16148          // Add the base if non-zero.
16149          if (FalseC->getAPIntValue() != 0)
16150            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16151                               SDValue(FalseC, 0));
16152          if (N->getNumValues() == 2)  // Dead flag value?
16153            return DCI.CombineTo(N, Cond, SDValue());
16154          return Cond;
16155        }
16156      }
16157    }
16158  }
16159
16160  // Handle these cases:
16161  //   (select (x != c), e, c) -> select (x != c), e, x),
16162  //   (select (x == c), c, e) -> select (x == c), x, e)
16163  // where the c is an integer constant, and the "select" is the combination
16164  // of CMOV and CMP.
16165  //
16166  // The rationale for this change is that the conditional-move from a constant
16167  // needs two instructions, however, conditional-move from a register needs
16168  // only one instruction.
16169  //
16170  // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16171  //  some instruction-combining opportunities. This opt needs to be
16172  //  postponed as late as possible.
16173  //
16174  if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16175    // the DCI.xxxx conditions are provided to postpone the optimization as
16176    // late as possible.
16177
16178    ConstantSDNode *CmpAgainst = 0;
16179    if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16180        (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16181        !isa<ConstantSDNode>(Cond.getOperand(0))) {
16182
16183      if (CC == X86::COND_NE &&
16184          CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16185        CC = X86::GetOppositeBranchCondition(CC);
16186        std::swap(TrueOp, FalseOp);
16187      }
16188
16189      if (CC == X86::COND_E &&
16190          CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16191        SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16192                          DAG.getConstant(CC, MVT::i8), Cond };
16193        return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16194                           array_lengthof(Ops));
16195      }
16196    }
16197  }
16198
16199  return SDValue();
16200}
16201
16202/// PerformMulCombine - Optimize a single multiply with constant into two
16203/// in order to implement it with two cheaper instructions, e.g.
16204/// LEA + SHL, LEA + LEA.
16205static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16206                                 TargetLowering::DAGCombinerInfo &DCI) {
16207  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16208    return SDValue();
16209
16210  EVT VT = N->getValueType(0);
16211  if (VT != MVT::i64)
16212    return SDValue();
16213
16214  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16215  if (!C)
16216    return SDValue();
16217  uint64_t MulAmt = C->getZExtValue();
16218  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16219    return SDValue();
16220
16221  uint64_t MulAmt1 = 0;
16222  uint64_t MulAmt2 = 0;
16223  if ((MulAmt % 9) == 0) {
16224    MulAmt1 = 9;
16225    MulAmt2 = MulAmt / 9;
16226  } else if ((MulAmt % 5) == 0) {
16227    MulAmt1 = 5;
16228    MulAmt2 = MulAmt / 5;
16229  } else if ((MulAmt % 3) == 0) {
16230    MulAmt1 = 3;
16231    MulAmt2 = MulAmt / 3;
16232  }
16233  if (MulAmt2 &&
16234      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16235    DebugLoc DL = N->getDebugLoc();
16236
16237    if (isPowerOf2_64(MulAmt2) &&
16238        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16239      // If second multiplifer is pow2, issue it first. We want the multiply by
16240      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16241      // is an add.
16242      std::swap(MulAmt1, MulAmt2);
16243
16244    SDValue NewMul;
16245    if (isPowerOf2_64(MulAmt1))
16246      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16247                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16248    else
16249      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16250                           DAG.getConstant(MulAmt1, VT));
16251
16252    if (isPowerOf2_64(MulAmt2))
16253      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16254                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16255    else
16256      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16257                           DAG.getConstant(MulAmt2, VT));
16258
16259    // Do not add new nodes to DAG combiner worklist.
16260    DCI.CombineTo(N, NewMul, false);
16261  }
16262  return SDValue();
16263}
16264
16265static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16266  SDValue N0 = N->getOperand(0);
16267  SDValue N1 = N->getOperand(1);
16268  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16269  EVT VT = N0.getValueType();
16270
16271  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16272  // since the result of setcc_c is all zero's or all ones.
16273  if (VT.isInteger() && !VT.isVector() &&
16274      N1C && N0.getOpcode() == ISD::AND &&
16275      N0.getOperand(1).getOpcode() == ISD::Constant) {
16276    SDValue N00 = N0.getOperand(0);
16277    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16278        ((N00.getOpcode() == ISD::ANY_EXTEND ||
16279          N00.getOpcode() == ISD::ZERO_EXTEND) &&
16280         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16281      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16282      APInt ShAmt = N1C->getAPIntValue();
16283      Mask = Mask.shl(ShAmt);
16284      if (Mask != 0)
16285        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16286                           N00, DAG.getConstant(Mask, VT));
16287    }
16288  }
16289
16290  // Hardware support for vector shifts is sparse which makes us scalarize the
16291  // vector operations in many cases. Also, on sandybridge ADD is faster than
16292  // shl.
16293  // (shl V, 1) -> add V,V
16294  if (isSplatVector(N1.getNode())) {
16295    assert(N0.getValueType().isVector() && "Invalid vector shift type");
16296    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16297    // We shift all of the values by one. In many cases we do not have
16298    // hardware support for this operation. This is better expressed as an ADD
16299    // of two values.
16300    if (N1C && (1 == N1C->getZExtValue())) {
16301      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16302    }
16303  }
16304
16305  return SDValue();
16306}
16307
16308/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16309///                       when possible.
16310static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16311                                   TargetLowering::DAGCombinerInfo &DCI,
16312                                   const X86Subtarget *Subtarget) {
16313  if (N->getOpcode() == ISD::SHL) {
16314    SDValue V = PerformSHLCombine(N, DAG);
16315    if (V.getNode()) return V;
16316  }
16317
16318  return SDValue();
16319}
16320
16321// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16322// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16323// and friends.  Likewise for OR -> CMPNEQSS.
16324static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16325                            TargetLowering::DAGCombinerInfo &DCI,
16326                            const X86Subtarget *Subtarget) {
16327  unsigned opcode;
16328
16329  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16330  // we're requiring SSE2 for both.
16331  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16332    SDValue N0 = N->getOperand(0);
16333    SDValue N1 = N->getOperand(1);
16334    SDValue CMP0 = N0->getOperand(1);
16335    SDValue CMP1 = N1->getOperand(1);
16336    DebugLoc DL = N->getDebugLoc();
16337
16338    // The SETCCs should both refer to the same CMP.
16339    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16340      return SDValue();
16341
16342    SDValue CMP00 = CMP0->getOperand(0);
16343    SDValue CMP01 = CMP0->getOperand(1);
16344    EVT     VT    = CMP00.getValueType();
16345
16346    if (VT == MVT::f32 || VT == MVT::f64) {
16347      bool ExpectingFlags = false;
16348      // Check for any users that want flags:
16349      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16350           !ExpectingFlags && UI != UE; ++UI)
16351        switch (UI->getOpcode()) {
16352        default:
16353        case ISD::BR_CC:
16354        case ISD::BRCOND:
16355        case ISD::SELECT:
16356          ExpectingFlags = true;
16357          break;
16358        case ISD::CopyToReg:
16359        case ISD::SIGN_EXTEND:
16360        case ISD::ZERO_EXTEND:
16361        case ISD::ANY_EXTEND:
16362          break;
16363        }
16364
16365      if (!ExpectingFlags) {
16366        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16367        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16368
16369        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16370          X86::CondCode tmp = cc0;
16371          cc0 = cc1;
16372          cc1 = tmp;
16373        }
16374
16375        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16376            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16377          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16378          X86ISD::NodeType NTOperator = is64BitFP ?
16379            X86ISD::FSETCCsd : X86ISD::FSETCCss;
16380          // FIXME: need symbolic constants for these magic numbers.
16381          // See X86ATTInstPrinter.cpp:printSSECC().
16382          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16383          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16384                                              DAG.getConstant(x86cc, MVT::i8));
16385          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16386                                              OnesOrZeroesF);
16387          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16388                                      DAG.getConstant(1, MVT::i32));
16389          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16390          return OneBitOfTruth;
16391        }
16392      }
16393    }
16394  }
16395  return SDValue();
16396}
16397
16398/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16399/// so it can be folded inside ANDNP.
16400static bool CanFoldXORWithAllOnes(const SDNode *N) {
16401  EVT VT = N->getValueType(0);
16402
16403  // Match direct AllOnes for 128 and 256-bit vectors
16404  if (ISD::isBuildVectorAllOnes(N))
16405    return true;
16406
16407  // Look through a bit convert.
16408  if (N->getOpcode() == ISD::BITCAST)
16409    N = N->getOperand(0).getNode();
16410
16411  // Sometimes the operand may come from a insert_subvector building a 256-bit
16412  // allones vector
16413  if (VT.is256BitVector() &&
16414      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16415    SDValue V1 = N->getOperand(0);
16416    SDValue V2 = N->getOperand(1);
16417
16418    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16419        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16420        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16421        ISD::isBuildVectorAllOnes(V2.getNode()))
16422      return true;
16423  }
16424
16425  return false;
16426}
16427
16428// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16429// register. In most cases we actually compare or select YMM-sized registers
16430// and mixing the two types creates horrible code. This method optimizes
16431// some of the transition sequences.
16432static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16433                                 TargetLowering::DAGCombinerInfo &DCI,
16434                                 const X86Subtarget *Subtarget) {
16435  EVT VT = N->getValueType(0);
16436  if (!VT.is256BitVector())
16437    return SDValue();
16438
16439  assert((N->getOpcode() == ISD::ANY_EXTEND ||
16440          N->getOpcode() == ISD::ZERO_EXTEND ||
16441          N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16442
16443  SDValue Narrow = N->getOperand(0);
16444  EVT NarrowVT = Narrow->getValueType(0);
16445  if (!NarrowVT.is128BitVector())
16446    return SDValue();
16447
16448  if (Narrow->getOpcode() != ISD::XOR &&
16449      Narrow->getOpcode() != ISD::AND &&
16450      Narrow->getOpcode() != ISD::OR)
16451    return SDValue();
16452
16453  SDValue N0  = Narrow->getOperand(0);
16454  SDValue N1  = Narrow->getOperand(1);
16455  DebugLoc DL = Narrow->getDebugLoc();
16456
16457  // The Left side has to be a trunc.
16458  if (N0.getOpcode() != ISD::TRUNCATE)
16459    return SDValue();
16460
16461  // The type of the truncated inputs.
16462  EVT WideVT = N0->getOperand(0)->getValueType(0);
16463  if (WideVT != VT)
16464    return SDValue();
16465
16466  // The right side has to be a 'trunc' or a constant vector.
16467  bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16468  bool RHSConst = (isSplatVector(N1.getNode()) &&
16469                   isa<ConstantSDNode>(N1->getOperand(0)));
16470  if (!RHSTrunc && !RHSConst)
16471    return SDValue();
16472
16473  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16474
16475  if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16476    return SDValue();
16477
16478  // Set N0 and N1 to hold the inputs to the new wide operation.
16479  N0 = N0->getOperand(0);
16480  if (RHSConst) {
16481    N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16482                     N1->getOperand(0));
16483    SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16484    N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16485  } else if (RHSTrunc) {
16486    N1 = N1->getOperand(0);
16487  }
16488
16489  // Generate the wide operation.
16490  SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16491  unsigned Opcode = N->getOpcode();
16492  switch (Opcode) {
16493  case ISD::ANY_EXTEND:
16494    return Op;
16495  case ISD::ZERO_EXTEND: {
16496    unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16497    APInt Mask = APInt::getAllOnesValue(InBits);
16498    Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16499    return DAG.getNode(ISD::AND, DL, VT,
16500                       Op, DAG.getConstant(Mask, VT));
16501  }
16502  case ISD::SIGN_EXTEND:
16503    return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16504                       Op, DAG.getValueType(NarrowVT));
16505  default:
16506    llvm_unreachable("Unexpected opcode");
16507  }
16508}
16509
16510static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16511                                 TargetLowering::DAGCombinerInfo &DCI,
16512                                 const X86Subtarget *Subtarget) {
16513  EVT VT = N->getValueType(0);
16514  if (DCI.isBeforeLegalizeOps())
16515    return SDValue();
16516
16517  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16518  if (R.getNode())
16519    return R;
16520
16521  // Create BLSI, and BLSR instructions
16522  // BLSI is X & (-X)
16523  // BLSR is X & (X-1)
16524  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16525    SDValue N0 = N->getOperand(0);
16526    SDValue N1 = N->getOperand(1);
16527    DebugLoc DL = N->getDebugLoc();
16528
16529    // Check LHS for neg
16530    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16531        isZero(N0.getOperand(0)))
16532      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16533
16534    // Check RHS for neg
16535    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16536        isZero(N1.getOperand(0)))
16537      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16538
16539    // Check LHS for X-1
16540    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16541        isAllOnes(N0.getOperand(1)))
16542      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16543
16544    // Check RHS for X-1
16545    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16546        isAllOnes(N1.getOperand(1)))
16547      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16548
16549    return SDValue();
16550  }
16551
16552  // Want to form ANDNP nodes:
16553  // 1) In the hopes of then easily combining them with OR and AND nodes
16554  //    to form PBLEND/PSIGN.
16555  // 2) To match ANDN packed intrinsics
16556  if (VT != MVT::v2i64 && VT != MVT::v4i64)
16557    return SDValue();
16558
16559  SDValue N0 = N->getOperand(0);
16560  SDValue N1 = N->getOperand(1);
16561  DebugLoc DL = N->getDebugLoc();
16562
16563  // Check LHS for vnot
16564  if (N0.getOpcode() == ISD::XOR &&
16565      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16566      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16567    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16568
16569  // Check RHS for vnot
16570  if (N1.getOpcode() == ISD::XOR &&
16571      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16572      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16573    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16574
16575  return SDValue();
16576}
16577
16578static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16579                                TargetLowering::DAGCombinerInfo &DCI,
16580                                const X86Subtarget *Subtarget) {
16581  EVT VT = N->getValueType(0);
16582  if (DCI.isBeforeLegalizeOps())
16583    return SDValue();
16584
16585  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16586  if (R.getNode())
16587    return R;
16588
16589  SDValue N0 = N->getOperand(0);
16590  SDValue N1 = N->getOperand(1);
16591
16592  // look for psign/blend
16593  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16594    if (!Subtarget->hasSSSE3() ||
16595        (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16596      return SDValue();
16597
16598    // Canonicalize pandn to RHS
16599    if (N0.getOpcode() == X86ISD::ANDNP)
16600      std::swap(N0, N1);
16601    // or (and (m, y), (pandn m, x))
16602    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16603      SDValue Mask = N1.getOperand(0);
16604      SDValue X    = N1.getOperand(1);
16605      SDValue Y;
16606      if (N0.getOperand(0) == Mask)
16607        Y = N0.getOperand(1);
16608      if (N0.getOperand(1) == Mask)
16609        Y = N0.getOperand(0);
16610
16611      // Check to see if the mask appeared in both the AND and ANDNP and
16612      if (!Y.getNode())
16613        return SDValue();
16614
16615      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16616      // Look through mask bitcast.
16617      if (Mask.getOpcode() == ISD::BITCAST)
16618        Mask = Mask.getOperand(0);
16619      if (X.getOpcode() == ISD::BITCAST)
16620        X = X.getOperand(0);
16621      if (Y.getOpcode() == ISD::BITCAST)
16622        Y = Y.getOperand(0);
16623
16624      EVT MaskVT = Mask.getValueType();
16625
16626      // Validate that the Mask operand is a vector sra node.
16627      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16628      // there is no psrai.b
16629      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16630      unsigned SraAmt = ~0;
16631      if (Mask.getOpcode() == ISD::SRA) {
16632        SDValue Amt = Mask.getOperand(1);
16633        if (isSplatVector(Amt.getNode())) {
16634          SDValue SclrAmt = Amt->getOperand(0);
16635          if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16636            SraAmt = C->getZExtValue();
16637        }
16638      } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16639        SDValue SraC = Mask.getOperand(1);
16640        SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16641      }
16642      if ((SraAmt + 1) != EltBits)
16643        return SDValue();
16644
16645      DebugLoc DL = N->getDebugLoc();
16646
16647      // Now we know we at least have a plendvb with the mask val.  See if
16648      // we can form a psignb/w/d.
16649      // psign = x.type == y.type == mask.type && y = sub(0, x);
16650      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16651          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16652          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16653        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16654               "Unsupported VT for PSIGN");
16655        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16656        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16657      }
16658      // PBLENDVB only available on SSE 4.1
16659      if (!Subtarget->hasSSE41())
16660        return SDValue();
16661
16662      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16663
16664      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16665      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16666      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16667      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16668      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16669    }
16670  }
16671
16672  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16673    return SDValue();
16674
16675  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16676  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16677    std::swap(N0, N1);
16678  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16679    return SDValue();
16680  if (!N0.hasOneUse() || !N1.hasOneUse())
16681    return SDValue();
16682
16683  SDValue ShAmt0 = N0.getOperand(1);
16684  if (ShAmt0.getValueType() != MVT::i8)
16685    return SDValue();
16686  SDValue ShAmt1 = N1.getOperand(1);
16687  if (ShAmt1.getValueType() != MVT::i8)
16688    return SDValue();
16689  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16690    ShAmt0 = ShAmt0.getOperand(0);
16691  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16692    ShAmt1 = ShAmt1.getOperand(0);
16693
16694  DebugLoc DL = N->getDebugLoc();
16695  unsigned Opc = X86ISD::SHLD;
16696  SDValue Op0 = N0.getOperand(0);
16697  SDValue Op1 = N1.getOperand(0);
16698  if (ShAmt0.getOpcode() == ISD::SUB) {
16699    Opc = X86ISD::SHRD;
16700    std::swap(Op0, Op1);
16701    std::swap(ShAmt0, ShAmt1);
16702  }
16703
16704  unsigned Bits = VT.getSizeInBits();
16705  if (ShAmt1.getOpcode() == ISD::SUB) {
16706    SDValue Sum = ShAmt1.getOperand(0);
16707    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16708      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16709      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16710        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16711      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16712        return DAG.getNode(Opc, DL, VT,
16713                           Op0, Op1,
16714                           DAG.getNode(ISD::TRUNCATE, DL,
16715                                       MVT::i8, ShAmt0));
16716    }
16717  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16718    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16719    if (ShAmt0C &&
16720        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16721      return DAG.getNode(Opc, DL, VT,
16722                         N0.getOperand(0), N1.getOperand(0),
16723                         DAG.getNode(ISD::TRUNCATE, DL,
16724                                       MVT::i8, ShAmt0));
16725  }
16726
16727  return SDValue();
16728}
16729
16730// Generate NEG and CMOV for integer abs.
16731static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16732  EVT VT = N->getValueType(0);
16733
16734  // Since X86 does not have CMOV for 8-bit integer, we don't convert
16735  // 8-bit integer abs to NEG and CMOV.
16736  if (VT.isInteger() && VT.getSizeInBits() == 8)
16737    return SDValue();
16738
16739  SDValue N0 = N->getOperand(0);
16740  SDValue N1 = N->getOperand(1);
16741  DebugLoc DL = N->getDebugLoc();
16742
16743  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16744  // and change it to SUB and CMOV.
16745  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16746      N0.getOpcode() == ISD::ADD &&
16747      N0.getOperand(1) == N1 &&
16748      N1.getOpcode() == ISD::SRA &&
16749      N1.getOperand(0) == N0.getOperand(0))
16750    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16751      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16752        // Generate SUB & CMOV.
16753        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16754                                  DAG.getConstant(0, VT), N0.getOperand(0));
16755
16756        SDValue Ops[] = { N0.getOperand(0), Neg,
16757                          DAG.getConstant(X86::COND_GE, MVT::i8),
16758                          SDValue(Neg.getNode(), 1) };
16759        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16760                           Ops, array_lengthof(Ops));
16761      }
16762  return SDValue();
16763}
16764
16765// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16766static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16767                                 TargetLowering::DAGCombinerInfo &DCI,
16768                                 const X86Subtarget *Subtarget) {
16769  EVT VT = N->getValueType(0);
16770  if (DCI.isBeforeLegalizeOps())
16771    return SDValue();
16772
16773  if (Subtarget->hasCMov()) {
16774    SDValue RV = performIntegerAbsCombine(N, DAG);
16775    if (RV.getNode())
16776      return RV;
16777  }
16778
16779  // Try forming BMI if it is available.
16780  if (!Subtarget->hasBMI())
16781    return SDValue();
16782
16783  if (VT != MVT::i32 && VT != MVT::i64)
16784    return SDValue();
16785
16786  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16787
16788  // Create BLSMSK instructions by finding X ^ (X-1)
16789  SDValue N0 = N->getOperand(0);
16790  SDValue N1 = N->getOperand(1);
16791  DebugLoc DL = N->getDebugLoc();
16792
16793  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16794      isAllOnes(N0.getOperand(1)))
16795    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16796
16797  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16798      isAllOnes(N1.getOperand(1)))
16799    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16800
16801  return SDValue();
16802}
16803
16804/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16805static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16806                                  TargetLowering::DAGCombinerInfo &DCI,
16807                                  const X86Subtarget *Subtarget) {
16808  LoadSDNode *Ld = cast<LoadSDNode>(N);
16809  EVT RegVT = Ld->getValueType(0);
16810  EVT MemVT = Ld->getMemoryVT();
16811  DebugLoc dl = Ld->getDebugLoc();
16812  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16813  unsigned RegSz = RegVT.getSizeInBits();
16814
16815  // On Sandybridge unaligned 256bit loads are inefficient.
16816  ISD::LoadExtType Ext = Ld->getExtensionType();
16817  unsigned Alignment = Ld->getAlignment();
16818  bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16819  if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16820      !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16821    unsigned NumElems = RegVT.getVectorNumElements();
16822    if (NumElems < 2)
16823      return SDValue();
16824
16825    SDValue Ptr = Ld->getBasePtr();
16826    SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16827
16828    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16829                                  NumElems/2);
16830    SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16831                                Ld->getPointerInfo(), Ld->isVolatile(),
16832                                Ld->isNonTemporal(), Ld->isInvariant(),
16833                                Alignment);
16834    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16835    SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16836                                Ld->getPointerInfo(), Ld->isVolatile(),
16837                                Ld->isNonTemporal(), Ld->isInvariant(),
16838                                std::min(16U, Alignment));
16839    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16840                             Load1.getValue(1),
16841                             Load2.getValue(1));
16842
16843    SDValue NewVec = DAG.getUNDEF(RegVT);
16844    NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16845    NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16846    return DCI.CombineTo(N, NewVec, TF, true);
16847  }
16848
16849  // If this is a vector EXT Load then attempt to optimize it using a
16850  // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16851  // expansion is still better than scalar code.
16852  // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16853  // emit a shuffle and a arithmetic shift.
16854  // TODO: It is possible to support ZExt by zeroing the undef values
16855  // during the shuffle phase or after the shuffle.
16856  if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16857      (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16858    assert(MemVT != RegVT && "Cannot extend to the same type");
16859    assert(MemVT.isVector() && "Must load a vector from memory");
16860
16861    unsigned NumElems = RegVT.getVectorNumElements();
16862    unsigned MemSz = MemVT.getSizeInBits();
16863    assert(RegSz > MemSz && "Register size must be greater than the mem size");
16864
16865    if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16866      return SDValue();
16867
16868    // All sizes must be a power of two.
16869    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16870      return SDValue();
16871
16872    // Attempt to load the original value using scalar loads.
16873    // Find the largest scalar type that divides the total loaded size.
16874    MVT SclrLoadTy = MVT::i8;
16875    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16876         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16877      MVT Tp = (MVT::SimpleValueType)tp;
16878      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16879        SclrLoadTy = Tp;
16880      }
16881    }
16882
16883    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16884    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16885        (64 <= MemSz))
16886      SclrLoadTy = MVT::f64;
16887
16888    // Calculate the number of scalar loads that we need to perform
16889    // in order to load our vector from memory.
16890    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16891    if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16892      return SDValue();
16893
16894    unsigned loadRegZize = RegSz;
16895    if (Ext == ISD::SEXTLOAD && RegSz == 256)
16896      loadRegZize /= 2;
16897
16898    // Represent our vector as a sequence of elements which are the
16899    // largest scalar that we can load.
16900    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16901      loadRegZize/SclrLoadTy.getSizeInBits());
16902
16903    // Represent the data using the same element type that is stored in
16904    // memory. In practice, we ''widen'' MemVT.
16905    EVT WideVecVT =
16906          EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16907                       loadRegZize/MemVT.getScalarType().getSizeInBits());
16908
16909    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16910      "Invalid vector type");
16911
16912    // We can't shuffle using an illegal type.
16913    if (!TLI.isTypeLegal(WideVecVT))
16914      return SDValue();
16915
16916    SmallVector<SDValue, 8> Chains;
16917    SDValue Ptr = Ld->getBasePtr();
16918    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16919                                        TLI.getPointerTy());
16920    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16921
16922    for (unsigned i = 0; i < NumLoads; ++i) {
16923      // Perform a single load.
16924      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16925                                       Ptr, Ld->getPointerInfo(),
16926                                       Ld->isVolatile(), Ld->isNonTemporal(),
16927                                       Ld->isInvariant(), Ld->getAlignment());
16928      Chains.push_back(ScalarLoad.getValue(1));
16929      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16930      // another round of DAGCombining.
16931      if (i == 0)
16932        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16933      else
16934        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16935                          ScalarLoad, DAG.getIntPtrConstant(i));
16936
16937      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16938    }
16939
16940    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16941                               Chains.size());
16942
16943    // Bitcast the loaded value to a vector of the original element type, in
16944    // the size of the target vector type.
16945    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16946    unsigned SizeRatio = RegSz/MemSz;
16947
16948    if (Ext == ISD::SEXTLOAD) {
16949      // If we have SSE4.1 we can directly emit a VSEXT node.
16950      if (Subtarget->hasSSE41()) {
16951        SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16952        return DCI.CombineTo(N, Sext, TF, true);
16953      }
16954
16955      // Otherwise we'll shuffle the small elements in the high bits of the
16956      // larger type and perform an arithmetic shift. If the shift is not legal
16957      // it's better to scalarize.
16958      if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16959        return SDValue();
16960
16961      // Redistribute the loaded elements into the different locations.
16962      SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16963      for (unsigned i = 0; i != NumElems; ++i)
16964        ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16965
16966      SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16967                                           DAG.getUNDEF(WideVecVT),
16968                                           &ShuffleVec[0]);
16969
16970      Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16971
16972      // Build the arithmetic shift.
16973      unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16974                     MemVT.getVectorElementType().getSizeInBits();
16975      Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16976                          DAG.getConstant(Amt, RegVT));
16977
16978      return DCI.CombineTo(N, Shuff, TF, true);
16979    }
16980
16981    // Redistribute the loaded elements into the different locations.
16982    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16983    for (unsigned i = 0; i != NumElems; ++i)
16984      ShuffleVec[i*SizeRatio] = i;
16985
16986    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16987                                         DAG.getUNDEF(WideVecVT),
16988                                         &ShuffleVec[0]);
16989
16990    // Bitcast to the requested type.
16991    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16992    // Replace the original load with the new sequence
16993    // and return the new chain.
16994    return DCI.CombineTo(N, Shuff, TF, true);
16995  }
16996
16997  return SDValue();
16998}
16999
17000/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17001static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17002                                   const X86Subtarget *Subtarget) {
17003  StoreSDNode *St = cast<StoreSDNode>(N);
17004  EVT VT = St->getValue().getValueType();
17005  EVT StVT = St->getMemoryVT();
17006  DebugLoc dl = St->getDebugLoc();
17007  SDValue StoredVal = St->getOperand(1);
17008  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17009
17010  // If we are saving a concatenation of two XMM registers, perform two stores.
17011  // On Sandy Bridge, 256-bit memory operations are executed by two
17012  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17013  // memory  operation.
17014  unsigned Alignment = St->getAlignment();
17015  bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17016  if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17017      StVT == VT && !IsAligned) {
17018    unsigned NumElems = VT.getVectorNumElements();
17019    if (NumElems < 2)
17020      return SDValue();
17021
17022    SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17023    SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17024
17025    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17026    SDValue Ptr0 = St->getBasePtr();
17027    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17028
17029    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17030                                St->getPointerInfo(), St->isVolatile(),
17031                                St->isNonTemporal(), Alignment);
17032    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17033                                St->getPointerInfo(), St->isVolatile(),
17034                                St->isNonTemporal(),
17035                                std::min(16U, Alignment));
17036    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17037  }
17038
17039  // Optimize trunc store (of multiple scalars) to shuffle and store.
17040  // First, pack all of the elements in one place. Next, store to memory
17041  // in fewer chunks.
17042  if (St->isTruncatingStore() && VT.isVector()) {
17043    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17044    unsigned NumElems = VT.getVectorNumElements();
17045    assert(StVT != VT && "Cannot truncate to the same type");
17046    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17047    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17048
17049    // From, To sizes and ElemCount must be pow of two
17050    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17051    // We are going to use the original vector elt for storing.
17052    // Accumulated smaller vector elements must be a multiple of the store size.
17053    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17054
17055    unsigned SizeRatio  = FromSz / ToSz;
17056
17057    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17058
17059    // Create a type on which we perform the shuffle
17060    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17061            StVT.getScalarType(), NumElems*SizeRatio);
17062
17063    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17064
17065    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17066    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17067    for (unsigned i = 0; i != NumElems; ++i)
17068      ShuffleVec[i] = i * SizeRatio;
17069
17070    // Can't shuffle using an illegal type.
17071    if (!TLI.isTypeLegal(WideVecVT))
17072      return SDValue();
17073
17074    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17075                                         DAG.getUNDEF(WideVecVT),
17076                                         &ShuffleVec[0]);
17077    // At this point all of the data is stored at the bottom of the
17078    // register. We now need to save it to mem.
17079
17080    // Find the largest store unit
17081    MVT StoreType = MVT::i8;
17082    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17083         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17084      MVT Tp = (MVT::SimpleValueType)tp;
17085      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17086        StoreType = Tp;
17087    }
17088
17089    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17090    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17091        (64 <= NumElems * ToSz))
17092      StoreType = MVT::f64;
17093
17094    // Bitcast the original vector into a vector of store-size units
17095    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17096            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17097    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17098    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17099    SmallVector<SDValue, 8> Chains;
17100    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17101                                        TLI.getPointerTy());
17102    SDValue Ptr = St->getBasePtr();
17103
17104    // Perform one or more big stores into memory.
17105    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17106      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17107                                   StoreType, ShuffWide,
17108                                   DAG.getIntPtrConstant(i));
17109      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17110                                St->getPointerInfo(), St->isVolatile(),
17111                                St->isNonTemporal(), St->getAlignment());
17112      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17113      Chains.push_back(Ch);
17114    }
17115
17116    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17117                               Chains.size());
17118  }
17119
17120  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17121  // the FP state in cases where an emms may be missing.
17122  // A preferable solution to the general problem is to figure out the right
17123  // places to insert EMMS.  This qualifies as a quick hack.
17124
17125  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17126  if (VT.getSizeInBits() != 64)
17127    return SDValue();
17128
17129  const Function *F = DAG.getMachineFunction().getFunction();
17130  bool NoImplicitFloatOps = F->getAttributes().
17131    hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17132  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17133                     && Subtarget->hasSSE2();
17134  if ((VT.isVector() ||
17135       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17136      isa<LoadSDNode>(St->getValue()) &&
17137      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17138      St->getChain().hasOneUse() && !St->isVolatile()) {
17139    SDNode* LdVal = St->getValue().getNode();
17140    LoadSDNode *Ld = 0;
17141    int TokenFactorIndex = -1;
17142    SmallVector<SDValue, 8> Ops;
17143    SDNode* ChainVal = St->getChain().getNode();
17144    // Must be a store of a load.  We currently handle two cases:  the load
17145    // is a direct child, and it's under an intervening TokenFactor.  It is
17146    // possible to dig deeper under nested TokenFactors.
17147    if (ChainVal == LdVal)
17148      Ld = cast<LoadSDNode>(St->getChain());
17149    else if (St->getValue().hasOneUse() &&
17150             ChainVal->getOpcode() == ISD::TokenFactor) {
17151      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17152        if (ChainVal->getOperand(i).getNode() == LdVal) {
17153          TokenFactorIndex = i;
17154          Ld = cast<LoadSDNode>(St->getValue());
17155        } else
17156          Ops.push_back(ChainVal->getOperand(i));
17157      }
17158    }
17159
17160    if (!Ld || !ISD::isNormalLoad(Ld))
17161      return SDValue();
17162
17163    // If this is not the MMX case, i.e. we are just turning i64 load/store
17164    // into f64 load/store, avoid the transformation if there are multiple
17165    // uses of the loaded value.
17166    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17167      return SDValue();
17168
17169    DebugLoc LdDL = Ld->getDebugLoc();
17170    DebugLoc StDL = N->getDebugLoc();
17171    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17172    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17173    // pair instead.
17174    if (Subtarget->is64Bit() || F64IsLegal) {
17175      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17176      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17177                                  Ld->getPointerInfo(), Ld->isVolatile(),
17178                                  Ld->isNonTemporal(), Ld->isInvariant(),
17179                                  Ld->getAlignment());
17180      SDValue NewChain = NewLd.getValue(1);
17181      if (TokenFactorIndex != -1) {
17182        Ops.push_back(NewChain);
17183        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17184                               Ops.size());
17185      }
17186      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17187                          St->getPointerInfo(),
17188                          St->isVolatile(), St->isNonTemporal(),
17189                          St->getAlignment());
17190    }
17191
17192    // Otherwise, lower to two pairs of 32-bit loads / stores.
17193    SDValue LoAddr = Ld->getBasePtr();
17194    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17195                                 DAG.getConstant(4, MVT::i32));
17196
17197    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17198                               Ld->getPointerInfo(),
17199                               Ld->isVolatile(), Ld->isNonTemporal(),
17200                               Ld->isInvariant(), Ld->getAlignment());
17201    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17202                               Ld->getPointerInfo().getWithOffset(4),
17203                               Ld->isVolatile(), Ld->isNonTemporal(),
17204                               Ld->isInvariant(),
17205                               MinAlign(Ld->getAlignment(), 4));
17206
17207    SDValue NewChain = LoLd.getValue(1);
17208    if (TokenFactorIndex != -1) {
17209      Ops.push_back(LoLd);
17210      Ops.push_back(HiLd);
17211      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17212                             Ops.size());
17213    }
17214
17215    LoAddr = St->getBasePtr();
17216    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17217                         DAG.getConstant(4, MVT::i32));
17218
17219    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17220                                St->getPointerInfo(),
17221                                St->isVolatile(), St->isNonTemporal(),
17222                                St->getAlignment());
17223    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17224                                St->getPointerInfo().getWithOffset(4),
17225                                St->isVolatile(),
17226                                St->isNonTemporal(),
17227                                MinAlign(St->getAlignment(), 4));
17228    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17229  }
17230  return SDValue();
17231}
17232
17233/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17234/// and return the operands for the horizontal operation in LHS and RHS.  A
17235/// horizontal operation performs the binary operation on successive elements
17236/// of its first operand, then on successive elements of its second operand,
17237/// returning the resulting values in a vector.  For example, if
17238///   A = < float a0, float a1, float a2, float a3 >
17239/// and
17240///   B = < float b0, float b1, float b2, float b3 >
17241/// then the result of doing a horizontal operation on A and B is
17242///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17243/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17244/// A horizontal-op B, for some already available A and B, and if so then LHS is
17245/// set to A, RHS to B, and the routine returns 'true'.
17246/// Note that the binary operation should have the property that if one of the
17247/// operands is UNDEF then the result is UNDEF.
17248static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17249  // Look for the following pattern: if
17250  //   A = < float a0, float a1, float a2, float a3 >
17251  //   B = < float b0, float b1, float b2, float b3 >
17252  // and
17253  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17254  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17255  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17256  // which is A horizontal-op B.
17257
17258  // At least one of the operands should be a vector shuffle.
17259  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17260      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17261    return false;
17262
17263  EVT VT = LHS.getValueType();
17264
17265  assert((VT.is128BitVector() || VT.is256BitVector()) &&
17266         "Unsupported vector type for horizontal add/sub");
17267
17268  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17269  // operate independently on 128-bit lanes.
17270  unsigned NumElts = VT.getVectorNumElements();
17271  unsigned NumLanes = VT.getSizeInBits()/128;
17272  unsigned NumLaneElts = NumElts / NumLanes;
17273  assert((NumLaneElts % 2 == 0) &&
17274         "Vector type should have an even number of elements in each lane");
17275  unsigned HalfLaneElts = NumLaneElts/2;
17276
17277  // View LHS in the form
17278  //   LHS = VECTOR_SHUFFLE A, B, LMask
17279  // If LHS is not a shuffle then pretend it is the shuffle
17280  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17281  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17282  // type VT.
17283  SDValue A, B;
17284  SmallVector<int, 16> LMask(NumElts);
17285  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17286    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17287      A = LHS.getOperand(0);
17288    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17289      B = LHS.getOperand(1);
17290    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17291    std::copy(Mask.begin(), Mask.end(), LMask.begin());
17292  } else {
17293    if (LHS.getOpcode() != ISD::UNDEF)
17294      A = LHS;
17295    for (unsigned i = 0; i != NumElts; ++i)
17296      LMask[i] = i;
17297  }
17298
17299  // Likewise, view RHS in the form
17300  //   RHS = VECTOR_SHUFFLE C, D, RMask
17301  SDValue C, D;
17302  SmallVector<int, 16> RMask(NumElts);
17303  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17304    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17305      C = RHS.getOperand(0);
17306    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17307      D = RHS.getOperand(1);
17308    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17309    std::copy(Mask.begin(), Mask.end(), RMask.begin());
17310  } else {
17311    if (RHS.getOpcode() != ISD::UNDEF)
17312      C = RHS;
17313    for (unsigned i = 0; i != NumElts; ++i)
17314      RMask[i] = i;
17315  }
17316
17317  // Check that the shuffles are both shuffling the same vectors.
17318  if (!(A == C && B == D) && !(A == D && B == C))
17319    return false;
17320
17321  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17322  if (!A.getNode() && !B.getNode())
17323    return false;
17324
17325  // If A and B occur in reverse order in RHS, then "swap" them (which means
17326  // rewriting the mask).
17327  if (A != C)
17328    CommuteVectorShuffleMask(RMask, NumElts);
17329
17330  // At this point LHS and RHS are equivalent to
17331  //   LHS = VECTOR_SHUFFLE A, B, LMask
17332  //   RHS = VECTOR_SHUFFLE A, B, RMask
17333  // Check that the masks correspond to performing a horizontal operation.
17334  for (unsigned i = 0; i != NumElts; ++i) {
17335    int LIdx = LMask[i], RIdx = RMask[i];
17336
17337    // Ignore any UNDEF components.
17338    if (LIdx < 0 || RIdx < 0 ||
17339        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17340        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17341      continue;
17342
17343    // Check that successive elements are being operated on.  If not, this is
17344    // not a horizontal operation.
17345    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17346    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17347    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17348    if (!(LIdx == Index && RIdx == Index + 1) &&
17349        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17350      return false;
17351  }
17352
17353  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17354  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17355  return true;
17356}
17357
17358/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17359static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17360                                  const X86Subtarget *Subtarget) {
17361  EVT VT = N->getValueType(0);
17362  SDValue LHS = N->getOperand(0);
17363  SDValue RHS = N->getOperand(1);
17364
17365  // Try to synthesize horizontal adds from adds of shuffles.
17366  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17367       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17368      isHorizontalBinOp(LHS, RHS, true))
17369    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17370  return SDValue();
17371}
17372
17373/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17374static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17375                                  const X86Subtarget *Subtarget) {
17376  EVT VT = N->getValueType(0);
17377  SDValue LHS = N->getOperand(0);
17378  SDValue RHS = N->getOperand(1);
17379
17380  // Try to synthesize horizontal subs from subs of shuffles.
17381  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17382       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17383      isHorizontalBinOp(LHS, RHS, false))
17384    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17385  return SDValue();
17386}
17387
17388/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17389/// X86ISD::FXOR nodes.
17390static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17391  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17392  // F[X]OR(0.0, x) -> x
17393  // F[X]OR(x, 0.0) -> x
17394  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17395    if (C->getValueAPF().isPosZero())
17396      return N->getOperand(1);
17397  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17398    if (C->getValueAPF().isPosZero())
17399      return N->getOperand(0);
17400  return SDValue();
17401}
17402
17403/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17404/// X86ISD::FMAX nodes.
17405static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17406  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17407
17408  // Only perform optimizations if UnsafeMath is used.
17409  if (!DAG.getTarget().Options.UnsafeFPMath)
17410    return SDValue();
17411
17412  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17413  // into FMINC and FMAXC, which are Commutative operations.
17414  unsigned NewOp = 0;
17415  switch (N->getOpcode()) {
17416    default: llvm_unreachable("unknown opcode");
17417    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17418    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17419  }
17420
17421  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17422                     N->getOperand(0), N->getOperand(1));
17423}
17424
17425/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17426static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17427  // FAND(0.0, x) -> 0.0
17428  // FAND(x, 0.0) -> 0.0
17429  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17430    if (C->getValueAPF().isPosZero())
17431      return N->getOperand(0);
17432  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17433    if (C->getValueAPF().isPosZero())
17434      return N->getOperand(1);
17435  return SDValue();
17436}
17437
17438static SDValue PerformBTCombine(SDNode *N,
17439                                SelectionDAG &DAG,
17440                                TargetLowering::DAGCombinerInfo &DCI) {
17441  // BT ignores high bits in the bit index operand.
17442  SDValue Op1 = N->getOperand(1);
17443  if (Op1.hasOneUse()) {
17444    unsigned BitWidth = Op1.getValueSizeInBits();
17445    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17446    APInt KnownZero, KnownOne;
17447    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17448                                          !DCI.isBeforeLegalizeOps());
17449    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17450    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17451        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17452      DCI.CommitTargetLoweringOpt(TLO);
17453  }
17454  return SDValue();
17455}
17456
17457static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17458  SDValue Op = N->getOperand(0);
17459  if (Op.getOpcode() == ISD::BITCAST)
17460    Op = Op.getOperand(0);
17461  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17462  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17463      VT.getVectorElementType().getSizeInBits() ==
17464      OpVT.getVectorElementType().getSizeInBits()) {
17465    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17466  }
17467  return SDValue();
17468}
17469
17470static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17471                                               const X86Subtarget *Subtarget) {
17472  EVT VT = N->getValueType(0);
17473  if (!VT.isVector())
17474    return SDValue();
17475
17476  SDValue N0 = N->getOperand(0);
17477  SDValue N1 = N->getOperand(1);
17478  EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17479  DebugLoc dl = N->getDebugLoc();
17480
17481  // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17482  // both SSE and AVX2 since there is no sign-extended shift right
17483  // operation on a vector with 64-bit elements.
17484  //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17485  // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17486  if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17487      N0.getOpcode() == ISD::SIGN_EXTEND)) {
17488    SDValue N00 = N0.getOperand(0);
17489
17490    // EXTLOAD has a better solution on AVX2,
17491    // it may be replaced with X86ISD::VSEXT node.
17492    if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17493      if (!ISD::isNormalLoad(N00.getNode()))
17494        return SDValue();
17495
17496    if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17497        SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17498                                  N00, N1);
17499      return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17500    }
17501  }
17502  return SDValue();
17503}
17504
17505static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17506                                  TargetLowering::DAGCombinerInfo &DCI,
17507                                  const X86Subtarget *Subtarget) {
17508  if (!DCI.isBeforeLegalizeOps())
17509    return SDValue();
17510
17511  if (!Subtarget->hasFp256())
17512    return SDValue();
17513
17514  EVT VT = N->getValueType(0);
17515  if (VT.isVector() && VT.getSizeInBits() == 256) {
17516    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17517    if (R.getNode())
17518      return R;
17519  }
17520
17521  return SDValue();
17522}
17523
17524static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17525                                 const X86Subtarget* Subtarget) {
17526  DebugLoc dl = N->getDebugLoc();
17527  EVT VT = N->getValueType(0);
17528
17529  // Let legalize expand this if it isn't a legal type yet.
17530  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17531    return SDValue();
17532
17533  EVT ScalarVT = VT.getScalarType();
17534  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17535      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17536    return SDValue();
17537
17538  SDValue A = N->getOperand(0);
17539  SDValue B = N->getOperand(1);
17540  SDValue C = N->getOperand(2);
17541
17542  bool NegA = (A.getOpcode() == ISD::FNEG);
17543  bool NegB = (B.getOpcode() == ISD::FNEG);
17544  bool NegC = (C.getOpcode() == ISD::FNEG);
17545
17546  // Negative multiplication when NegA xor NegB
17547  bool NegMul = (NegA != NegB);
17548  if (NegA)
17549    A = A.getOperand(0);
17550  if (NegB)
17551    B = B.getOperand(0);
17552  if (NegC)
17553    C = C.getOperand(0);
17554
17555  unsigned Opcode;
17556  if (!NegMul)
17557    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17558  else
17559    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17560
17561  return DAG.getNode(Opcode, dl, VT, A, B, C);
17562}
17563
17564static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17565                                  TargetLowering::DAGCombinerInfo &DCI,
17566                                  const X86Subtarget *Subtarget) {
17567  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17568  //           (and (i32 x86isd::setcc_carry), 1)
17569  // This eliminates the zext. This transformation is necessary because
17570  // ISD::SETCC is always legalized to i8.
17571  DebugLoc dl = N->getDebugLoc();
17572  SDValue N0 = N->getOperand(0);
17573  EVT VT = N->getValueType(0);
17574
17575  if (N0.getOpcode() == ISD::AND &&
17576      N0.hasOneUse() &&
17577      N0.getOperand(0).hasOneUse()) {
17578    SDValue N00 = N0.getOperand(0);
17579    if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17580      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17581      if (!C || C->getZExtValue() != 1)
17582        return SDValue();
17583      return DAG.getNode(ISD::AND, dl, VT,
17584                         DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17585                                     N00.getOperand(0), N00.getOperand(1)),
17586                         DAG.getConstant(1, VT));
17587    }
17588  }
17589
17590  if (VT.is256BitVector()) {
17591    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17592    if (R.getNode())
17593      return R;
17594  }
17595
17596  return SDValue();
17597}
17598
17599// Optimize x == -y --> x+y == 0
17600//          x != -y --> x+y != 0
17601static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17602  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17603  SDValue LHS = N->getOperand(0);
17604  SDValue RHS = N->getOperand(1);
17605
17606  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17607    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17608      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17609        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17610                                   LHS.getValueType(), RHS, LHS.getOperand(1));
17611        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17612                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17613      }
17614  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17615    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17616      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17617        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17618                                   RHS.getValueType(), LHS, RHS.getOperand(1));
17619        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17620                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17621      }
17622  return SDValue();
17623}
17624
17625// Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17626// as "sbb reg,reg", since it can be extended without zext and produces
17627// an all-ones bit which is more useful than 0/1 in some cases.
17628static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17629  return DAG.getNode(ISD::AND, DL, MVT::i8,
17630                     DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17631                                 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17632                     DAG.getConstant(1, MVT::i8));
17633}
17634
17635// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17636static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17637                                   TargetLowering::DAGCombinerInfo &DCI,
17638                                   const X86Subtarget *Subtarget) {
17639  DebugLoc DL = N->getDebugLoc();
17640  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17641  SDValue EFLAGS = N->getOperand(1);
17642
17643  if (CC == X86::COND_A) {
17644    // Try to convert COND_A into COND_B in an attempt to facilitate
17645    // materializing "setb reg".
17646    //
17647    // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17648    // cannot take an immediate as its first operand.
17649    //
17650    if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17651        EFLAGS.getValueType().isInteger() &&
17652        !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17653      SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17654                                   EFLAGS.getNode()->getVTList(),
17655                                   EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17656      SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17657      return MaterializeSETB(DL, NewEFLAGS, DAG);
17658    }
17659  }
17660
17661  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17662  // a zext and produces an all-ones bit which is more useful than 0/1 in some
17663  // cases.
17664  if (CC == X86::COND_B)
17665    return MaterializeSETB(DL, EFLAGS, DAG);
17666
17667  SDValue Flags;
17668
17669  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17670  if (Flags.getNode()) {
17671    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17672    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17673  }
17674
17675  return SDValue();
17676}
17677
17678// Optimize branch condition evaluation.
17679//
17680static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17681                                    TargetLowering::DAGCombinerInfo &DCI,
17682                                    const X86Subtarget *Subtarget) {
17683  DebugLoc DL = N->getDebugLoc();
17684  SDValue Chain = N->getOperand(0);
17685  SDValue Dest = N->getOperand(1);
17686  SDValue EFLAGS = N->getOperand(3);
17687  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17688
17689  SDValue Flags;
17690
17691  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17692  if (Flags.getNode()) {
17693    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17694    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17695                       Flags);
17696  }
17697
17698  return SDValue();
17699}
17700
17701static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17702                                        const X86TargetLowering *XTLI) {
17703  SDValue Op0 = N->getOperand(0);
17704  EVT InVT = Op0->getValueType(0);
17705
17706  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17707  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17708    DebugLoc dl = N->getDebugLoc();
17709    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17710    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17711    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17712  }
17713
17714  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17715  // a 32-bit target where SSE doesn't support i64->FP operations.
17716  if (Op0.getOpcode() == ISD::LOAD) {
17717    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17718    EVT VT = Ld->getValueType(0);
17719    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17720        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17721        !XTLI->getSubtarget()->is64Bit() &&
17722        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17723      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17724                                          Ld->getChain(), Op0, DAG);
17725      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17726      return FILDChain;
17727    }
17728  }
17729  return SDValue();
17730}
17731
17732// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17733static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17734                                 X86TargetLowering::DAGCombinerInfo &DCI) {
17735  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17736  // the result is either zero or one (depending on the input carry bit).
17737  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17738  if (X86::isZeroNode(N->getOperand(0)) &&
17739      X86::isZeroNode(N->getOperand(1)) &&
17740      // We don't have a good way to replace an EFLAGS use, so only do this when
17741      // dead right now.
17742      SDValue(N, 1).use_empty()) {
17743    DebugLoc DL = N->getDebugLoc();
17744    EVT VT = N->getValueType(0);
17745    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17746    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17747                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17748                                           DAG.getConstant(X86::COND_B,MVT::i8),
17749                                           N->getOperand(2)),
17750                               DAG.getConstant(1, VT));
17751    return DCI.CombineTo(N, Res1, CarryOut);
17752  }
17753
17754  return SDValue();
17755}
17756
17757// fold (add Y, (sete  X, 0)) -> adc  0, Y
17758//      (add Y, (setne X, 0)) -> sbb -1, Y
17759//      (sub (sete  X, 0), Y) -> sbb  0, Y
17760//      (sub (setne X, 0), Y) -> adc -1, Y
17761static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17762  DebugLoc DL = N->getDebugLoc();
17763
17764  // Look through ZExts.
17765  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17766  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17767    return SDValue();
17768
17769  SDValue SetCC = Ext.getOperand(0);
17770  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17771    return SDValue();
17772
17773  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17774  if (CC != X86::COND_E && CC != X86::COND_NE)
17775    return SDValue();
17776
17777  SDValue Cmp = SetCC.getOperand(1);
17778  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17779      !X86::isZeroNode(Cmp.getOperand(1)) ||
17780      !Cmp.getOperand(0).getValueType().isInteger())
17781    return SDValue();
17782
17783  SDValue CmpOp0 = Cmp.getOperand(0);
17784  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17785                               DAG.getConstant(1, CmpOp0.getValueType()));
17786
17787  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17788  if (CC == X86::COND_NE)
17789    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17790                       DL, OtherVal.getValueType(), OtherVal,
17791                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17792  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17793                     DL, OtherVal.getValueType(), OtherVal,
17794                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17795}
17796
17797/// PerformADDCombine - Do target-specific dag combines on integer adds.
17798static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17799                                 const X86Subtarget *Subtarget) {
17800  EVT VT = N->getValueType(0);
17801  SDValue Op0 = N->getOperand(0);
17802  SDValue Op1 = N->getOperand(1);
17803
17804  // Try to synthesize horizontal adds from adds of shuffles.
17805  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17806       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17807      isHorizontalBinOp(Op0, Op1, true))
17808    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17809
17810  return OptimizeConditionalInDecrement(N, DAG);
17811}
17812
17813static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17814                                 const X86Subtarget *Subtarget) {
17815  SDValue Op0 = N->getOperand(0);
17816  SDValue Op1 = N->getOperand(1);
17817
17818  // X86 can't encode an immediate LHS of a sub. See if we can push the
17819  // negation into a preceding instruction.
17820  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17821    // If the RHS of the sub is a XOR with one use and a constant, invert the
17822    // immediate. Then add one to the LHS of the sub so we can turn
17823    // X-Y -> X+~Y+1, saving one register.
17824    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17825        isa<ConstantSDNode>(Op1.getOperand(1))) {
17826      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17827      EVT VT = Op0.getValueType();
17828      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17829                                   Op1.getOperand(0),
17830                                   DAG.getConstant(~XorC, VT));
17831      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17832                         DAG.getConstant(C->getAPIntValue()+1, VT));
17833    }
17834  }
17835
17836  // Try to synthesize horizontal adds from adds of shuffles.
17837  EVT VT = N->getValueType(0);
17838  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17839       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17840      isHorizontalBinOp(Op0, Op1, true))
17841    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17842
17843  return OptimizeConditionalInDecrement(N, DAG);
17844}
17845
17846/// performVZEXTCombine - Performs build vector combines
17847static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17848                                        TargetLowering::DAGCombinerInfo &DCI,
17849                                        const X86Subtarget *Subtarget) {
17850  // (vzext (bitcast (vzext (x)) -> (vzext x)
17851  SDValue In = N->getOperand(0);
17852  while (In.getOpcode() == ISD::BITCAST)
17853    In = In.getOperand(0);
17854
17855  if (In.getOpcode() != X86ISD::VZEXT)
17856    return SDValue();
17857
17858  return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17859                     In.getOperand(0));
17860}
17861
17862SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17863                                             DAGCombinerInfo &DCI) const {
17864  SelectionDAG &DAG = DCI.DAG;
17865  switch (N->getOpcode()) {
17866  default: break;
17867  case ISD::EXTRACT_VECTOR_ELT:
17868    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17869  case ISD::VSELECT:
17870  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17871  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17872  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17873  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17874  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17875  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17876  case ISD::SHL:
17877  case ISD::SRA:
17878  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17879  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17880  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17881  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17882  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17883  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17884  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17885  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17886  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17887  case X86ISD::FXOR:
17888  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17889  case X86ISD::FMIN:
17890  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17891  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17892  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17893  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17894  case ISD::ANY_EXTEND:
17895  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17896  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17897  case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17898  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17899  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17900  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17901  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17902  case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17903  case X86ISD::SHUFP:       // Handle all target specific shuffles
17904  case X86ISD::PALIGNR:
17905  case X86ISD::UNPCKH:
17906  case X86ISD::UNPCKL:
17907  case X86ISD::MOVHLPS:
17908  case X86ISD::MOVLHPS:
17909  case X86ISD::PSHUFD:
17910  case X86ISD::PSHUFHW:
17911  case X86ISD::PSHUFLW:
17912  case X86ISD::MOVSS:
17913  case X86ISD::MOVSD:
17914  case X86ISD::VPERMILP:
17915  case X86ISD::VPERM2X128:
17916  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17917  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17918  }
17919
17920  return SDValue();
17921}
17922
17923/// isTypeDesirableForOp - Return true if the target has native support for
17924/// the specified value type and it is 'desirable' to use the type for the
17925/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17926/// instruction encodings are longer and some i16 instructions are slow.
17927bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17928  if (!isTypeLegal(VT))
17929    return false;
17930  if (VT != MVT::i16)
17931    return true;
17932
17933  switch (Opc) {
17934  default:
17935    return true;
17936  case ISD::LOAD:
17937  case ISD::SIGN_EXTEND:
17938  case ISD::ZERO_EXTEND:
17939  case ISD::ANY_EXTEND:
17940  case ISD::SHL:
17941  case ISD::SRL:
17942  case ISD::SUB:
17943  case ISD::ADD:
17944  case ISD::MUL:
17945  case ISD::AND:
17946  case ISD::OR:
17947  case ISD::XOR:
17948    return false;
17949  }
17950}
17951
17952/// IsDesirableToPromoteOp - This method query the target whether it is
17953/// beneficial for dag combiner to promote the specified node. If true, it
17954/// should return the desired promotion type by reference.
17955bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17956  EVT VT = Op.getValueType();
17957  if (VT != MVT::i16)
17958    return false;
17959
17960  bool Promote = false;
17961  bool Commute = false;
17962  switch (Op.getOpcode()) {
17963  default: break;
17964  case ISD::LOAD: {
17965    LoadSDNode *LD = cast<LoadSDNode>(Op);
17966    // If the non-extending load has a single use and it's not live out, then it
17967    // might be folded.
17968    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17969                                                     Op.hasOneUse()*/) {
17970      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17971             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17972        // The only case where we'd want to promote LOAD (rather then it being
17973        // promoted as an operand is when it's only use is liveout.
17974        if (UI->getOpcode() != ISD::CopyToReg)
17975          return false;
17976      }
17977    }
17978    Promote = true;
17979    break;
17980  }
17981  case ISD::SIGN_EXTEND:
17982  case ISD::ZERO_EXTEND:
17983  case ISD::ANY_EXTEND:
17984    Promote = true;
17985    break;
17986  case ISD::SHL:
17987  case ISD::SRL: {
17988    SDValue N0 = Op.getOperand(0);
17989    // Look out for (store (shl (load), x)).
17990    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17991      return false;
17992    Promote = true;
17993    break;
17994  }
17995  case ISD::ADD:
17996  case ISD::MUL:
17997  case ISD::AND:
17998  case ISD::OR:
17999  case ISD::XOR:
18000    Commute = true;
18001    // fallthrough
18002  case ISD::SUB: {
18003    SDValue N0 = Op.getOperand(0);
18004    SDValue N1 = Op.getOperand(1);
18005    if (!Commute && MayFoldLoad(N1))
18006      return false;
18007    // Avoid disabling potential load folding opportunities.
18008    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18009      return false;
18010    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18011      return false;
18012    Promote = true;
18013  }
18014  }
18015
18016  PVT = MVT::i32;
18017  return Promote;
18018}
18019
18020//===----------------------------------------------------------------------===//
18021//                           X86 Inline Assembly Support
18022//===----------------------------------------------------------------------===//
18023
18024namespace {
18025  // Helper to match a string separated by whitespace.
18026  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18027    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18028
18029    for (unsigned i = 0, e = args.size(); i != e; ++i) {
18030      StringRef piece(*args[i]);
18031      if (!s.startswith(piece)) // Check if the piece matches.
18032        return false;
18033
18034      s = s.substr(piece.size());
18035      StringRef::size_type pos = s.find_first_not_of(" \t");
18036      if (pos == 0) // We matched a prefix.
18037        return false;
18038
18039      s = s.substr(pos);
18040    }
18041
18042    return s.empty();
18043  }
18044  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18045}
18046
18047bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18048  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18049
18050  std::string AsmStr = IA->getAsmString();
18051
18052  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18053  if (!Ty || Ty->getBitWidth() % 16 != 0)
18054    return false;
18055
18056  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18057  SmallVector<StringRef, 4> AsmPieces;
18058  SplitString(AsmStr, AsmPieces, ";\n");
18059
18060  switch (AsmPieces.size()) {
18061  default: return false;
18062  case 1:
18063    // FIXME: this should verify that we are targeting a 486 or better.  If not,
18064    // we will turn this bswap into something that will be lowered to logical
18065    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18066    // lower so don't worry about this.
18067    // bswap $0
18068    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18069        matchAsm(AsmPieces[0], "bswapl", "$0") ||
18070        matchAsm(AsmPieces[0], "bswapq", "$0") ||
18071        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18072        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18073        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18074      // No need to check constraints, nothing other than the equivalent of
18075      // "=r,0" would be valid here.
18076      return IntrinsicLowering::LowerToByteSwap(CI);
18077    }
18078
18079    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18080    if (CI->getType()->isIntegerTy(16) &&
18081        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18082        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18083         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18084      AsmPieces.clear();
18085      const std::string &ConstraintsStr = IA->getConstraintString();
18086      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18087      array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18088      if (AsmPieces.size() == 4 &&
18089          AsmPieces[0] == "~{cc}" &&
18090          AsmPieces[1] == "~{dirflag}" &&
18091          AsmPieces[2] == "~{flags}" &&
18092          AsmPieces[3] == "~{fpsr}")
18093      return IntrinsicLowering::LowerToByteSwap(CI);
18094    }
18095    break;
18096  case 3:
18097    if (CI->getType()->isIntegerTy(32) &&
18098        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18099        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18100        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18101        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18102      AsmPieces.clear();
18103      const std::string &ConstraintsStr = IA->getConstraintString();
18104      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18105      array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18106      if (AsmPieces.size() == 4 &&
18107          AsmPieces[0] == "~{cc}" &&
18108          AsmPieces[1] == "~{dirflag}" &&
18109          AsmPieces[2] == "~{flags}" &&
18110          AsmPieces[3] == "~{fpsr}")
18111        return IntrinsicLowering::LowerToByteSwap(CI);
18112    }
18113
18114    if (CI->getType()->isIntegerTy(64)) {
18115      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18116      if (Constraints.size() >= 2 &&
18117          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18118          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18119        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18120        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18121            matchAsm(AsmPieces[1], "bswap", "%edx") &&
18122            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18123          return IntrinsicLowering::LowerToByteSwap(CI);
18124      }
18125    }
18126    break;
18127  }
18128  return false;
18129}
18130
18131/// getConstraintType - Given a constraint letter, return the type of
18132/// constraint it is for this target.
18133X86TargetLowering::ConstraintType
18134X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18135  if (Constraint.size() == 1) {
18136    switch (Constraint[0]) {
18137    case 'R':
18138    case 'q':
18139    case 'Q':
18140    case 'f':
18141    case 't':
18142    case 'u':
18143    case 'y':
18144    case 'x':
18145    case 'Y':
18146    case 'l':
18147      return C_RegisterClass;
18148    case 'a':
18149    case 'b':
18150    case 'c':
18151    case 'd':
18152    case 'S':
18153    case 'D':
18154    case 'A':
18155      return C_Register;
18156    case 'I':
18157    case 'J':
18158    case 'K':
18159    case 'L':
18160    case 'M':
18161    case 'N':
18162    case 'G':
18163    case 'C':
18164    case 'e':
18165    case 'Z':
18166      return C_Other;
18167    default:
18168      break;
18169    }
18170  }
18171  return TargetLowering::getConstraintType(Constraint);
18172}
18173
18174/// Examine constraint type and operand type and determine a weight value.
18175/// This object must already have been set up with the operand type
18176/// and the current alternative constraint selected.
18177TargetLowering::ConstraintWeight
18178  X86TargetLowering::getSingleConstraintMatchWeight(
18179    AsmOperandInfo &info, const char *constraint) const {
18180  ConstraintWeight weight = CW_Invalid;
18181  Value *CallOperandVal = info.CallOperandVal;
18182    // If we don't have a value, we can't do a match,
18183    // but allow it at the lowest weight.
18184  if (CallOperandVal == NULL)
18185    return CW_Default;
18186  Type *type = CallOperandVal->getType();
18187  // Look at the constraint type.
18188  switch (*constraint) {
18189  default:
18190    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18191  case 'R':
18192  case 'q':
18193  case 'Q':
18194  case 'a':
18195  case 'b':
18196  case 'c':
18197  case 'd':
18198  case 'S':
18199  case 'D':
18200  case 'A':
18201    if (CallOperandVal->getType()->isIntegerTy())
18202      weight = CW_SpecificReg;
18203    break;
18204  case 'f':
18205  case 't':
18206  case 'u':
18207    if (type->isFloatingPointTy())
18208      weight = CW_SpecificReg;
18209    break;
18210  case 'y':
18211    if (type->isX86_MMXTy() && Subtarget->hasMMX())
18212      weight = CW_SpecificReg;
18213    break;
18214  case 'x':
18215  case 'Y':
18216    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18217        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18218      weight = CW_Register;
18219    break;
18220  case 'I':
18221    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18222      if (C->getZExtValue() <= 31)
18223        weight = CW_Constant;
18224    }
18225    break;
18226  case 'J':
18227    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18228      if (C->getZExtValue() <= 63)
18229        weight = CW_Constant;
18230    }
18231    break;
18232  case 'K':
18233    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18234      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18235        weight = CW_Constant;
18236    }
18237    break;
18238  case 'L':
18239    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18240      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18241        weight = CW_Constant;
18242    }
18243    break;
18244  case 'M':
18245    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18246      if (C->getZExtValue() <= 3)
18247        weight = CW_Constant;
18248    }
18249    break;
18250  case 'N':
18251    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18252      if (C->getZExtValue() <= 0xff)
18253        weight = CW_Constant;
18254    }
18255    break;
18256  case 'G':
18257  case 'C':
18258    if (dyn_cast<ConstantFP>(CallOperandVal)) {
18259      weight = CW_Constant;
18260    }
18261    break;
18262  case 'e':
18263    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18264      if ((C->getSExtValue() >= -0x80000000LL) &&
18265          (C->getSExtValue() <= 0x7fffffffLL))
18266        weight = CW_Constant;
18267    }
18268    break;
18269  case 'Z':
18270    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18271      if (C->getZExtValue() <= 0xffffffff)
18272        weight = CW_Constant;
18273    }
18274    break;
18275  }
18276  return weight;
18277}
18278
18279/// LowerXConstraint - try to replace an X constraint, which matches anything,
18280/// with another that has more specific requirements based on the type of the
18281/// corresponding operand.
18282const char *X86TargetLowering::
18283LowerXConstraint(EVT ConstraintVT) const {
18284  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18285  // 'f' like normal targets.
18286  if (ConstraintVT.isFloatingPoint()) {
18287    if (Subtarget->hasSSE2())
18288      return "Y";
18289    if (Subtarget->hasSSE1())
18290      return "x";
18291  }
18292
18293  return TargetLowering::LowerXConstraint(ConstraintVT);
18294}
18295
18296/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18297/// vector.  If it is invalid, don't add anything to Ops.
18298void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18299                                                     std::string &Constraint,
18300                                                     std::vector<SDValue>&Ops,
18301                                                     SelectionDAG &DAG) const {
18302  SDValue Result(0, 0);
18303
18304  // Only support length 1 constraints for now.
18305  if (Constraint.length() > 1) return;
18306
18307  char ConstraintLetter = Constraint[0];
18308  switch (ConstraintLetter) {
18309  default: break;
18310  case 'I':
18311    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18312      if (C->getZExtValue() <= 31) {
18313        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18314        break;
18315      }
18316    }
18317    return;
18318  case 'J':
18319    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18320      if (C->getZExtValue() <= 63) {
18321        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18322        break;
18323      }
18324    }
18325    return;
18326  case 'K':
18327    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18328      if (isInt<8>(C->getSExtValue())) {
18329        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18330        break;
18331      }
18332    }
18333    return;
18334  case 'N':
18335    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18336      if (C->getZExtValue() <= 255) {
18337        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18338        break;
18339      }
18340    }
18341    return;
18342  case 'e': {
18343    // 32-bit signed value
18344    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18345      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18346                                           C->getSExtValue())) {
18347        // Widen to 64 bits here to get it sign extended.
18348        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18349        break;
18350      }
18351    // FIXME gcc accepts some relocatable values here too, but only in certain
18352    // memory models; it's complicated.
18353    }
18354    return;
18355  }
18356  case 'Z': {
18357    // 32-bit unsigned value
18358    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18359      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18360                                           C->getZExtValue())) {
18361        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18362        break;
18363      }
18364    }
18365    // FIXME gcc accepts some relocatable values here too, but only in certain
18366    // memory models; it's complicated.
18367    return;
18368  }
18369  case 'i': {
18370    // Literal immediates are always ok.
18371    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18372      // Widen to 64 bits here to get it sign extended.
18373      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18374      break;
18375    }
18376
18377    // In any sort of PIC mode addresses need to be computed at runtime by
18378    // adding in a register or some sort of table lookup.  These can't
18379    // be used as immediates.
18380    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18381      return;
18382
18383    // If we are in non-pic codegen mode, we allow the address of a global (with
18384    // an optional displacement) to be used with 'i'.
18385    GlobalAddressSDNode *GA = 0;
18386    int64_t Offset = 0;
18387
18388    // Match either (GA), (GA+C), (GA+C1+C2), etc.
18389    while (1) {
18390      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18391        Offset += GA->getOffset();
18392        break;
18393      } else if (Op.getOpcode() == ISD::ADD) {
18394        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18395          Offset += C->getZExtValue();
18396          Op = Op.getOperand(0);
18397          continue;
18398        }
18399      } else if (Op.getOpcode() == ISD::SUB) {
18400        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18401          Offset += -C->getZExtValue();
18402          Op = Op.getOperand(0);
18403          continue;
18404        }
18405      }
18406
18407      // Otherwise, this isn't something we can handle, reject it.
18408      return;
18409    }
18410
18411    const GlobalValue *GV = GA->getGlobal();
18412    // If we require an extra load to get this address, as in PIC mode, we
18413    // can't accept it.
18414    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18415                                                        getTargetMachine())))
18416      return;
18417
18418    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18419                                        GA->getValueType(0), Offset);
18420    break;
18421  }
18422  }
18423
18424  if (Result.getNode()) {
18425    Ops.push_back(Result);
18426    return;
18427  }
18428  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18429}
18430
18431std::pair<unsigned, const TargetRegisterClass*>
18432X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18433                                                EVT VT) const {
18434  // First, see if this is a constraint that directly corresponds to an LLVM
18435  // register class.
18436  if (Constraint.size() == 1) {
18437    // GCC Constraint Letters
18438    switch (Constraint[0]) {
18439    default: break;
18440      // TODO: Slight differences here in allocation order and leaving
18441      // RIP in the class. Do they matter any more here than they do
18442      // in the normal allocation?
18443    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18444      if (Subtarget->is64Bit()) {
18445        if (VT == MVT::i32 || VT == MVT::f32)
18446          return std::make_pair(0U, &X86::GR32RegClass);
18447        if (VT == MVT::i16)
18448          return std::make_pair(0U, &X86::GR16RegClass);
18449        if (VT == MVT::i8 || VT == MVT::i1)
18450          return std::make_pair(0U, &X86::GR8RegClass);
18451        if (VT == MVT::i64 || VT == MVT::f64)
18452          return std::make_pair(0U, &X86::GR64RegClass);
18453        break;
18454      }
18455      // 32-bit fallthrough
18456    case 'Q':   // Q_REGS
18457      if (VT == MVT::i32 || VT == MVT::f32)
18458        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18459      if (VT == MVT::i16)
18460        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18461      if (VT == MVT::i8 || VT == MVT::i1)
18462        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18463      if (VT == MVT::i64)
18464        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18465      break;
18466    case 'r':   // GENERAL_REGS
18467    case 'l':   // INDEX_REGS
18468      if (VT == MVT::i8 || VT == MVT::i1)
18469        return std::make_pair(0U, &X86::GR8RegClass);
18470      if (VT == MVT::i16)
18471        return std::make_pair(0U, &X86::GR16RegClass);
18472      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18473        return std::make_pair(0U, &X86::GR32RegClass);
18474      return std::make_pair(0U, &X86::GR64RegClass);
18475    case 'R':   // LEGACY_REGS
18476      if (VT == MVT::i8 || VT == MVT::i1)
18477        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18478      if (VT == MVT::i16)
18479        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18480      if (VT == MVT::i32 || !Subtarget->is64Bit())
18481        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18482      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18483    case 'f':  // FP Stack registers.
18484      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18485      // value to the correct fpstack register class.
18486      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18487        return std::make_pair(0U, &X86::RFP32RegClass);
18488      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18489        return std::make_pair(0U, &X86::RFP64RegClass);
18490      return std::make_pair(0U, &X86::RFP80RegClass);
18491    case 'y':   // MMX_REGS if MMX allowed.
18492      if (!Subtarget->hasMMX()) break;
18493      return std::make_pair(0U, &X86::VR64RegClass);
18494    case 'Y':   // SSE_REGS if SSE2 allowed
18495      if (!Subtarget->hasSSE2()) break;
18496      // FALL THROUGH.
18497    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18498      if (!Subtarget->hasSSE1()) break;
18499
18500      switch (VT.getSimpleVT().SimpleTy) {
18501      default: break;
18502      // Scalar SSE types.
18503      case MVT::f32:
18504      case MVT::i32:
18505        return std::make_pair(0U, &X86::FR32RegClass);
18506      case MVT::f64:
18507      case MVT::i64:
18508        return std::make_pair(0U, &X86::FR64RegClass);
18509      // Vector types.
18510      case MVT::v16i8:
18511      case MVT::v8i16:
18512      case MVT::v4i32:
18513      case MVT::v2i64:
18514      case MVT::v4f32:
18515      case MVT::v2f64:
18516        return std::make_pair(0U, &X86::VR128RegClass);
18517      // AVX types.
18518      case MVT::v32i8:
18519      case MVT::v16i16:
18520      case MVT::v8i32:
18521      case MVT::v4i64:
18522      case MVT::v8f32:
18523      case MVT::v4f64:
18524        return std::make_pair(0U, &X86::VR256RegClass);
18525      }
18526      break;
18527    }
18528  }
18529
18530  // Use the default implementation in TargetLowering to convert the register
18531  // constraint into a member of a register class.
18532  std::pair<unsigned, const TargetRegisterClass*> Res;
18533  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18534
18535  // Not found as a standard register?
18536  if (Res.second == 0) {
18537    // Map st(0) -> st(7) -> ST0
18538    if (Constraint.size() == 7 && Constraint[0] == '{' &&
18539        tolower(Constraint[1]) == 's' &&
18540        tolower(Constraint[2]) == 't' &&
18541        Constraint[3] == '(' &&
18542        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18543        Constraint[5] == ')' &&
18544        Constraint[6] == '}') {
18545
18546      Res.first = X86::ST0+Constraint[4]-'0';
18547      Res.second = &X86::RFP80RegClass;
18548      return Res;
18549    }
18550
18551    // GCC allows "st(0)" to be called just plain "st".
18552    if (StringRef("{st}").equals_lower(Constraint)) {
18553      Res.first = X86::ST0;
18554      Res.second = &X86::RFP80RegClass;
18555      return Res;
18556    }
18557
18558    // flags -> EFLAGS
18559    if (StringRef("{flags}").equals_lower(Constraint)) {
18560      Res.first = X86::EFLAGS;
18561      Res.second = &X86::CCRRegClass;
18562      return Res;
18563    }
18564
18565    // 'A' means EAX + EDX.
18566    if (Constraint == "A") {
18567      Res.first = X86::EAX;
18568      Res.second = &X86::GR32_ADRegClass;
18569      return Res;
18570    }
18571    return Res;
18572  }
18573
18574  // Otherwise, check to see if this is a register class of the wrong value
18575  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18576  // turn into {ax},{dx}.
18577  if (Res.second->hasType(VT))
18578    return Res;   // Correct type already, nothing to do.
18579
18580  // All of the single-register GCC register classes map their values onto
18581  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18582  // really want an 8-bit or 32-bit register, map to the appropriate register
18583  // class and return the appropriate register.
18584  if (Res.second == &X86::GR16RegClass) {
18585    if (VT == MVT::i8 || VT == MVT::i1) {
18586      unsigned DestReg = 0;
18587      switch (Res.first) {
18588      default: break;
18589      case X86::AX: DestReg = X86::AL; break;
18590      case X86::DX: DestReg = X86::DL; break;
18591      case X86::CX: DestReg = X86::CL; break;
18592      case X86::BX: DestReg = X86::BL; break;
18593      }
18594      if (DestReg) {
18595        Res.first = DestReg;
18596        Res.second = &X86::GR8RegClass;
18597      }
18598    } else if (VT == MVT::i32 || VT == MVT::f32) {
18599      unsigned DestReg = 0;
18600      switch (Res.first) {
18601      default: break;
18602      case X86::AX: DestReg = X86::EAX; break;
18603      case X86::DX: DestReg = X86::EDX; break;
18604      case X86::CX: DestReg = X86::ECX; break;
18605      case X86::BX: DestReg = X86::EBX; break;
18606      case X86::SI: DestReg = X86::ESI; break;
18607      case X86::DI: DestReg = X86::EDI; break;
18608      case X86::BP: DestReg = X86::EBP; break;
18609      case X86::SP: DestReg = X86::ESP; break;
18610      }
18611      if (DestReg) {
18612        Res.first = DestReg;
18613        Res.second = &X86::GR32RegClass;
18614      }
18615    } else if (VT == MVT::i64 || VT == MVT::f64) {
18616      unsigned DestReg = 0;
18617      switch (Res.first) {
18618      default: break;
18619      case X86::AX: DestReg = X86::RAX; break;
18620      case X86::DX: DestReg = X86::RDX; break;
18621      case X86::CX: DestReg = X86::RCX; break;
18622      case X86::BX: DestReg = X86::RBX; break;
18623      case X86::SI: DestReg = X86::RSI; break;
18624      case X86::DI: DestReg = X86::RDI; break;
18625      case X86::BP: DestReg = X86::RBP; break;
18626      case X86::SP: DestReg = X86::RSP; break;
18627      }
18628      if (DestReg) {
18629        Res.first = DestReg;
18630        Res.second = &X86::GR64RegClass;
18631      }
18632    }
18633  } else if (Res.second == &X86::FR32RegClass ||
18634             Res.second == &X86::FR64RegClass ||
18635             Res.second == &X86::VR128RegClass) {
18636    // Handle references to XMM physical registers that got mapped into the
18637    // wrong class.  This can happen with constraints like {xmm0} where the
18638    // target independent register mapper will just pick the first match it can
18639    // find, ignoring the required type.
18640
18641    if (VT == MVT::f32 || VT == MVT::i32)
18642      Res.second = &X86::FR32RegClass;
18643    else if (VT == MVT::f64 || VT == MVT::i64)
18644      Res.second = &X86::FR64RegClass;
18645    else if (X86::VR128RegClass.hasType(VT))
18646      Res.second = &X86::VR128RegClass;
18647    else if (X86::VR256RegClass.hasType(VT))
18648      Res.second = &X86::VR256RegClass;
18649  }
18650
18651  return Res;
18652}
18653