[x86] Fix PR20355 (and dups) by not using unsigned multiplication when
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.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/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
974     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
975     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
976     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
977     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
978     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
979     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
980     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
981     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
985     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
986     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
987
988     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
989     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
992
993     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
998
999     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002       // Do not attempt to custom lower non-power-of-2 vectors
1003       if (!isPowerOf2_32(VT.getVectorNumElements()))
1004         continue;
1005       // Do not attempt to custom lower non-128-bit vectors
1006       if (!VT.is128BitVector())
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1011     }
1012
1013     // We support custom legalizing of sext and anyext loads for specific
1014     // memory vector types which we can load as a scalar (or sequence of
1015     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016     // loads these must work with a single scalar load.
1017     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1018     if (Subtarget->is64Bit()) {
1019       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     }
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1028
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1033     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1035
1036     if (Subtarget->is64Bit()) {
1037       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1038       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1039     }
1040
1041     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1042     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1043       MVT VT = (MVT::SimpleValueType)i;
1044
1045       // Do not attempt to promote non-128-bit vectors
1046       if (!VT.is128BitVector())
1047         continue;
1048
1049       setOperationAction(ISD::AND,    VT, Promote);
1050       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1051       setOperationAction(ISD::OR,     VT, Promote);
1052       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1053       setOperationAction(ISD::XOR,    VT, Promote);
1054       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1055       setOperationAction(ISD::LOAD,   VT, Promote);
1056       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1057       setOperationAction(ISD::SELECT, VT, Promote);
1058       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1059     }
1060
1061     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1062
1063     // Custom lower v2i64 and v2f64 selects.
1064     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1065     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1066     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1067     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1074     // As there is no 64-bit GPR available, we need build a special custom
1075     // sequence to convert from v2i32 to v2f32.
1076     if (!Subtarget->is64Bit())
1077       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1078
1079     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1080     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1081
1082     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1083
1084     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1087   }
1088
1089   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1098     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1100
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1106     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1107     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1108     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1109     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1110     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1111
1112     // FIXME: Do we need to handle scalar-to-vector here?
1113     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1114
1115     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
1116
1117     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1121     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1122     // There is no BLENDI for byte vectors. We don't need to custom lower
1123     // some vselects for now.
1124     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1125
1126     // SSE41 brings specific instructions for doing vector sign extend even in
1127     // cases where we don't have SRA.
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1130     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1131
1132     // i8 and i16 vectors are custom , because the source register and source
1133     // source memory operand types are not the same width.  f32 vectors are
1134     // custom since the immediate controlling the insert encodes additional
1135     // information.
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1139     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1140
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1144     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1145
1146     // FIXME: these should be Legal but thats only for the case where
1147     // the index is constant.  For now custom expand to deal with that.
1148     if (Subtarget->is64Bit()) {
1149       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1150       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1151     }
1152   }
1153
1154   if (Subtarget->hasSSE2()) {
1155     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1156     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1157
1158     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1159     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1160
1161     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1162     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1163
1164     // In the customized shift lowering, the legal cases in AVX2 will be
1165     // recognized.
1166     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1167     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1168
1169     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1170     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1171
1172     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1173   }
1174
1175   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1176     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1181     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1182
1183     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1185     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1186
1187     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1191     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1192     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1193     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1194     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1195     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1197     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1198     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1199
1200     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1204     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1205     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1206     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1207     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1208     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1210     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1211     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1212
1213     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1214     // even though v8i16 is a legal type.
1215     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1218
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1220     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1221     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1222
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1224     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1225
1226     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1227
1228     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1229     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1230
1231     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1232     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1233
1234     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1235     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1236
1237     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1240     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1241
1242     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1244     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1245
1246     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1249     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1250
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1253     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1256     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1259     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1262     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1263
1264     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1265       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1270       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1271     }
1272
1273     if (Subtarget->hasInt256()) {
1274       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1277       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1278
1279       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1282       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1283
1284       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1285       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1286       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1287       // Don't lower v32i8 because there is no 128-bit byte mul
1288
1289       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1291       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1292       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1293
1294       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1295       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1296     } else {
1297       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1300       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1301
1302       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1305       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1306
1307       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1309       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1310       // Don't lower v32i8 because there is no 128-bit byte mul
1311     }
1312
1313     // In the customized shift lowering, the legal cases in AVX2 will be
1314     // recognized.
1315     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1316     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1317
1318     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1319     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1320
1321     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1322
1323     // Custom lower several nodes for 256-bit types.
1324     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1325              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1326       MVT VT = (MVT::SimpleValueType)i;
1327
1328       // Extract subvector is special because the value type
1329       // (result) is 128-bit but the source is 256-bit wide.
1330       if (VT.is128BitVector())
1331         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1332
1333       // Do not attempt to custom lower other non-256-bit vectors
1334       if (!VT.is256BitVector())
1335         continue;
1336
1337       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1338       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1339       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1340       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1341       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1342       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1343       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1344     }
1345
1346     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1347     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1348       MVT VT = (MVT::SimpleValueType)i;
1349
1350       // Do not attempt to promote non-256-bit vectors
1351       if (!VT.is256BitVector())
1352         continue;
1353
1354       setOperationAction(ISD::AND,    VT, Promote);
1355       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1356       setOperationAction(ISD::OR,     VT, Promote);
1357       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1358       setOperationAction(ISD::XOR,    VT, Promote);
1359       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1360       setOperationAction(ISD::LOAD,   VT, Promote);
1361       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1362       setOperationAction(ISD::SELECT, VT, Promote);
1363       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1364     }
1365   }
1366
1367   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1368     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1371     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1372
1373     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1374     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1375     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1376
1377     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1378     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1379     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1380     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1381     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1382     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1387     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1388
1389     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1393     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1394     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1395
1396     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1400     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1401     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1402     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1403     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1404
1405     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1407     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1408     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1409     if (Subtarget->is64Bit()) {
1410       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1412       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1413       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1414     }
1415     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1418     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1419     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1422     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1423     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1424     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1425
1426     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1431     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1439
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1446
1447     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1448     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1449
1450     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1451
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1453     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1455     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1457     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1461
1462     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1469
1470     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1477     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1478
1479     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1482     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1483     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1484     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1485
1486     if (Subtarget->hasCDI()) {
1487       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1488       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1489     }
1490
1491     // Custom lower several nodes.
1492     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1493              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1494       MVT VT = (MVT::SimpleValueType)i;
1495
1496       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1497       // Extract subvector is special because the value type
1498       // (result) is 256/128-bit but the source is 512-bit wide.
1499       if (VT.is128BitVector() || VT.is256BitVector())
1500         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1501
1502       if (VT.getVectorElementType() == MVT::i1)
1503         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1504
1505       // Do not attempt to custom lower other non-512-bit vectors
1506       if (!VT.is512BitVector())
1507         continue;
1508
1509       if ( EltSize >= 32) {
1510         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1511         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1512         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1513         setOperationAction(ISD::VSELECT,             VT, Legal);
1514         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1515         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1516         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1517       }
1518     }
1519     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1520       MVT VT = (MVT::SimpleValueType)i;
1521
1522       // Do not attempt to promote non-256-bit vectors
1523       if (!VT.is512BitVector())
1524         continue;
1525
1526       setOperationAction(ISD::SELECT, VT, Promote);
1527       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1528     }
1529   }// has  AVX-512
1530
1531   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534   }
1535
1536   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1537   // of this type with custom code.
1538   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1539            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1540     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1541                        Custom);
1542   }
1543
1544   // We want to custom lower some of our intrinsics.
1545   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1547   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1548   if (!Subtarget->is64Bit())
1549     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1550
1551   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1552   // handle type legalization for these operations here.
1553   //
1554   // FIXME: We really should do custom legalization for addition and
1555   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1556   // than generic legalization for 64-bit multiplication-with-overflow, though.
1557   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1558     // Add/Sub/Mul with overflow operations are custom lowered.
1559     MVT VT = IntVTs[i];
1560     setOperationAction(ISD::SADDO, VT, Custom);
1561     setOperationAction(ISD::UADDO, VT, Custom);
1562     setOperationAction(ISD::SSUBO, VT, Custom);
1563     setOperationAction(ISD::USUBO, VT, Custom);
1564     setOperationAction(ISD::SMULO, VT, Custom);
1565     setOperationAction(ISD::UMULO, VT, Custom);
1566   }
1567
1568   // There are no 8-bit 3-address imul/mul instructions
1569   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1570   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1571
1572   if (!Subtarget->is64Bit()) {
1573     // These libcalls are not available in 32-bit.
1574     setLibcallName(RTLIB::SHL_I128, nullptr);
1575     setLibcallName(RTLIB::SRL_I128, nullptr);
1576     setLibcallName(RTLIB::SRA_I128, nullptr);
1577   }
1578
1579   // Combine sin / cos into one node or libcall if possible.
1580   if (Subtarget->hasSinCos()) {
1581     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1582     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1583     if (Subtarget->isTargetDarwin()) {
1584       // For MacOSX, we don't want to the normal expansion of a libcall to
1585       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1586       // traffic.
1587       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1588       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1589     }
1590   }
1591
1592   if (Subtarget->isTargetWin64()) {
1593     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1595     setOperationAction(ISD::SREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UREM, MVT::i128, Custom);
1597     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1598     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1599   }
1600
1601   // We have target-specific dag combine patterns for the following nodes:
1602   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1603   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1604   setTargetDAGCombine(ISD::VSELECT);
1605   setTargetDAGCombine(ISD::SELECT);
1606   setTargetDAGCombine(ISD::SHL);
1607   setTargetDAGCombine(ISD::SRA);
1608   setTargetDAGCombine(ISD::SRL);
1609   setTargetDAGCombine(ISD::OR);
1610   setTargetDAGCombine(ISD::AND);
1611   setTargetDAGCombine(ISD::ADD);
1612   setTargetDAGCombine(ISD::FADD);
1613   setTargetDAGCombine(ISD::FSUB);
1614   setTargetDAGCombine(ISD::FMA);
1615   setTargetDAGCombine(ISD::SUB);
1616   setTargetDAGCombine(ISD::LOAD);
1617   setTargetDAGCombine(ISD::STORE);
1618   setTargetDAGCombine(ISD::ZERO_EXTEND);
1619   setTargetDAGCombine(ISD::ANY_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND);
1621   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1622   setTargetDAGCombine(ISD::TRUNCATE);
1623   setTargetDAGCombine(ISD::SINT_TO_FP);
1624   setTargetDAGCombine(ISD::SETCC);
1625   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1626   setTargetDAGCombine(ISD::BUILD_VECTOR);
1627   if (Subtarget->is64Bit())
1628     setTargetDAGCombine(ISD::MUL);
1629   setTargetDAGCombine(ISD::XOR);
1630
1631   computeRegisterProperties();
1632
1633   // On Darwin, -Os means optimize for size without hurting performance,
1634   // do not reduce the limit.
1635   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1636   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1637   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1638   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1639   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1640   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1641   setPrefLoopAlignment(4); // 2^4 bytes.
1642
1643   // Predictable cmov don't hurt on atom because it's in-order.
1644   PredictableSelectIsExpensive = !Subtarget->isAtom();
1645
1646   setPrefFunctionAlignment(4); // 2^4 bytes.
1647 }
1648
1649 // This has so far only been implemented for 64-bit MachO.
1650 bool X86TargetLowering::useLoadStackGuardNode() const {
1651   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1652          Subtarget->is64Bit();
1653 }
1654
1655 TargetLoweringBase::LegalizeTypeAction
1656 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1657   if (ExperimentalVectorWideningLegalization &&
1658       VT.getVectorNumElements() != 1 &&
1659       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1660     return TypeWidenVector;
1661
1662   return TargetLoweringBase::getPreferredVectorAction(VT);
1663 }
1664
1665 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1666   if (!VT.isVector())
1667     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1668
1669   if (Subtarget->hasAVX512())
1670     switch(VT.getVectorNumElements()) {
1671     case  8: return MVT::v8i1;
1672     case 16: return MVT::v16i1;
1673   }
1674
1675   return VT.changeVectorElementTypeToInteger();
1676 }
1677
1678 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1679 /// the desired ByVal argument alignment.
1680 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1681   if (MaxAlign == 16)
1682     return;
1683   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1684     if (VTy->getBitWidth() == 128)
1685       MaxAlign = 16;
1686   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1687     unsigned EltAlign = 0;
1688     getMaxByValAlign(ATy->getElementType(), EltAlign);
1689     if (EltAlign > MaxAlign)
1690       MaxAlign = EltAlign;
1691   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1692     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1693       unsigned EltAlign = 0;
1694       getMaxByValAlign(STy->getElementType(i), EltAlign);
1695       if (EltAlign > MaxAlign)
1696         MaxAlign = EltAlign;
1697       if (MaxAlign == 16)
1698         break;
1699     }
1700   }
1701 }
1702
1703 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1704 /// function arguments in the caller parameter area. For X86, aggregates
1705 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1706 /// are at 4-byte boundaries.
1707 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1708   if (Subtarget->is64Bit()) {
1709     // Max of 8 and alignment of type.
1710     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1711     if (TyAlign > 8)
1712       return TyAlign;
1713     return 8;
1714   }
1715
1716   unsigned Align = 4;
1717   if (Subtarget->hasSSE1())
1718     getMaxByValAlign(Ty, Align);
1719   return Align;
1720 }
1721
1722 /// getOptimalMemOpType - Returns the target specific optimal type for load
1723 /// and store operations as a result of memset, memcpy, and memmove
1724 /// lowering. If DstAlign is zero that means it's safe to destination
1725 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1726 /// means there isn't a need to check it against alignment requirement,
1727 /// probably because the source does not need to be loaded. If 'IsMemset' is
1728 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1729 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1730 /// source is constant so it does not need to be loaded.
1731 /// It returns EVT::Other if the type should be determined using generic
1732 /// target-independent logic.
1733 EVT
1734 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1735                                        unsigned DstAlign, unsigned SrcAlign,
1736                                        bool IsMemset, bool ZeroMemset,
1737                                        bool MemcpyStrSrc,
1738                                        MachineFunction &MF) const {
1739   const Function *F = MF.getFunction();
1740   if ((!IsMemset || ZeroMemset) &&
1741       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1742                                        Attribute::NoImplicitFloat)) {
1743     if (Size >= 16 &&
1744         (Subtarget->isUnalignedMemAccessFast() ||
1745          ((DstAlign == 0 || DstAlign >= 16) &&
1746           (SrcAlign == 0 || SrcAlign >= 16)))) {
1747       if (Size >= 32) {
1748         if (Subtarget->hasInt256())
1749           return MVT::v8i32;
1750         if (Subtarget->hasFp256())
1751           return MVT::v8f32;
1752       }
1753       if (Subtarget->hasSSE2())
1754         return MVT::v4i32;
1755       if (Subtarget->hasSSE1())
1756         return MVT::v4f32;
1757     } else if (!MemcpyStrSrc && Size >= 8 &&
1758                !Subtarget->is64Bit() &&
1759                Subtarget->hasSSE2()) {
1760       // Do not use f64 to lower memcpy if source is string constant. It's
1761       // better to use i32 to avoid the loads.
1762       return MVT::f64;
1763     }
1764   }
1765   if (Subtarget->is64Bit() && Size >= 8)
1766     return MVT::i64;
1767   return MVT::i32;
1768 }
1769
1770 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1771   if (VT == MVT::f32)
1772     return X86ScalarSSEf32;
1773   else if (VT == MVT::f64)
1774     return X86ScalarSSEf64;
1775   return true;
1776 }
1777
1778 bool
1779 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1780                                                  unsigned,
1781                                                  bool *Fast) const {
1782   if (Fast)
1783     *Fast = Subtarget->isUnalignedMemAccessFast();
1784   return true;
1785 }
1786
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function.  The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792   // symbol.
1793   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794       Subtarget->isPICStyleGOT())
1795     return MachineJumpTableInfo::EK_Custom32;
1796
1797   // Otherwise, use the normal jump table encoding heuristics.
1798   return TargetLowering::getJumpTableEncoding();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 /// jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 /// MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ?
1848       (const TargetRegisterClass*)&X86::GR64RegClass :
1849       (const TargetRegisterClass*)&X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1905                  RVLocs, Context);
1906   return CCInfo.CheckReturn(Outs, RetCC_X86);
1907 }
1908
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911   return ScratchRegs;
1912 }
1913
1914 SDValue
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916                                CallingConv::ID CallConv, bool isVarArg,
1917                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1918                                const SmallVectorImpl<SDValue> &OutVals,
1919                                SDLoc dl, SelectionDAG &DAG) const {
1920   MachineFunction &MF = DAG.getMachineFunction();
1921   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922
1923   SmallVector<CCValAssign, 16> RVLocs;
1924   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925                  RVLocs, *DAG.getContext());
1926   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927
1928   SDValue Flag;
1929   SmallVector<SDValue, 6> RetOps;
1930   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931   // Operand #1 = Bytes To Pop
1932   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1933                    MVT::i16));
1934
1935   // Copy the result values into the output registers.
1936   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937     CCValAssign &VA = RVLocs[i];
1938     assert(VA.isRegLoc() && "Can only return in registers!");
1939     SDValue ValToCopy = OutVals[i];
1940     EVT ValVT = ValToCopy.getValueType();
1941
1942     // Promote values to the appropriate types
1943     if (VA.getLocInfo() == CCValAssign::SExt)
1944       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::ZExt)
1946       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::AExt)
1948       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");  
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::ST0 ||
1972         VA.getLocReg() == X86::ST1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010     MachineFunction &MF = DAG.getMachineFunction();
2011     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012     unsigned Reg = FuncInfo->getSRetReturnReg();
2013     assert(Reg &&
2014            "SRetReturnReg should have been set in LowerFormalArguments().");
2015     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2016
2017     unsigned RetValReg
2018         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019           X86::RAX : X86::EAX;
2020     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021     Flag = Chain.getValue(1);
2022
2023     // RAX/EAX now acts like a return value.
2024     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025   }
2026
2027   RetOps[0] = Chain;  // Update chain.
2028
2029   // Add the flag if we have it.
2030   if (Flag.getNode())
2031     RetOps.push_back(Flag);
2032
2033   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 }
2035
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037   if (N->getNumValues() != 1)
2038     return false;
2039   if (!N->hasNUsesOfValue(1, 0))
2040     return false;
2041
2042   SDValue TCChain = Chain;
2043   SDNode *Copy = *N->use_begin();
2044   if (Copy->getOpcode() == ISD::CopyToReg) {
2045     // If the copy has a glue operand, we conservatively assume it isn't safe to
2046     // perform a tail call.
2047     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048       return false;
2049     TCChain = Copy->getOperand(0);
2050   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051     return false;
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != X86ISD::RET_FLAG)
2057       return false;
2058     HasRet = true;
2059   }
2060
2061   if (!HasRet)
2062     return false;
2063
2064   Chain = TCChain;
2065   return true;
2066 }
2067
2068 MVT
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070                                             ISD::NodeType ExtendKind) const {
2071   MVT ReturnMVT;
2072   // TODO: Is this also valid on 32-bit?
2073   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074     ReturnMVT = MVT::i8;
2075   else
2076     ReturnMVT = MVT::i32;
2077
2078   MVT MinVT = getRegisterType(ReturnMVT);
2079   return VT.bitsLT(MinVT) ? MinVT : VT;
2080 }
2081
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2084 ///
2085 SDValue
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087                                    CallingConv::ID CallConv, bool isVarArg,
2088                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2089                                    SDLoc dl, SelectionDAG &DAG,
2090                                    SmallVectorImpl<SDValue> &InVals) const {
2091
2092   // Assign locations to each value returned by this call.
2093   SmallVector<CCValAssign, 16> RVLocs;
2094   bool Is64Bit = Subtarget->is64Bit();
2095   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096                  DAG.getTarget(), RVLocs, *DAG.getContext());
2097   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2098
2099   // Copy all of the result registers out of their specified physreg.
2100   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101     CCValAssign &VA = RVLocs[i];
2102     EVT CopyVT = VA.getValVT();
2103
2104     // If this is x86-64, and we disabled SSE, we can't return FP values
2105     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107       report_fatal_error("SSE register return with SSE disabled");
2108     }
2109
2110     SDValue Val;
2111
2112     // If this is a call to a function that returns an fp value on the floating
2113     // point stack, we must guarantee the value is popped from the stack, so
2114     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2115     // if the return value is not used. We use the FpPOP_RETVAL instruction
2116     // instead.
2117     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2118       // If we prefer to use the value in xmm registers, copy it out as f80 and
2119       // use a truncate to move it from fp stack reg to xmm reg.
2120       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2121       SDValue Ops[] = { Chain, InFlag };
2122       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2123                                          MVT::Other, MVT::Glue, Ops), 1);
2124       Val = Chain.getValue(0);
2125
2126       // Round the f80 to the right size, which also moves it to the appropriate
2127       // xmm register.
2128       if (CopyVT != VA.getValVT())
2129         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2130                           // This truncation won't change the value.
2131                           DAG.getIntPtrConstant(1));
2132     } else {
2133       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2134                                  CopyVT, InFlag).getValue(1);
2135       Val = Chain.getValue(0);
2136     }
2137     InFlag = Chain.getValue(2);
2138     InVals.push_back(Val);
2139   }
2140
2141   return Chain;
2142 }
2143
2144 //===----------------------------------------------------------------------===//
2145 //                C & StdCall & Fast Calling Convention implementation
2146 //===----------------------------------------------------------------------===//
2147 //  StdCall calling convention seems to be standard for many Windows' API
2148 //  routines and around. It differs from C calling convention just a little:
2149 //  callee should clean up the stack, not caller. Symbols should be also
2150 //  decorated in some fancy way :) It doesn't support any vector arguments.
2151 //  For info on fast calling convention see Fast Calling Convention (tail call)
2152 //  implementation LowerX86_32FastCCCallTo.
2153
2154 /// CallIsStructReturn - Determines whether a call uses struct return
2155 /// semantics.
2156 enum StructReturnType {
2157   NotStructReturn,
2158   RegStructReturn,
2159   StackStructReturn
2160 };
2161 static StructReturnType
2162 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2163   if (Outs.empty())
2164     return NotStructReturn;
2165
2166   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2167   if (!Flags.isSRet())
2168     return NotStructReturn;
2169   if (Flags.isInReg())
2170     return RegStructReturn;
2171   return StackStructReturn;
2172 }
2173
2174 /// ArgsAreStructReturn - Determines whether a function uses struct
2175 /// return semantics.
2176 static StructReturnType
2177 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2178   if (Ins.empty())
2179     return NotStructReturn;
2180
2181   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2182   if (!Flags.isSRet())
2183     return NotStructReturn;
2184   if (Flags.isInReg())
2185     return RegStructReturn;
2186   return StackStructReturn;
2187 }
2188
2189 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2190 /// by "Src" to address "Dst" with size and alignment information specified by
2191 /// the specific parameter attribute. The copy will be passed as a byval
2192 /// function parameter.
2193 static SDValue
2194 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2195                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2196                           SDLoc dl) {
2197   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2198
2199   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2200                        /*isVolatile*/false, /*AlwaysInline=*/true,
2201                        MachinePointerInfo(), MachinePointerInfo());
2202 }
2203
2204 /// IsTailCallConvention - Return true if the calling convention is one that
2205 /// supports tail call optimization.
2206 static bool IsTailCallConvention(CallingConv::ID CC) {
2207   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2208           CC == CallingConv::HiPE);
2209 }
2210
2211 /// \brief Return true if the calling convention is a C calling convention.
2212 static bool IsCCallConvention(CallingConv::ID CC) {
2213   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2214           CC == CallingConv::X86_64_SysV);
2215 }
2216
2217 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2218   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2219     return false;
2220
2221   CallSite CS(CI);
2222   CallingConv::ID CalleeCC = CS.getCallingConv();
2223   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2224     return false;
2225
2226   return true;
2227 }
2228
2229 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2230 /// a tailcall target by changing its ABI.
2231 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2232                                    bool GuaranteedTailCallOpt) {
2233   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2234 }
2235
2236 SDValue
2237 X86TargetLowering::LowerMemArgument(SDValue Chain,
2238                                     CallingConv::ID CallConv,
2239                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2240                                     SDLoc dl, SelectionDAG &DAG,
2241                                     const CCValAssign &VA,
2242                                     MachineFrameInfo *MFI,
2243                                     unsigned i) const {
2244   // Create the nodes corresponding to a load from this parameter slot.
2245   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2246   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2247       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2248   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2249   EVT ValVT;
2250
2251   // If value is passed by pointer we have address passed instead of the value
2252   // itself.
2253   if (VA.getLocInfo() == CCValAssign::Indirect)
2254     ValVT = VA.getLocVT();
2255   else
2256     ValVT = VA.getValVT();
2257
2258   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2259   // changed with more analysis.
2260   // In case of tail call optimization mark all arguments mutable. Since they
2261   // could be overwritten by lowering of arguments in case of a tail call.
2262   if (Flags.isByVal()) {
2263     unsigned Bytes = Flags.getByValSize();
2264     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2265     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2266     return DAG.getFrameIndex(FI, getPointerTy());
2267   } else {
2268     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2269                                     VA.getLocMemOffset(), isImmutable);
2270     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2271     return DAG.getLoad(ValVT, dl, Chain, FIN,
2272                        MachinePointerInfo::getFixedStack(FI),
2273                        false, false, false, 0);
2274   }
2275 }
2276
2277 SDValue
2278 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2279                                         CallingConv::ID CallConv,
2280                                         bool isVarArg,
2281                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2282                                         SDLoc dl,
2283                                         SelectionDAG &DAG,
2284                                         SmallVectorImpl<SDValue> &InVals)
2285                                           const {
2286   MachineFunction &MF = DAG.getMachineFunction();
2287   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2288
2289   const Function* Fn = MF.getFunction();
2290   if (Fn->hasExternalLinkage() &&
2291       Subtarget->isTargetCygMing() &&
2292       Fn->getName() == "main")
2293     FuncInfo->setForceFramePointer(true);
2294
2295   MachineFrameInfo *MFI = MF.getFrameInfo();
2296   bool Is64Bit = Subtarget->is64Bit();
2297   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2298
2299   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2300          "Var args not supported with calling convention fastcc, ghc or hipe");
2301
2302   // Assign locations to all of the incoming arguments.
2303   SmallVector<CCValAssign, 16> ArgLocs;
2304   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2305                  ArgLocs, *DAG.getContext());
2306
2307   // Allocate shadow area for Win64
2308   if (IsWin64)
2309     CCInfo.AllocateStack(32, 8);
2310
2311   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2312
2313   unsigned LastVal = ~0U;
2314   SDValue ArgValue;
2315   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2316     CCValAssign &VA = ArgLocs[i];
2317     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2318     // places.
2319     assert(VA.getValNo() != LastVal &&
2320            "Don't support value assigned to multiple locs yet");
2321     (void)LastVal;
2322     LastVal = VA.getValNo();
2323
2324     if (VA.isRegLoc()) {
2325       EVT RegVT = VA.getLocVT();
2326       const TargetRegisterClass *RC;
2327       if (RegVT == MVT::i32)
2328         RC = &X86::GR32RegClass;
2329       else if (Is64Bit && RegVT == MVT::i64)
2330         RC = &X86::GR64RegClass;
2331       else if (RegVT == MVT::f32)
2332         RC = &X86::FR32RegClass;
2333       else if (RegVT == MVT::f64)
2334         RC = &X86::FR64RegClass;
2335       else if (RegVT.is512BitVector())
2336         RC = &X86::VR512RegClass;
2337       else if (RegVT.is256BitVector())
2338         RC = &X86::VR256RegClass;
2339       else if (RegVT.is128BitVector())
2340         RC = &X86::VR128RegClass;
2341       else if (RegVT == MVT::x86mmx)
2342         RC = &X86::VR64RegClass;
2343       else if (RegVT == MVT::i1)
2344         RC = &X86::VK1RegClass;
2345       else if (RegVT == MVT::v8i1)
2346         RC = &X86::VK8RegClass;
2347       else if (RegVT == MVT::v16i1)
2348         RC = &X86::VK16RegClass;
2349       else if (RegVT == MVT::v32i1)
2350         RC = &X86::VK32RegClass;
2351       else if (RegVT == MVT::v64i1)
2352         RC = &X86::VK64RegClass;
2353       else
2354         llvm_unreachable("Unknown argument type!");
2355
2356       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2357       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2358
2359       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2360       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2361       // right size.
2362       if (VA.getLocInfo() == CCValAssign::SExt)
2363         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2364                                DAG.getValueType(VA.getValVT()));
2365       else if (VA.getLocInfo() == CCValAssign::ZExt)
2366         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2367                                DAG.getValueType(VA.getValVT()));
2368       else if (VA.getLocInfo() == CCValAssign::BCvt)
2369         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2370
2371       if (VA.isExtInLoc()) {
2372         // Handle MMX values passed in XMM regs.
2373         if (RegVT.isVector())
2374           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2375         else
2376           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2377       }
2378     } else {
2379       assert(VA.isMemLoc());
2380       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2381     }
2382
2383     // If value is passed via pointer - do a load.
2384     if (VA.getLocInfo() == CCValAssign::Indirect)
2385       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2386                              MachinePointerInfo(), false, false, false, 0);
2387
2388     InVals.push_back(ArgValue);
2389   }
2390
2391   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2392     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2393       // The x86-64 ABIs require that for returning structs by value we copy
2394       // the sret argument into %rax/%eax (depending on ABI) for the return.
2395       // Win32 requires us to put the sret argument to %eax as well.
2396       // Save the argument into a virtual register so that we can access it
2397       // from the return points.
2398       if (Ins[i].Flags.isSRet()) {
2399         unsigned Reg = FuncInfo->getSRetReturnReg();
2400         if (!Reg) {
2401           MVT PtrTy = getPointerTy();
2402           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2403           FuncInfo->setSRetReturnReg(Reg);
2404         }
2405         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2406         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2407         break;
2408       }
2409     }
2410   }
2411
2412   unsigned StackSize = CCInfo.getNextStackOffset();
2413   // Align stack specially for tail calls.
2414   if (FuncIsMadeTailCallSafe(CallConv,
2415                              MF.getTarget().Options.GuaranteedTailCallOpt))
2416     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2417
2418   // If the function takes variable number of arguments, make a frame index for
2419   // the start of the first vararg value... for expansion of llvm.va_start.
2420   if (isVarArg) {
2421     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2422                     CallConv != CallingConv::X86_ThisCall)) {
2423       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2424     }
2425     if (Is64Bit) {
2426       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2427
2428       // FIXME: We should really autogenerate these arrays
2429       static const MCPhysReg GPR64ArgRegsWin64[] = {
2430         X86::RCX, X86::RDX, X86::R8,  X86::R9
2431       };
2432       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2433         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2434       };
2435       static const MCPhysReg XMMArgRegs64Bit[] = {
2436         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2437         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2438       };
2439       const MCPhysReg *GPR64ArgRegs;
2440       unsigned NumXMMRegs = 0;
2441
2442       if (IsWin64) {
2443         // The XMM registers which might contain var arg parameters are shadowed
2444         // in their paired GPR.  So we only need to save the GPR to their home
2445         // slots.
2446         TotalNumIntRegs = 4;
2447         GPR64ArgRegs = GPR64ArgRegsWin64;
2448       } else {
2449         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2450         GPR64ArgRegs = GPR64ArgRegs64Bit;
2451
2452         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2453                                                 TotalNumXMMRegs);
2454       }
2455       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2456                                                        TotalNumIntRegs);
2457
2458       bool NoImplicitFloatOps = Fn->getAttributes().
2459         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2460       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2461              "SSE register cannot be used when SSE is disabled!");
2462       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2463                NoImplicitFloatOps) &&
2464              "SSE register cannot be used when SSE is disabled!");
2465       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2466           !Subtarget->hasSSE1())
2467         // Kernel mode asks for SSE to be disabled, so don't push them
2468         // on the stack.
2469         TotalNumXMMRegs = 0;
2470
2471       if (IsWin64) {
2472         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2473         // Get to the caller-allocated home save location.  Add 8 to account
2474         // for the return address.
2475         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2476         FuncInfo->setRegSaveFrameIndex(
2477           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2478         // Fixup to set vararg frame on shadow area (4 x i64).
2479         if (NumIntRegs < 4)
2480           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2481       } else {
2482         // For X86-64, if there are vararg parameters that are passed via
2483         // registers, then we must store them to their spots on the stack so
2484         // they may be loaded by deferencing the result of va_next.
2485         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2486         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2487         FuncInfo->setRegSaveFrameIndex(
2488           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2489                                false));
2490       }
2491
2492       // Store the integer parameter registers.
2493       SmallVector<SDValue, 8> MemOps;
2494       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2495                                         getPointerTy());
2496       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2497       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2498         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2499                                   DAG.getIntPtrConstant(Offset));
2500         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2501                                      &X86::GR64RegClass);
2502         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2503         SDValue Store =
2504           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2505                        MachinePointerInfo::getFixedStack(
2506                          FuncInfo->getRegSaveFrameIndex(), Offset),
2507                        false, false, 0);
2508         MemOps.push_back(Store);
2509         Offset += 8;
2510       }
2511
2512       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2513         // Now store the XMM (fp + vector) parameter registers.
2514         SmallVector<SDValue, 11> SaveXMMOps;
2515         SaveXMMOps.push_back(Chain);
2516
2517         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2518         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2519         SaveXMMOps.push_back(ALVal);
2520
2521         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2522                                FuncInfo->getRegSaveFrameIndex()));
2523         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2524                                FuncInfo->getVarArgsFPOffset()));
2525
2526         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2527           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2528                                        &X86::VR128RegClass);
2529           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2530           SaveXMMOps.push_back(Val);
2531         }
2532         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2533                                      MVT::Other, SaveXMMOps));
2534       }
2535
2536       if (!MemOps.empty())
2537         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2538     }
2539   }
2540
2541   // Some CCs need callee pop.
2542   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2543                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2544     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2545   } else {
2546     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2547     // If this is an sret function, the return should pop the hidden pointer.
2548     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2549         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2550         argsAreStructReturn(Ins) == StackStructReturn)
2551       FuncInfo->setBytesToPopOnReturn(4);
2552   }
2553
2554   if (!Is64Bit) {
2555     // RegSaveFrameIndex is X86-64 only.
2556     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2557     if (CallConv == CallingConv::X86_FastCall ||
2558         CallConv == CallingConv::X86_ThisCall)
2559       // fastcc functions can't have varargs.
2560       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2561   }
2562
2563   FuncInfo->setArgumentStackSize(StackSize);
2564
2565   return Chain;
2566 }
2567
2568 SDValue
2569 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2570                                     SDValue StackPtr, SDValue Arg,
2571                                     SDLoc dl, SelectionDAG &DAG,
2572                                     const CCValAssign &VA,
2573                                     ISD::ArgFlagsTy Flags) const {
2574   unsigned LocMemOffset = VA.getLocMemOffset();
2575   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2576   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2577   if (Flags.isByVal())
2578     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2579
2580   return DAG.getStore(Chain, dl, Arg, PtrOff,
2581                       MachinePointerInfo::getStack(LocMemOffset),
2582                       false, false, 0);
2583 }
2584
2585 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2586 /// optimization is performed and it is required.
2587 SDValue
2588 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2589                                            SDValue &OutRetAddr, SDValue Chain,
2590                                            bool IsTailCall, bool Is64Bit,
2591                                            int FPDiff, SDLoc dl) const {
2592   // Adjust the Return address stack slot.
2593   EVT VT = getPointerTy();
2594   OutRetAddr = getReturnAddressFrameIndex(DAG);
2595
2596   // Load the "old" Return address.
2597   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2598                            false, false, false, 0);
2599   return SDValue(OutRetAddr.getNode(), 1);
2600 }
2601
2602 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2603 /// optimization is performed and it is required (FPDiff!=0).
2604 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2605                                         SDValue Chain, SDValue RetAddrFrIdx,
2606                                         EVT PtrVT, unsigned SlotSize,
2607                                         int FPDiff, SDLoc dl) {
2608   // Store the return address to the appropriate stack slot.
2609   if (!FPDiff) return Chain;
2610   // Calculate the new stack slot for the return address.
2611   int NewReturnAddrFI =
2612     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2613                                          false);
2614   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2615   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2616                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2617                        false, false, 0);
2618   return Chain;
2619 }
2620
2621 SDValue
2622 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2623                              SmallVectorImpl<SDValue> &InVals) const {
2624   SelectionDAG &DAG                     = CLI.DAG;
2625   SDLoc &dl                             = CLI.DL;
2626   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2627   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2628   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2629   SDValue Chain                         = CLI.Chain;
2630   SDValue Callee                        = CLI.Callee;
2631   CallingConv::ID CallConv              = CLI.CallConv;
2632   bool &isTailCall                      = CLI.IsTailCall;
2633   bool isVarArg                         = CLI.IsVarArg;
2634
2635   MachineFunction &MF = DAG.getMachineFunction();
2636   bool Is64Bit        = Subtarget->is64Bit();
2637   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2638   StructReturnType SR = callIsStructReturn(Outs);
2639   bool IsSibcall      = false;
2640
2641   if (MF.getTarget().Options.DisableTailCalls)
2642     isTailCall = false;
2643
2644   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2645   if (IsMustTail) {
2646     // Force this to be a tail call.  The verifier rules are enough to ensure
2647     // that we can lower this successfully without moving the return address
2648     // around.
2649     isTailCall = true;
2650   } else if (isTailCall) {
2651     // Check if it's really possible to do a tail call.
2652     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2653                     isVarArg, SR != NotStructReturn,
2654                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2655                     Outs, OutVals, Ins, DAG);
2656
2657     // Sibcalls are automatically detected tailcalls which do not require
2658     // ABI changes.
2659     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2660       IsSibcall = true;
2661
2662     if (isTailCall)
2663       ++NumTailCalls;
2664   }
2665
2666   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2667          "Var args not supported with calling convention fastcc, ghc or hipe");
2668
2669   // Analyze operands of the call, assigning locations to each operand.
2670   SmallVector<CCValAssign, 16> ArgLocs;
2671   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2672                  ArgLocs, *DAG.getContext());
2673
2674   // Allocate shadow area for Win64
2675   if (IsWin64)
2676     CCInfo.AllocateStack(32, 8);
2677
2678   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2679
2680   // Get a count of how many bytes are to be pushed on the stack.
2681   unsigned NumBytes = CCInfo.getNextStackOffset();
2682   if (IsSibcall)
2683     // This is a sibcall. The memory operands are available in caller's
2684     // own caller's stack.
2685     NumBytes = 0;
2686   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2687            IsTailCallConvention(CallConv))
2688     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2689
2690   int FPDiff = 0;
2691   if (isTailCall && !IsSibcall && !IsMustTail) {
2692     // Lower arguments at fp - stackoffset + fpdiff.
2693     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2694     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2695
2696     FPDiff = NumBytesCallerPushed - NumBytes;
2697
2698     // Set the delta of movement of the returnaddr stackslot.
2699     // But only set if delta is greater than previous delta.
2700     if (FPDiff < X86Info->getTCReturnAddrDelta())
2701       X86Info->setTCReturnAddrDelta(FPDiff);
2702   }
2703
2704   unsigned NumBytesToPush = NumBytes;
2705   unsigned NumBytesToPop = NumBytes;
2706
2707   // If we have an inalloca argument, all stack space has already been allocated
2708   // for us and be right at the top of the stack.  We don't support multiple
2709   // arguments passed in memory when using inalloca.
2710   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2711     NumBytesToPush = 0;
2712     if (!ArgLocs.back().isMemLoc())
2713       report_fatal_error("cannot use inalloca attribute on a register "
2714                          "parameter");
2715     if (ArgLocs.back().getLocMemOffset() != 0)
2716       report_fatal_error("any parameter with the inalloca attribute must be "
2717                          "the only memory argument");
2718   }
2719
2720   if (!IsSibcall)
2721     Chain = DAG.getCALLSEQ_START(
2722         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2723
2724   SDValue RetAddrFrIdx;
2725   // Load return address for tail calls.
2726   if (isTailCall && FPDiff)
2727     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2728                                     Is64Bit, FPDiff, dl);
2729
2730   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2731   SmallVector<SDValue, 8> MemOpChains;
2732   SDValue StackPtr;
2733
2734   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2735   // of tail call optimization arguments are handle later.
2736   const X86RegisterInfo *RegInfo =
2737     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2738   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2739     // Skip inalloca arguments, they have already been written.
2740     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2741     if (Flags.isInAlloca())
2742       continue;
2743
2744     CCValAssign &VA = ArgLocs[i];
2745     EVT RegVT = VA.getLocVT();
2746     SDValue Arg = OutVals[i];
2747     bool isByVal = Flags.isByVal();
2748
2749     // Promote the value if needed.
2750     switch (VA.getLocInfo()) {
2751     default: llvm_unreachable("Unknown loc info!");
2752     case CCValAssign::Full: break;
2753     case CCValAssign::SExt:
2754       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2755       break;
2756     case CCValAssign::ZExt:
2757       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2758       break;
2759     case CCValAssign::AExt:
2760       if (RegVT.is128BitVector()) {
2761         // Special case: passing MMX values in XMM registers.
2762         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2763         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2764         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2765       } else
2766         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2767       break;
2768     case CCValAssign::BCvt:
2769       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2770       break;
2771     case CCValAssign::Indirect: {
2772       // Store the argument.
2773       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2774       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2775       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2776                            MachinePointerInfo::getFixedStack(FI),
2777                            false, false, 0);
2778       Arg = SpillSlot;
2779       break;
2780     }
2781     }
2782
2783     if (VA.isRegLoc()) {
2784       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2785       if (isVarArg && IsWin64) {
2786         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2787         // shadow reg if callee is a varargs function.
2788         unsigned ShadowReg = 0;
2789         switch (VA.getLocReg()) {
2790         case X86::XMM0: ShadowReg = X86::RCX; break;
2791         case X86::XMM1: ShadowReg = X86::RDX; break;
2792         case X86::XMM2: ShadowReg = X86::R8; break;
2793         case X86::XMM3: ShadowReg = X86::R9; break;
2794         }
2795         if (ShadowReg)
2796           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2797       }
2798     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2799       assert(VA.isMemLoc());
2800       if (!StackPtr.getNode())
2801         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2802                                       getPointerTy());
2803       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2804                                              dl, DAG, VA, Flags));
2805     }
2806   }
2807
2808   if (!MemOpChains.empty())
2809     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2810
2811   if (Subtarget->isPICStyleGOT()) {
2812     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2813     // GOT pointer.
2814     if (!isTailCall) {
2815       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2816                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2817     } else {
2818       // If we are tail calling and generating PIC/GOT style code load the
2819       // address of the callee into ECX. The value in ecx is used as target of
2820       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2821       // for tail calls on PIC/GOT architectures. Normally we would just put the
2822       // address of GOT into ebx and then call target@PLT. But for tail calls
2823       // ebx would be restored (since ebx is callee saved) before jumping to the
2824       // target@PLT.
2825
2826       // Note: The actual moving to ECX is done further down.
2827       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2828       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2829           !G->getGlobal()->hasProtectedVisibility())
2830         Callee = LowerGlobalAddress(Callee, DAG);
2831       else if (isa<ExternalSymbolSDNode>(Callee))
2832         Callee = LowerExternalSymbol(Callee, DAG);
2833     }
2834   }
2835
2836   if (Is64Bit && isVarArg && !IsWin64) {
2837     // From AMD64 ABI document:
2838     // For calls that may call functions that use varargs or stdargs
2839     // (prototype-less calls or calls to functions containing ellipsis (...) in
2840     // the declaration) %al is used as hidden argument to specify the number
2841     // of SSE registers used. The contents of %al do not need to match exactly
2842     // the number of registers, but must be an ubound on the number of SSE
2843     // registers used and is in the range 0 - 8 inclusive.
2844
2845     // Count the number of XMM registers allocated.
2846     static const MCPhysReg XMMArgRegs[] = {
2847       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2848       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2849     };
2850     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2851     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2852            && "SSE registers cannot be used when SSE is disabled");
2853
2854     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2855                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2856   }
2857
2858   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2859   // don't need this because the eligibility check rejects calls that require
2860   // shuffling arguments passed in memory.
2861   if (!IsSibcall && isTailCall) {
2862     // Force all the incoming stack arguments to be loaded from the stack
2863     // before any new outgoing arguments are stored to the stack, because the
2864     // outgoing stack slots may alias the incoming argument stack slots, and
2865     // the alias isn't otherwise explicit. This is slightly more conservative
2866     // than necessary, because it means that each store effectively depends
2867     // on every argument instead of just those arguments it would clobber.
2868     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2869
2870     SmallVector<SDValue, 8> MemOpChains2;
2871     SDValue FIN;
2872     int FI = 0;
2873     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874       CCValAssign &VA = ArgLocs[i];
2875       if (VA.isRegLoc())
2876         continue;
2877       assert(VA.isMemLoc());
2878       SDValue Arg = OutVals[i];
2879       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2880       // Skip inalloca arguments.  They don't require any work.
2881       if (Flags.isInAlloca())
2882         continue;
2883       // Create frame index.
2884       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2885       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2886       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2887       FIN = DAG.getFrameIndex(FI, getPointerTy());
2888
2889       if (Flags.isByVal()) {
2890         // Copy relative to framepointer.
2891         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2892         if (!StackPtr.getNode())
2893           StackPtr = DAG.getCopyFromReg(Chain, dl,
2894                                         RegInfo->getStackRegister(),
2895                                         getPointerTy());
2896         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2897
2898         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2899                                                          ArgChain,
2900                                                          Flags, DAG, dl));
2901       } else {
2902         // Store relative to framepointer.
2903         MemOpChains2.push_back(
2904           DAG.getStore(ArgChain, dl, Arg, FIN,
2905                        MachinePointerInfo::getFixedStack(FI),
2906                        false, false, 0));
2907       }
2908     }
2909
2910     if (!MemOpChains2.empty())
2911       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2912
2913     // Store the return address to the appropriate stack slot.
2914     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2915                                      getPointerTy(), RegInfo->getSlotSize(),
2916                                      FPDiff, dl);
2917   }
2918
2919   // Build a sequence of copy-to-reg nodes chained together with token chain
2920   // and flag operands which copy the outgoing args into registers.
2921   SDValue InFlag;
2922   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2923     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2924                              RegsToPass[i].second, InFlag);
2925     InFlag = Chain.getValue(1);
2926   }
2927
2928   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2929     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2930     // In the 64-bit large code model, we have to make all calls
2931     // through a register, since the call instruction's 32-bit
2932     // pc-relative offset may not be large enough to hold the whole
2933     // address.
2934   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2935     // If the callee is a GlobalAddress node (quite common, every direct call
2936     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2937     // it.
2938
2939     // We should use extra load for direct calls to dllimported functions in
2940     // non-JIT mode.
2941     const GlobalValue *GV = G->getGlobal();
2942     if (!GV->hasDLLImportStorageClass()) {
2943       unsigned char OpFlags = 0;
2944       bool ExtraLoad = false;
2945       unsigned WrapperKind = ISD::DELETED_NODE;
2946
2947       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2948       // external symbols most go through the PLT in PIC mode.  If the symbol
2949       // has hidden or protected visibility, or if it is static or local, then
2950       // we don't need to use the PLT - we can directly call it.
2951       if (Subtarget->isTargetELF() &&
2952           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2953           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2954         OpFlags = X86II::MO_PLT;
2955       } else if (Subtarget->isPICStyleStubAny() &&
2956                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2957                  (!Subtarget->getTargetTriple().isMacOSX() ||
2958                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2959         // PC-relative references to external symbols should go through $stub,
2960         // unless we're building with the leopard linker or later, which
2961         // automatically synthesizes these stubs.
2962         OpFlags = X86II::MO_DARWIN_STUB;
2963       } else if (Subtarget->isPICStyleRIPRel() &&
2964                  isa<Function>(GV) &&
2965                  cast<Function>(GV)->getAttributes().
2966                    hasAttribute(AttributeSet::FunctionIndex,
2967                                 Attribute::NonLazyBind)) {
2968         // If the function is marked as non-lazy, generate an indirect call
2969         // which loads from the GOT directly. This avoids runtime overhead
2970         // at the cost of eager binding (and one extra byte of encoding).
2971         OpFlags = X86II::MO_GOTPCREL;
2972         WrapperKind = X86ISD::WrapperRIP;
2973         ExtraLoad = true;
2974       }
2975
2976       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2977                                           G->getOffset(), OpFlags);
2978
2979       // Add a wrapper if needed.
2980       if (WrapperKind != ISD::DELETED_NODE)
2981         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2982       // Add extra indirection if needed.
2983       if (ExtraLoad)
2984         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2985                              MachinePointerInfo::getGOT(),
2986                              false, false, false, 0);
2987     }
2988   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2989     unsigned char OpFlags = 0;
2990
2991     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2992     // external symbols should go through the PLT.
2993     if (Subtarget->isTargetELF() &&
2994         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2995       OpFlags = X86II::MO_PLT;
2996     } else if (Subtarget->isPICStyleStubAny() &&
2997                (!Subtarget->getTargetTriple().isMacOSX() ||
2998                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2999       // PC-relative references to external symbols should go through $stub,
3000       // unless we're building with the leopard linker or later, which
3001       // automatically synthesizes these stubs.
3002       OpFlags = X86II::MO_DARWIN_STUB;
3003     }
3004
3005     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3006                                          OpFlags);
3007   }
3008
3009   // Returns a chain & a flag for retval copy to use.
3010   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3011   SmallVector<SDValue, 8> Ops;
3012
3013   if (!IsSibcall && isTailCall) {
3014     Chain = DAG.getCALLSEQ_END(Chain,
3015                                DAG.getIntPtrConstant(NumBytesToPop, true),
3016                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3017     InFlag = Chain.getValue(1);
3018   }
3019
3020   Ops.push_back(Chain);
3021   Ops.push_back(Callee);
3022
3023   if (isTailCall)
3024     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3025
3026   // Add argument registers to the end of the list so that they are known live
3027   // into the call.
3028   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3029     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3030                                   RegsToPass[i].second.getValueType()));
3031
3032   // Add a register mask operand representing the call-preserved registers.
3033   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3034   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3035   assert(Mask && "Missing call preserved mask for calling convention");
3036   Ops.push_back(DAG.getRegisterMask(Mask));
3037
3038   if (InFlag.getNode())
3039     Ops.push_back(InFlag);
3040
3041   if (isTailCall) {
3042     // We used to do:
3043     //// If this is the first return lowered for this function, add the regs
3044     //// to the liveout set for the function.
3045     // This isn't right, although it's probably harmless on x86; liveouts
3046     // should be computed from returns not tail calls.  Consider a void
3047     // function making a tail call to a function returning int.
3048     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3049   }
3050
3051   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3052   InFlag = Chain.getValue(1);
3053
3054   // Create the CALLSEQ_END node.
3055   unsigned NumBytesForCalleeToPop;
3056   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3057                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3058     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3059   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3060            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3061            SR == StackStructReturn)
3062     // If this is a call to a struct-return function, the callee
3063     // pops the hidden struct pointer, so we have to push it back.
3064     // This is common for Darwin/X86, Linux & Mingw32 targets.
3065     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3066     NumBytesForCalleeToPop = 4;
3067   else
3068     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3069
3070   // Returns a flag for retval copy to use.
3071   if (!IsSibcall) {
3072     Chain = DAG.getCALLSEQ_END(Chain,
3073                                DAG.getIntPtrConstant(NumBytesToPop, true),
3074                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3075                                                      true),
3076                                InFlag, dl);
3077     InFlag = Chain.getValue(1);
3078   }
3079
3080   // Handle result values, copying them out of physregs into vregs that we
3081   // return.
3082   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3083                          Ins, dl, DAG, InVals);
3084 }
3085
3086 //===----------------------------------------------------------------------===//
3087 //                Fast Calling Convention (tail call) implementation
3088 //===----------------------------------------------------------------------===//
3089
3090 //  Like std call, callee cleans arguments, convention except that ECX is
3091 //  reserved for storing the tail called function address. Only 2 registers are
3092 //  free for argument passing (inreg). Tail call optimization is performed
3093 //  provided:
3094 //                * tailcallopt is enabled
3095 //                * caller/callee are fastcc
3096 //  On X86_64 architecture with GOT-style position independent code only local
3097 //  (within module) calls are supported at the moment.
3098 //  To keep the stack aligned according to platform abi the function
3099 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3100 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3101 //  If a tail called function callee has more arguments than the caller the
3102 //  caller needs to make sure that there is room to move the RETADDR to. This is
3103 //  achieved by reserving an area the size of the argument delta right after the
3104 //  original RETADDR, but before the saved framepointer or the spilled registers
3105 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3106 //  stack layout:
3107 //    arg1
3108 //    arg2
3109 //    RETADDR
3110 //    [ new RETADDR
3111 //      move area ]
3112 //    (possible EBP)
3113 //    ESI
3114 //    EDI
3115 //    local1 ..
3116
3117 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3118 /// for a 16 byte align requirement.
3119 unsigned
3120 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3121                                                SelectionDAG& DAG) const {
3122   MachineFunction &MF = DAG.getMachineFunction();
3123   const TargetMachine &TM = MF.getTarget();
3124   const X86RegisterInfo *RegInfo =
3125     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3126   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3127   unsigned StackAlignment = TFI.getStackAlignment();
3128   uint64_t AlignMask = StackAlignment - 1;
3129   int64_t Offset = StackSize;
3130   unsigned SlotSize = RegInfo->getSlotSize();
3131   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3132     // Number smaller than 12 so just add the difference.
3133     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3134   } else {
3135     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3136     Offset = ((~AlignMask) & Offset) + StackAlignment +
3137       (StackAlignment-SlotSize);
3138   }
3139   return Offset;
3140 }
3141
3142 /// MatchingStackOffset - Return true if the given stack call argument is
3143 /// already available in the same position (relatively) of the caller's
3144 /// incoming argument stack.
3145 static
3146 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3147                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3148                          const X86InstrInfo *TII) {
3149   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3150   int FI = INT_MAX;
3151   if (Arg.getOpcode() == ISD::CopyFromReg) {
3152     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3153     if (!TargetRegisterInfo::isVirtualRegister(VR))
3154       return false;
3155     MachineInstr *Def = MRI->getVRegDef(VR);
3156     if (!Def)
3157       return false;
3158     if (!Flags.isByVal()) {
3159       if (!TII->isLoadFromStackSlot(Def, FI))
3160         return false;
3161     } else {
3162       unsigned Opcode = Def->getOpcode();
3163       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3164           Def->getOperand(1).isFI()) {
3165         FI = Def->getOperand(1).getIndex();
3166         Bytes = Flags.getByValSize();
3167       } else
3168         return false;
3169     }
3170   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3171     if (Flags.isByVal())
3172       // ByVal argument is passed in as a pointer but it's now being
3173       // dereferenced. e.g.
3174       // define @foo(%struct.X* %A) {
3175       //   tail call @bar(%struct.X* byval %A)
3176       // }
3177       return false;
3178     SDValue Ptr = Ld->getBasePtr();
3179     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3180     if (!FINode)
3181       return false;
3182     FI = FINode->getIndex();
3183   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3184     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3185     FI = FINode->getIndex();
3186     Bytes = Flags.getByValSize();
3187   } else
3188     return false;
3189
3190   assert(FI != INT_MAX);
3191   if (!MFI->isFixedObjectIndex(FI))
3192     return false;
3193   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3194 }
3195
3196 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3197 /// for tail call optimization. Targets which want to do tail call
3198 /// optimization should implement this function.
3199 bool
3200 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3201                                                      CallingConv::ID CalleeCC,
3202                                                      bool isVarArg,
3203                                                      bool isCalleeStructRet,
3204                                                      bool isCallerStructRet,
3205                                                      Type *RetTy,
3206                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3207                                     const SmallVectorImpl<SDValue> &OutVals,
3208                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3209                                                      SelectionDAG &DAG) const {
3210   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3211     return false;
3212
3213   // If -tailcallopt is specified, make fastcc functions tail-callable.
3214   const MachineFunction &MF = DAG.getMachineFunction();
3215   const Function *CallerF = MF.getFunction();
3216
3217   // If the function return type is x86_fp80 and the callee return type is not,
3218   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3219   // perform a tailcall optimization here.
3220   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3221     return false;
3222
3223   CallingConv::ID CallerCC = CallerF->getCallingConv();
3224   bool CCMatch = CallerCC == CalleeCC;
3225   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3226   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3227
3228   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3229     if (IsTailCallConvention(CalleeCC) && CCMatch)
3230       return true;
3231     return false;
3232   }
3233
3234   // Look for obvious safe cases to perform tail call optimization that do not
3235   // require ABI changes. This is what gcc calls sibcall.
3236
3237   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3238   // emit a special epilogue.
3239   const X86RegisterInfo *RegInfo =
3240     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3241   if (RegInfo->needsStackRealignment(MF))
3242     return false;
3243
3244   // Also avoid sibcall optimization if either caller or callee uses struct
3245   // return semantics.
3246   if (isCalleeStructRet || isCallerStructRet)
3247     return false;
3248
3249   // An stdcall/thiscall caller is expected to clean up its arguments; the
3250   // callee isn't going to do that.
3251   // FIXME: this is more restrictive than needed. We could produce a tailcall
3252   // when the stack adjustment matches. For example, with a thiscall that takes
3253   // only one argument.
3254   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3255                    CallerCC == CallingConv::X86_ThisCall))
3256     return false;
3257
3258   // Do not sibcall optimize vararg calls unless all arguments are passed via
3259   // registers.
3260   if (isVarArg && !Outs.empty()) {
3261
3262     // Optimizing for varargs on Win64 is unlikely to be safe without
3263     // additional testing.
3264     if (IsCalleeWin64 || IsCallerWin64)
3265       return false;
3266
3267     SmallVector<CCValAssign, 16> ArgLocs;
3268     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3269                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3270
3271     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3272     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3273       if (!ArgLocs[i].isRegLoc())
3274         return false;
3275   }
3276
3277   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3278   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3279   // this into a sibcall.
3280   bool Unused = false;
3281   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3282     if (!Ins[i].Used) {
3283       Unused = true;
3284       break;
3285     }
3286   }
3287   if (Unused) {
3288     SmallVector<CCValAssign, 16> RVLocs;
3289     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3290                    DAG.getTarget(), RVLocs, *DAG.getContext());
3291     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3292     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3293       CCValAssign &VA = RVLocs[i];
3294       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3295         return false;
3296     }
3297   }
3298
3299   // If the calling conventions do not match, then we'd better make sure the
3300   // results are returned in the same way as what the caller expects.
3301   if (!CCMatch) {
3302     SmallVector<CCValAssign, 16> RVLocs1;
3303     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3304                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3305     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3306
3307     SmallVector<CCValAssign, 16> RVLocs2;
3308     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3309                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3310     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3311
3312     if (RVLocs1.size() != RVLocs2.size())
3313       return false;
3314     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3315       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3316         return false;
3317       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3318         return false;
3319       if (RVLocs1[i].isRegLoc()) {
3320         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3321           return false;
3322       } else {
3323         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3324           return false;
3325       }
3326     }
3327   }
3328
3329   // If the callee takes no arguments then go on to check the results of the
3330   // call.
3331   if (!Outs.empty()) {
3332     // Check if stack adjustment is needed. For now, do not do this if any
3333     // argument is passed on the stack.
3334     SmallVector<CCValAssign, 16> ArgLocs;
3335     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3336                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3337
3338     // Allocate shadow area for Win64
3339     if (IsCalleeWin64)
3340       CCInfo.AllocateStack(32, 8);
3341
3342     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3343     if (CCInfo.getNextStackOffset()) {
3344       MachineFunction &MF = DAG.getMachineFunction();
3345       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3346         return false;
3347
3348       // Check if the arguments are already laid out in the right way as
3349       // the caller's fixed stack objects.
3350       MachineFrameInfo *MFI = MF.getFrameInfo();
3351       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3352       const X86InstrInfo *TII =
3353           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3354       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3355         CCValAssign &VA = ArgLocs[i];
3356         SDValue Arg = OutVals[i];
3357         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3358         if (VA.getLocInfo() == CCValAssign::Indirect)
3359           return false;
3360         if (!VA.isRegLoc()) {
3361           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3362                                    MFI, MRI, TII))
3363             return false;
3364         }
3365       }
3366     }
3367
3368     // If the tailcall address may be in a register, then make sure it's
3369     // possible to register allocate for it. In 32-bit, the call address can
3370     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3371     // callee-saved registers are restored. These happen to be the same
3372     // registers used to pass 'inreg' arguments so watch out for those.
3373     if (!Subtarget->is64Bit() &&
3374         ((!isa<GlobalAddressSDNode>(Callee) &&
3375           !isa<ExternalSymbolSDNode>(Callee)) ||
3376          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3377       unsigned NumInRegs = 0;
3378       // In PIC we need an extra register to formulate the address computation
3379       // for the callee.
3380       unsigned MaxInRegs =
3381         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3382
3383       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3384         CCValAssign &VA = ArgLocs[i];
3385         if (!VA.isRegLoc())
3386           continue;
3387         unsigned Reg = VA.getLocReg();
3388         switch (Reg) {
3389         default: break;
3390         case X86::EAX: case X86::EDX: case X86::ECX:
3391           if (++NumInRegs == MaxInRegs)
3392             return false;
3393           break;
3394         }
3395       }
3396     }
3397   }
3398
3399   return true;
3400 }
3401
3402 FastISel *
3403 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3404                                   const TargetLibraryInfo *libInfo) const {
3405   return X86::createFastISel(funcInfo, libInfo);
3406 }
3407
3408 //===----------------------------------------------------------------------===//
3409 //                           Other Lowering Hooks
3410 //===----------------------------------------------------------------------===//
3411
3412 static bool MayFoldLoad(SDValue Op) {
3413   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3414 }
3415
3416 static bool MayFoldIntoStore(SDValue Op) {
3417   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3418 }
3419
3420 static bool isTargetShuffle(unsigned Opcode) {
3421   switch(Opcode) {
3422   default: return false;
3423   case X86ISD::PSHUFD:
3424   case X86ISD::PSHUFHW:
3425   case X86ISD::PSHUFLW:
3426   case X86ISD::SHUFP:
3427   case X86ISD::PALIGNR:
3428   case X86ISD::MOVLHPS:
3429   case X86ISD::MOVLHPD:
3430   case X86ISD::MOVHLPS:
3431   case X86ISD::MOVLPS:
3432   case X86ISD::MOVLPD:
3433   case X86ISD::MOVSHDUP:
3434   case X86ISD::MOVSLDUP:
3435   case X86ISD::MOVDDUP:
3436   case X86ISD::MOVSS:
3437   case X86ISD::MOVSD:
3438   case X86ISD::UNPCKL:
3439   case X86ISD::UNPCKH:
3440   case X86ISD::VPERMILP:
3441   case X86ISD::VPERM2X128:
3442   case X86ISD::VPERMI:
3443     return true;
3444   }
3445 }
3446
3447 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3448                                     SDValue V1, SelectionDAG &DAG) {
3449   switch(Opc) {
3450   default: llvm_unreachable("Unknown x86 shuffle node");
3451   case X86ISD::MOVSHDUP:
3452   case X86ISD::MOVSLDUP:
3453   case X86ISD::MOVDDUP:
3454     return DAG.getNode(Opc, dl, VT, V1);
3455   }
3456 }
3457
3458 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3459                                     SDValue V1, unsigned TargetMask,
3460                                     SelectionDAG &DAG) {
3461   switch(Opc) {
3462   default: llvm_unreachable("Unknown x86 shuffle node");
3463   case X86ISD::PSHUFD:
3464   case X86ISD::PSHUFHW:
3465   case X86ISD::PSHUFLW:
3466   case X86ISD::VPERMILP:
3467   case X86ISD::VPERMI:
3468     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3469   }
3470 }
3471
3472 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3473                                     SDValue V1, SDValue V2, unsigned TargetMask,
3474                                     SelectionDAG &DAG) {
3475   switch(Opc) {
3476   default: llvm_unreachable("Unknown x86 shuffle node");
3477   case X86ISD::PALIGNR:
3478   case X86ISD::SHUFP:
3479   case X86ISD::VPERM2X128:
3480     return DAG.getNode(Opc, dl, VT, V1, V2,
3481                        DAG.getConstant(TargetMask, MVT::i8));
3482   }
3483 }
3484
3485 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3486                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3487   switch(Opc) {
3488   default: llvm_unreachable("Unknown x86 shuffle node");
3489   case X86ISD::MOVLHPS:
3490   case X86ISD::MOVLHPD:
3491   case X86ISD::MOVHLPS:
3492   case X86ISD::MOVLPS:
3493   case X86ISD::MOVLPD:
3494   case X86ISD::MOVSS:
3495   case X86ISD::MOVSD:
3496   case X86ISD::UNPCKL:
3497   case X86ISD::UNPCKH:
3498     return DAG.getNode(Opc, dl, VT, V1, V2);
3499   }
3500 }
3501
3502 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3503   MachineFunction &MF = DAG.getMachineFunction();
3504   const X86RegisterInfo *RegInfo =
3505     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3506   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3507   int ReturnAddrIndex = FuncInfo->getRAIndex();
3508
3509   if (ReturnAddrIndex == 0) {
3510     // Set up a frame object for the return address.
3511     unsigned SlotSize = RegInfo->getSlotSize();
3512     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3513                                                            -(int64_t)SlotSize,
3514                                                            false);
3515     FuncInfo->setRAIndex(ReturnAddrIndex);
3516   }
3517
3518   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3519 }
3520
3521 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3522                                        bool hasSymbolicDisplacement) {
3523   // Offset should fit into 32 bit immediate field.
3524   if (!isInt<32>(Offset))
3525     return false;
3526
3527   // If we don't have a symbolic displacement - we don't have any extra
3528   // restrictions.
3529   if (!hasSymbolicDisplacement)
3530     return true;
3531
3532   // FIXME: Some tweaks might be needed for medium code model.
3533   if (M != CodeModel::Small && M != CodeModel::Kernel)
3534     return false;
3535
3536   // For small code model we assume that latest object is 16MB before end of 31
3537   // bits boundary. We may also accept pretty large negative constants knowing
3538   // that all objects are in the positive half of address space.
3539   if (M == CodeModel::Small && Offset < 16*1024*1024)
3540     return true;
3541
3542   // For kernel code model we know that all object resist in the negative half
3543   // of 32bits address space. We may not accept negative offsets, since they may
3544   // be just off and we may accept pretty large positive ones.
3545   if (M == CodeModel::Kernel && Offset > 0)
3546     return true;
3547
3548   return false;
3549 }
3550
3551 /// isCalleePop - Determines whether the callee is required to pop its
3552 /// own arguments. Callee pop is necessary to support tail calls.
3553 bool X86::isCalleePop(CallingConv::ID CallingConv,
3554                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3555   if (IsVarArg)
3556     return false;
3557
3558   switch (CallingConv) {
3559   default:
3560     return false;
3561   case CallingConv::X86_StdCall:
3562     return !is64Bit;
3563   case CallingConv::X86_FastCall:
3564     return !is64Bit;
3565   case CallingConv::X86_ThisCall:
3566     return !is64Bit;
3567   case CallingConv::Fast:
3568     return TailCallOpt;
3569   case CallingConv::GHC:
3570     return TailCallOpt;
3571   case CallingConv::HiPE:
3572     return TailCallOpt;
3573   }
3574 }
3575
3576 /// \brief Return true if the condition is an unsigned comparison operation.
3577 static bool isX86CCUnsigned(unsigned X86CC) {
3578   switch (X86CC) {
3579   default: llvm_unreachable("Invalid integer condition!");
3580   case X86::COND_E:     return true;
3581   case X86::COND_G:     return false;
3582   case X86::COND_GE:    return false;
3583   case X86::COND_L:     return false;
3584   case X86::COND_LE:    return false;
3585   case X86::COND_NE:    return true;
3586   case X86::COND_B:     return true;
3587   case X86::COND_A:     return true;
3588   case X86::COND_BE:    return true;
3589   case X86::COND_AE:    return true;
3590   }
3591   llvm_unreachable("covered switch fell through?!");
3592 }
3593
3594 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3595 /// specific condition code, returning the condition code and the LHS/RHS of the
3596 /// comparison to make.
3597 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3598                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3599   if (!isFP) {
3600     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3601       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3602         // X > -1   -> X == 0, jump !sign.
3603         RHS = DAG.getConstant(0, RHS.getValueType());
3604         return X86::COND_NS;
3605       }
3606       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3607         // X < 0   -> X == 0, jump on sign.
3608         return X86::COND_S;
3609       }
3610       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3611         // X < 1   -> X <= 0
3612         RHS = DAG.getConstant(0, RHS.getValueType());
3613         return X86::COND_LE;
3614       }
3615     }
3616
3617     switch (SetCCOpcode) {
3618     default: llvm_unreachable("Invalid integer condition!");
3619     case ISD::SETEQ:  return X86::COND_E;
3620     case ISD::SETGT:  return X86::COND_G;
3621     case ISD::SETGE:  return X86::COND_GE;
3622     case ISD::SETLT:  return X86::COND_L;
3623     case ISD::SETLE:  return X86::COND_LE;
3624     case ISD::SETNE:  return X86::COND_NE;
3625     case ISD::SETULT: return X86::COND_B;
3626     case ISD::SETUGT: return X86::COND_A;
3627     case ISD::SETULE: return X86::COND_BE;
3628     case ISD::SETUGE: return X86::COND_AE;
3629     }
3630   }
3631
3632   // First determine if it is required or is profitable to flip the operands.
3633
3634   // If LHS is a foldable load, but RHS is not, flip the condition.
3635   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3636       !ISD::isNON_EXTLoad(RHS.getNode())) {
3637     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3638     std::swap(LHS, RHS);
3639   }
3640
3641   switch (SetCCOpcode) {
3642   default: break;
3643   case ISD::SETOLT:
3644   case ISD::SETOLE:
3645   case ISD::SETUGT:
3646   case ISD::SETUGE:
3647     std::swap(LHS, RHS);
3648     break;
3649   }
3650
3651   // On a floating point condition, the flags are set as follows:
3652   // ZF  PF  CF   op
3653   //  0 | 0 | 0 | X > Y
3654   //  0 | 0 | 1 | X < Y
3655   //  1 | 0 | 0 | X == Y
3656   //  1 | 1 | 1 | unordered
3657   switch (SetCCOpcode) {
3658   default: llvm_unreachable("Condcode should be pre-legalized away");
3659   case ISD::SETUEQ:
3660   case ISD::SETEQ:   return X86::COND_E;
3661   case ISD::SETOLT:              // flipped
3662   case ISD::SETOGT:
3663   case ISD::SETGT:   return X86::COND_A;
3664   case ISD::SETOLE:              // flipped
3665   case ISD::SETOGE:
3666   case ISD::SETGE:   return X86::COND_AE;
3667   case ISD::SETUGT:              // flipped
3668   case ISD::SETULT:
3669   case ISD::SETLT:   return X86::COND_B;
3670   case ISD::SETUGE:              // flipped
3671   case ISD::SETULE:
3672   case ISD::SETLE:   return X86::COND_BE;
3673   case ISD::SETONE:
3674   case ISD::SETNE:   return X86::COND_NE;
3675   case ISD::SETUO:   return X86::COND_P;
3676   case ISD::SETO:    return X86::COND_NP;
3677   case ISD::SETOEQ:
3678   case ISD::SETUNE:  return X86::COND_INVALID;
3679   }
3680 }
3681
3682 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3683 /// code. Current x86 isa includes the following FP cmov instructions:
3684 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3685 static bool hasFPCMov(unsigned X86CC) {
3686   switch (X86CC) {
3687   default:
3688     return false;
3689   case X86::COND_B:
3690   case X86::COND_BE:
3691   case X86::COND_E:
3692   case X86::COND_P:
3693   case X86::COND_A:
3694   case X86::COND_AE:
3695   case X86::COND_NE:
3696   case X86::COND_NP:
3697     return true;
3698   }
3699 }
3700
3701 /// isFPImmLegal - Returns true if the target can instruction select the
3702 /// specified FP immediate natively. If false, the legalizer will
3703 /// materialize the FP immediate as a load from a constant pool.
3704 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3705   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3706     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3707       return true;
3708   }
3709   return false;
3710 }
3711
3712 /// \brief Returns true if it is beneficial to convert a load of a constant
3713 /// to just the constant itself.
3714 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3715                                                           Type *Ty) const {
3716   assert(Ty->isIntegerTy());
3717
3718   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3719   if (BitSize == 0 || BitSize > 64)
3720     return false;
3721   return true;
3722 }
3723
3724 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3725 /// the specified range (L, H].
3726 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3727   return (Val < 0) || (Val >= Low && Val < Hi);
3728 }
3729
3730 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3731 /// specified value.
3732 static bool isUndefOrEqual(int Val, int CmpVal) {
3733   return (Val < 0 || Val == CmpVal);
3734 }
3735
3736 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3737 /// from position Pos and ending in Pos+Size, falls within the specified
3738 /// sequential range (L, L+Pos]. or is undef.
3739 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3740                                        unsigned Pos, unsigned Size, int Low) {
3741   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3742     if (!isUndefOrEqual(Mask[i], Low))
3743       return false;
3744   return true;
3745 }
3746
3747 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3748 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3749 /// the second operand.
3750 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3751   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3752     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3753   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3754     return (Mask[0] < 2 && Mask[1] < 2);
3755   return false;
3756 }
3757
3758 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3759 /// is suitable for input to PSHUFHW.
3760 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3761   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3762     return false;
3763
3764   // Lower quadword copied in order or undef.
3765   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3766     return false;
3767
3768   // Upper quadword shuffled.
3769   for (unsigned i = 4; i != 8; ++i)
3770     if (!isUndefOrInRange(Mask[i], 4, 8))
3771       return false;
3772
3773   if (VT == MVT::v16i16) {
3774     // Lower quadword copied in order or undef.
3775     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3776       return false;
3777
3778     // Upper quadword shuffled.
3779     for (unsigned i = 12; i != 16; ++i)
3780       if (!isUndefOrInRange(Mask[i], 12, 16))
3781         return false;
3782   }
3783
3784   return true;
3785 }
3786
3787 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3788 /// is suitable for input to PSHUFLW.
3789 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3790   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3791     return false;
3792
3793   // Upper quadword copied in order.
3794   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3795     return false;
3796
3797   // Lower quadword shuffled.
3798   for (unsigned i = 0; i != 4; ++i)
3799     if (!isUndefOrInRange(Mask[i], 0, 4))
3800       return false;
3801
3802   if (VT == MVT::v16i16) {
3803     // Upper quadword copied in order.
3804     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3805       return false;
3806
3807     // Lower quadword shuffled.
3808     for (unsigned i = 8; i != 12; ++i)
3809       if (!isUndefOrInRange(Mask[i], 8, 12))
3810         return false;
3811   }
3812
3813   return true;
3814 }
3815
3816 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3817 /// is suitable for input to PALIGNR.
3818 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3819                           const X86Subtarget *Subtarget) {
3820   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3821       (VT.is256BitVector() && !Subtarget->hasInt256()))
3822     return false;
3823
3824   unsigned NumElts = VT.getVectorNumElements();
3825   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3826   unsigned NumLaneElts = NumElts/NumLanes;
3827
3828   // Do not handle 64-bit element shuffles with palignr.
3829   if (NumLaneElts == 2)
3830     return false;
3831
3832   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3833     unsigned i;
3834     for (i = 0; i != NumLaneElts; ++i) {
3835       if (Mask[i+l] >= 0)
3836         break;
3837     }
3838
3839     // Lane is all undef, go to next lane
3840     if (i == NumLaneElts)
3841       continue;
3842
3843     int Start = Mask[i+l];
3844
3845     // Make sure its in this lane in one of the sources
3846     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3847         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3848       return false;
3849
3850     // If not lane 0, then we must match lane 0
3851     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3852       return false;
3853
3854     // Correct second source to be contiguous with first source
3855     if (Start >= (int)NumElts)
3856       Start -= NumElts - NumLaneElts;
3857
3858     // Make sure we're shifting in the right direction.
3859     if (Start <= (int)(i+l))
3860       return false;
3861
3862     Start -= i;
3863
3864     // Check the rest of the elements to see if they are consecutive.
3865     for (++i; i != NumLaneElts; ++i) {
3866       int Idx = Mask[i+l];
3867
3868       // Make sure its in this lane
3869       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3870           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3871         return false;
3872
3873       // If not lane 0, then we must match lane 0
3874       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3875         return false;
3876
3877       if (Idx >= (int)NumElts)
3878         Idx -= NumElts - NumLaneElts;
3879
3880       if (!isUndefOrEqual(Idx, Start+i))
3881         return false;
3882
3883     }
3884   }
3885
3886   return true;
3887 }
3888
3889 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3890 /// the two vector operands have swapped position.
3891 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3892                                      unsigned NumElems) {
3893   for (unsigned i = 0; i != NumElems; ++i) {
3894     int idx = Mask[i];
3895     if (idx < 0)
3896       continue;
3897     else if (idx < (int)NumElems)
3898       Mask[i] = idx + NumElems;
3899     else
3900       Mask[i] = idx - NumElems;
3901   }
3902 }
3903
3904 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3905 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3906 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3907 /// reverse of what x86 shuffles want.
3908 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3909
3910   unsigned NumElems = VT.getVectorNumElements();
3911   unsigned NumLanes = VT.getSizeInBits()/128;
3912   unsigned NumLaneElems = NumElems/NumLanes;
3913
3914   if (NumLaneElems != 2 && NumLaneElems != 4)
3915     return false;
3916
3917   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3918   bool symetricMaskRequired =
3919     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3920
3921   // VSHUFPSY divides the resulting vector into 4 chunks.
3922   // The sources are also splitted into 4 chunks, and each destination
3923   // chunk must come from a different source chunk.
3924   //
3925   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3926   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3927   //
3928   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3929   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3930   //
3931   // VSHUFPDY divides the resulting vector into 4 chunks.
3932   // The sources are also splitted into 4 chunks, and each destination
3933   // chunk must come from a different source chunk.
3934   //
3935   //  SRC1 =>      X3       X2       X1       X0
3936   //  SRC2 =>      Y3       Y2       Y1       Y0
3937   //
3938   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3939   //
3940   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3941   unsigned HalfLaneElems = NumLaneElems/2;
3942   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3943     for (unsigned i = 0; i != NumLaneElems; ++i) {
3944       int Idx = Mask[i+l];
3945       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3946       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3947         return false;
3948       // For VSHUFPSY, the mask of the second half must be the same as the
3949       // first but with the appropriate offsets. This works in the same way as
3950       // VPERMILPS works with masks.
3951       if (!symetricMaskRequired || Idx < 0)
3952         continue;
3953       if (MaskVal[i] < 0) {
3954         MaskVal[i] = Idx - l;
3955         continue;
3956       }
3957       if ((signed)(Idx - l) != MaskVal[i])
3958         return false;
3959     }
3960   }
3961
3962   return true;
3963 }
3964
3965 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3967 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3968   if (!VT.is128BitVector())
3969     return false;
3970
3971   unsigned NumElems = VT.getVectorNumElements();
3972
3973   if (NumElems != 4)
3974     return false;
3975
3976   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3977   return isUndefOrEqual(Mask[0], 6) &&
3978          isUndefOrEqual(Mask[1], 7) &&
3979          isUndefOrEqual(Mask[2], 2) &&
3980          isUndefOrEqual(Mask[3], 3);
3981 }
3982
3983 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3984 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3985 /// <2, 3, 2, 3>
3986 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3987   if (!VT.is128BitVector())
3988     return false;
3989
3990   unsigned NumElems = VT.getVectorNumElements();
3991
3992   if (NumElems != 4)
3993     return false;
3994
3995   return isUndefOrEqual(Mask[0], 2) &&
3996          isUndefOrEqual(Mask[1], 3) &&
3997          isUndefOrEqual(Mask[2], 2) &&
3998          isUndefOrEqual(Mask[3], 3);
3999 }
4000
4001 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4002 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4003 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4004   if (!VT.is128BitVector())
4005     return false;
4006
4007   unsigned NumElems = VT.getVectorNumElements();
4008
4009   if (NumElems != 2 && NumElems != 4)
4010     return false;
4011
4012   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4013     if (!isUndefOrEqual(Mask[i], i + NumElems))
4014       return false;
4015
4016   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4017     if (!isUndefOrEqual(Mask[i], i))
4018       return false;
4019
4020   return true;
4021 }
4022
4023 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4024 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4025 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4026   if (!VT.is128BitVector())
4027     return false;
4028
4029   unsigned NumElems = VT.getVectorNumElements();
4030
4031   if (NumElems != 2 && NumElems != 4)
4032     return false;
4033
4034   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4035     if (!isUndefOrEqual(Mask[i], i))
4036       return false;
4037
4038   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4039     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4040       return false;
4041
4042   return true;
4043 }
4044
4045 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4046 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4047 /// i. e: If all but one element come from the same vector.
4048 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4049   // TODO: Deal with AVX's VINSERTPS
4050   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4051     return false;
4052
4053   unsigned CorrectPosV1 = 0;
4054   unsigned CorrectPosV2 = 0;
4055   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4056     if (Mask[i] == -1) {
4057       ++CorrectPosV1;
4058       ++CorrectPosV2;
4059       continue;
4060     }
4061
4062     if (Mask[i] == i)
4063       ++CorrectPosV1;
4064     else if (Mask[i] == i + 4)
4065       ++CorrectPosV2;
4066   }
4067
4068   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4069     // We have 3 elements (undefs count as elements from any vector) from one
4070     // vector, and one from another.
4071     return true;
4072
4073   return false;
4074 }
4075
4076 //
4077 // Some special combinations that can be optimized.
4078 //
4079 static
4080 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4081                                SelectionDAG &DAG) {
4082   MVT VT = SVOp->getSimpleValueType(0);
4083   SDLoc dl(SVOp);
4084
4085   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4086     return SDValue();
4087
4088   ArrayRef<int> Mask = SVOp->getMask();
4089
4090   // These are the special masks that may be optimized.
4091   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4092   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4093   bool MatchEvenMask = true;
4094   bool MatchOddMask  = true;
4095   for (int i=0; i<8; ++i) {
4096     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4097       MatchEvenMask = false;
4098     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4099       MatchOddMask = false;
4100   }
4101
4102   if (!MatchEvenMask && !MatchOddMask)
4103     return SDValue();
4104
4105   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4106
4107   SDValue Op0 = SVOp->getOperand(0);
4108   SDValue Op1 = SVOp->getOperand(1);
4109
4110   if (MatchEvenMask) {
4111     // Shift the second operand right to 32 bits.
4112     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4113     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4114   } else {
4115     // Shift the first operand left to 32 bits.
4116     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4117     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4118   }
4119   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4120   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4121 }
4122
4123 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4124 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4125 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4126                          bool HasInt256, bool V2IsSplat = false) {
4127
4128   assert(VT.getSizeInBits() >= 128 &&
4129          "Unsupported vector type for unpckl");
4130
4131   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4132   unsigned NumLanes;
4133   unsigned NumOf256BitLanes;
4134   unsigned NumElts = VT.getVectorNumElements();
4135   if (VT.is256BitVector()) {
4136     if (NumElts != 4 && NumElts != 8 &&
4137         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4138     return false;
4139     NumLanes = 2;
4140     NumOf256BitLanes = 1;
4141   } else if (VT.is512BitVector()) {
4142     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4143            "Unsupported vector type for unpckh");
4144     NumLanes = 2;
4145     NumOf256BitLanes = 2;
4146   } else {
4147     NumLanes = 1;
4148     NumOf256BitLanes = 1;
4149   }
4150
4151   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4152   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4153
4154   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4155     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4156       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4157         int BitI  = Mask[l256*NumEltsInStride+l+i];
4158         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4159         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4160           return false;
4161         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4162           return false;
4163         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4164           return false;
4165       }
4166     }
4167   }
4168   return true;
4169 }
4170
4171 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4172 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4173 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4174                          bool HasInt256, bool V2IsSplat = false) {
4175   assert(VT.getSizeInBits() >= 128 &&
4176          "Unsupported vector type for unpckh");
4177
4178   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4179   unsigned NumLanes;
4180   unsigned NumOf256BitLanes;
4181   unsigned NumElts = VT.getVectorNumElements();
4182   if (VT.is256BitVector()) {
4183     if (NumElts != 4 && NumElts != 8 &&
4184         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4185     return false;
4186     NumLanes = 2;
4187     NumOf256BitLanes = 1;
4188   } else if (VT.is512BitVector()) {
4189     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4190            "Unsupported vector type for unpckh");
4191     NumLanes = 2;
4192     NumOf256BitLanes = 2;
4193   } else {
4194     NumLanes = 1;
4195     NumOf256BitLanes = 1;
4196   }
4197
4198   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4199   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4200
4201   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4202     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4203       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4204         int BitI  = Mask[l256*NumEltsInStride+l+i];
4205         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4206         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4207           return false;
4208         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4209           return false;
4210         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4211           return false;
4212       }
4213     }
4214   }
4215   return true;
4216 }
4217
4218 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4219 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4220 /// <0, 0, 1, 1>
4221 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4222   unsigned NumElts = VT.getVectorNumElements();
4223   bool Is256BitVec = VT.is256BitVector();
4224
4225   if (VT.is512BitVector())
4226     return false;
4227   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4228          "Unsupported vector type for unpckh");
4229
4230   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4231       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4232     return false;
4233
4234   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4235   // FIXME: Need a better way to get rid of this, there's no latency difference
4236   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4237   // the former later. We should also remove the "_undef" special mask.
4238   if (NumElts == 4 && Is256BitVec)
4239     return false;
4240
4241   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4242   // independently on 128-bit lanes.
4243   unsigned NumLanes = VT.getSizeInBits()/128;
4244   unsigned NumLaneElts = NumElts/NumLanes;
4245
4246   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4247     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4248       int BitI  = Mask[l+i];
4249       int BitI1 = Mask[l+i+1];
4250
4251       if (!isUndefOrEqual(BitI, j))
4252         return false;
4253       if (!isUndefOrEqual(BitI1, j))
4254         return false;
4255     }
4256   }
4257
4258   return true;
4259 }
4260
4261 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4262 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4263 /// <2, 2, 3, 3>
4264 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4265   unsigned NumElts = VT.getVectorNumElements();
4266
4267   if (VT.is512BitVector())
4268     return false;
4269
4270   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4271          "Unsupported vector type for unpckh");
4272
4273   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4274       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4275     return false;
4276
4277   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4278   // independently on 128-bit lanes.
4279   unsigned NumLanes = VT.getSizeInBits()/128;
4280   unsigned NumLaneElts = NumElts/NumLanes;
4281
4282   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4283     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4284       int BitI  = Mask[l+i];
4285       int BitI1 = Mask[l+i+1];
4286       if (!isUndefOrEqual(BitI, j))
4287         return false;
4288       if (!isUndefOrEqual(BitI1, j))
4289         return false;
4290     }
4291   }
4292   return true;
4293 }
4294
4295 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4296 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4297 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4298   if (!VT.is512BitVector())
4299     return false;
4300
4301   unsigned NumElts = VT.getVectorNumElements();
4302   unsigned HalfSize = NumElts/2;
4303   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4304     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4305       *Imm = 1;
4306       return true;
4307     }
4308   }
4309   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4310     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4311       *Imm = 0;
4312       return true;
4313     }
4314   }
4315   return false;
4316 }
4317
4318 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4319 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4320 /// MOVSD, and MOVD, i.e. setting the lowest element.
4321 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4322   if (VT.getVectorElementType().getSizeInBits() < 32)
4323     return false;
4324   if (!VT.is128BitVector())
4325     return false;
4326
4327   unsigned NumElts = VT.getVectorNumElements();
4328
4329   if (!isUndefOrEqual(Mask[0], NumElts))
4330     return false;
4331
4332   for (unsigned i = 1; i != NumElts; ++i)
4333     if (!isUndefOrEqual(Mask[i], i))
4334       return false;
4335
4336   return true;
4337 }
4338
4339 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4340 /// as permutations between 128-bit chunks or halves. As an example: this
4341 /// shuffle bellow:
4342 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4343 /// The first half comes from the second half of V1 and the second half from the
4344 /// the second half of V2.
4345 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4346   if (!HasFp256 || !VT.is256BitVector())
4347     return false;
4348
4349   // The shuffle result is divided into half A and half B. In total the two
4350   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4351   // B must come from C, D, E or F.
4352   unsigned HalfSize = VT.getVectorNumElements()/2;
4353   bool MatchA = false, MatchB = false;
4354
4355   // Check if A comes from one of C, D, E, F.
4356   for (unsigned Half = 0; Half != 4; ++Half) {
4357     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4358       MatchA = true;
4359       break;
4360     }
4361   }
4362
4363   // Check if B comes from one of C, D, E, F.
4364   for (unsigned Half = 0; Half != 4; ++Half) {
4365     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4366       MatchB = true;
4367       break;
4368     }
4369   }
4370
4371   return MatchA && MatchB;
4372 }
4373
4374 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4375 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4376 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4377   MVT VT = SVOp->getSimpleValueType(0);
4378
4379   unsigned HalfSize = VT.getVectorNumElements()/2;
4380
4381   unsigned FstHalf = 0, SndHalf = 0;
4382   for (unsigned i = 0; i < HalfSize; ++i) {
4383     if (SVOp->getMaskElt(i) > 0) {
4384       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4385       break;
4386     }
4387   }
4388   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4389     if (SVOp->getMaskElt(i) > 0) {
4390       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4391       break;
4392     }
4393   }
4394
4395   return (FstHalf | (SndHalf << 4));
4396 }
4397
4398 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4399 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4400   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4401   if (EltSize < 32)
4402     return false;
4403
4404   unsigned NumElts = VT.getVectorNumElements();
4405   Imm8 = 0;
4406   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4407     for (unsigned i = 0; i != NumElts; ++i) {
4408       if (Mask[i] < 0)
4409         continue;
4410       Imm8 |= Mask[i] << (i*2);
4411     }
4412     return true;
4413   }
4414
4415   unsigned LaneSize = 4;
4416   SmallVector<int, 4> MaskVal(LaneSize, -1);
4417
4418   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4419     for (unsigned i = 0; i != LaneSize; ++i) {
4420       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4421         return false;
4422       if (Mask[i+l] < 0)
4423         continue;
4424       if (MaskVal[i] < 0) {
4425         MaskVal[i] = Mask[i+l] - l;
4426         Imm8 |= MaskVal[i] << (i*2);
4427         continue;
4428       }
4429       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4430         return false;
4431     }
4432   }
4433   return true;
4434 }
4435
4436 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4437 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4438 /// Note that VPERMIL mask matching is different depending whether theunderlying
4439 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4440 /// to the same elements of the low, but to the higher half of the source.
4441 /// In VPERMILPD the two lanes could be shuffled independently of each other
4442 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4443 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4444   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4445   if (VT.getSizeInBits() < 256 || EltSize < 32)
4446     return false;
4447   bool symetricMaskRequired = (EltSize == 32);
4448   unsigned NumElts = VT.getVectorNumElements();
4449
4450   unsigned NumLanes = VT.getSizeInBits()/128;
4451   unsigned LaneSize = NumElts/NumLanes;
4452   // 2 or 4 elements in one lane
4453
4454   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4455   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4456     for (unsigned i = 0; i != LaneSize; ++i) {
4457       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4458         return false;
4459       if (symetricMaskRequired) {
4460         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4461           ExpectedMaskVal[i] = Mask[i+l] - l;
4462           continue;
4463         }
4464         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4465           return false;
4466       }
4467     }
4468   }
4469   return true;
4470 }
4471
4472 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4473 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4474 /// element of vector 2 and the other elements to come from vector 1 in order.
4475 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4476                                bool V2IsSplat = false, bool V2IsUndef = false) {
4477   if (!VT.is128BitVector())
4478     return false;
4479
4480   unsigned NumOps = VT.getVectorNumElements();
4481   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4482     return false;
4483
4484   if (!isUndefOrEqual(Mask[0], 0))
4485     return false;
4486
4487   for (unsigned i = 1; i != NumOps; ++i)
4488     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4489           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4490           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4491       return false;
4492
4493   return true;
4494 }
4495
4496 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4497 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4498 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4499 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4500                            const X86Subtarget *Subtarget) {
4501   if (!Subtarget->hasSSE3())
4502     return false;
4503
4504   unsigned NumElems = VT.getVectorNumElements();
4505
4506   if ((VT.is128BitVector() && NumElems != 4) ||
4507       (VT.is256BitVector() && NumElems != 8) ||
4508       (VT.is512BitVector() && NumElems != 16))
4509     return false;
4510
4511   // "i+1" is the value the indexed mask element must have
4512   for (unsigned i = 0; i != NumElems; i += 2)
4513     if (!isUndefOrEqual(Mask[i], i+1) ||
4514         !isUndefOrEqual(Mask[i+1], i+1))
4515       return false;
4516
4517   return true;
4518 }
4519
4520 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4521 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4522 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4523 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4524                            const X86Subtarget *Subtarget) {
4525   if (!Subtarget->hasSSE3())
4526     return false;
4527
4528   unsigned NumElems = VT.getVectorNumElements();
4529
4530   if ((VT.is128BitVector() && NumElems != 4) ||
4531       (VT.is256BitVector() && NumElems != 8) ||
4532       (VT.is512BitVector() && NumElems != 16))
4533     return false;
4534
4535   // "i" is the value the indexed mask element must have
4536   for (unsigned i = 0; i != NumElems; i += 2)
4537     if (!isUndefOrEqual(Mask[i], i) ||
4538         !isUndefOrEqual(Mask[i+1], i))
4539       return false;
4540
4541   return true;
4542 }
4543
4544 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4545 /// specifies a shuffle of elements that is suitable for input to 256-bit
4546 /// version of MOVDDUP.
4547 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4548   if (!HasFp256 || !VT.is256BitVector())
4549     return false;
4550
4551   unsigned NumElts = VT.getVectorNumElements();
4552   if (NumElts != 4)
4553     return false;
4554
4555   for (unsigned i = 0; i != NumElts/2; ++i)
4556     if (!isUndefOrEqual(Mask[i], 0))
4557       return false;
4558   for (unsigned i = NumElts/2; i != NumElts; ++i)
4559     if (!isUndefOrEqual(Mask[i], NumElts/2))
4560       return false;
4561   return true;
4562 }
4563
4564 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4565 /// specifies a shuffle of elements that is suitable for input to 128-bit
4566 /// version of MOVDDUP.
4567 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4568   if (!VT.is128BitVector())
4569     return false;
4570
4571   unsigned e = VT.getVectorNumElements() / 2;
4572   for (unsigned i = 0; i != e; ++i)
4573     if (!isUndefOrEqual(Mask[i], i))
4574       return false;
4575   for (unsigned i = 0; i != e; ++i)
4576     if (!isUndefOrEqual(Mask[e+i], i))
4577       return false;
4578   return true;
4579 }
4580
4581 /// isVEXTRACTIndex - Return true if the specified
4582 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4583 /// suitable for instruction that extract 128 or 256 bit vectors
4584 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4585   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4586   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4587     return false;
4588
4589   // The index should be aligned on a vecWidth-bit boundary.
4590   uint64_t Index =
4591     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4592
4593   MVT VT = N->getSimpleValueType(0);
4594   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4595   bool Result = (Index * ElSize) % vecWidth == 0;
4596
4597   return Result;
4598 }
4599
4600 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4601 /// operand specifies a subvector insert that is suitable for input to
4602 /// insertion of 128 or 256-bit subvectors
4603 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4604   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4605   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4606     return false;
4607   // The index should be aligned on a vecWidth-bit boundary.
4608   uint64_t Index =
4609     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4610
4611   MVT VT = N->getSimpleValueType(0);
4612   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4613   bool Result = (Index * ElSize) % vecWidth == 0;
4614
4615   return Result;
4616 }
4617
4618 bool X86::isVINSERT128Index(SDNode *N) {
4619   return isVINSERTIndex(N, 128);
4620 }
4621
4622 bool X86::isVINSERT256Index(SDNode *N) {
4623   return isVINSERTIndex(N, 256);
4624 }
4625
4626 bool X86::isVEXTRACT128Index(SDNode *N) {
4627   return isVEXTRACTIndex(N, 128);
4628 }
4629
4630 bool X86::isVEXTRACT256Index(SDNode *N) {
4631   return isVEXTRACTIndex(N, 256);
4632 }
4633
4634 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4635 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4636 /// Handles 128-bit and 256-bit.
4637 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4638   MVT VT = N->getSimpleValueType(0);
4639
4640   assert((VT.getSizeInBits() >= 128) &&
4641          "Unsupported vector type for PSHUF/SHUFP");
4642
4643   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4644   // independently on 128-bit lanes.
4645   unsigned NumElts = VT.getVectorNumElements();
4646   unsigned NumLanes = VT.getSizeInBits()/128;
4647   unsigned NumLaneElts = NumElts/NumLanes;
4648
4649   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4650          "Only supports 2, 4 or 8 elements per lane");
4651
4652   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4653   unsigned Mask = 0;
4654   for (unsigned i = 0; i != NumElts; ++i) {
4655     int Elt = N->getMaskElt(i);
4656     if (Elt < 0) continue;
4657     Elt &= NumLaneElts - 1;
4658     unsigned ShAmt = (i << Shift) % 8;
4659     Mask |= Elt << ShAmt;
4660   }
4661
4662   return Mask;
4663 }
4664
4665 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4666 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4667 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4668   MVT VT = N->getSimpleValueType(0);
4669
4670   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4671          "Unsupported vector type for PSHUFHW");
4672
4673   unsigned NumElts = VT.getVectorNumElements();
4674
4675   unsigned Mask = 0;
4676   for (unsigned l = 0; l != NumElts; l += 8) {
4677     // 8 nodes per lane, but we only care about the last 4.
4678     for (unsigned i = 0; i < 4; ++i) {
4679       int Elt = N->getMaskElt(l+i+4);
4680       if (Elt < 0) continue;
4681       Elt &= 0x3; // only 2-bits.
4682       Mask |= Elt << (i * 2);
4683     }
4684   }
4685
4686   return Mask;
4687 }
4688
4689 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4690 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4691 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4692   MVT VT = N->getSimpleValueType(0);
4693
4694   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4695          "Unsupported vector type for PSHUFHW");
4696
4697   unsigned NumElts = VT.getVectorNumElements();
4698
4699   unsigned Mask = 0;
4700   for (unsigned l = 0; l != NumElts; l += 8) {
4701     // 8 nodes per lane, but we only care about the first 4.
4702     for (unsigned i = 0; i < 4; ++i) {
4703       int Elt = N->getMaskElt(l+i);
4704       if (Elt < 0) continue;
4705       Elt &= 0x3; // only 2-bits
4706       Mask |= Elt << (i * 2);
4707     }
4708   }
4709
4710   return Mask;
4711 }
4712
4713 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4714 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4715 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4716   MVT VT = SVOp->getSimpleValueType(0);
4717   unsigned EltSize = VT.is512BitVector() ? 1 :
4718     VT.getVectorElementType().getSizeInBits() >> 3;
4719
4720   unsigned NumElts = VT.getVectorNumElements();
4721   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4722   unsigned NumLaneElts = NumElts/NumLanes;
4723
4724   int Val = 0;
4725   unsigned i;
4726   for (i = 0; i != NumElts; ++i) {
4727     Val = SVOp->getMaskElt(i);
4728     if (Val >= 0)
4729       break;
4730   }
4731   if (Val >= (int)NumElts)
4732     Val -= NumElts - NumLaneElts;
4733
4734   assert(Val - i > 0 && "PALIGNR imm should be positive");
4735   return (Val - i) * EltSize;
4736 }
4737
4738 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4739   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4740   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4741     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4742
4743   uint64_t Index =
4744     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4745
4746   MVT VecVT = N->getOperand(0).getSimpleValueType();
4747   MVT ElVT = VecVT.getVectorElementType();
4748
4749   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4750   return Index / NumElemsPerChunk;
4751 }
4752
4753 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4754   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4755   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4756     llvm_unreachable("Illegal insert subvector for VINSERT");
4757
4758   uint64_t Index =
4759     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4760
4761   MVT VecVT = N->getSimpleValueType(0);
4762   MVT ElVT = VecVT.getVectorElementType();
4763
4764   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4765   return Index / NumElemsPerChunk;
4766 }
4767
4768 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4769 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4770 /// and VINSERTI128 instructions.
4771 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4772   return getExtractVEXTRACTImmediate(N, 128);
4773 }
4774
4775 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4776 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4777 /// and VINSERTI64x4 instructions.
4778 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4779   return getExtractVEXTRACTImmediate(N, 256);
4780 }
4781
4782 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4783 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4784 /// and VINSERTI128 instructions.
4785 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4786   return getInsertVINSERTImmediate(N, 128);
4787 }
4788
4789 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4790 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4791 /// and VINSERTI64x4 instructions.
4792 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4793   return getInsertVINSERTImmediate(N, 256);
4794 }
4795
4796 /// isZero - Returns true if Elt is a constant integer zero
4797 static bool isZero(SDValue V) {
4798   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4799   return C && C->isNullValue();
4800 }
4801
4802 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4803 /// constant +0.0.
4804 bool X86::isZeroNode(SDValue Elt) {
4805   if (isZero(Elt))
4806     return true;
4807   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4808     return CFP->getValueAPF().isPosZero();
4809   return false;
4810 }
4811
4812 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4813 /// match movhlps. The lower half elements should come from upper half of
4814 /// V1 (and in order), and the upper half elements should come from the upper
4815 /// half of V2 (and in order).
4816 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4817   if (!VT.is128BitVector())
4818     return false;
4819   if (VT.getVectorNumElements() != 4)
4820     return false;
4821   for (unsigned i = 0, e = 2; i != e; ++i)
4822     if (!isUndefOrEqual(Mask[i], i+2))
4823       return false;
4824   for (unsigned i = 2; i != 4; ++i)
4825     if (!isUndefOrEqual(Mask[i], i+4))
4826       return false;
4827   return true;
4828 }
4829
4830 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4831 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4832 /// required.
4833 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4834   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4835     return false;
4836   N = N->getOperand(0).getNode();
4837   if (!ISD::isNON_EXTLoad(N))
4838     return false;
4839   if (LD)
4840     *LD = cast<LoadSDNode>(N);
4841   return true;
4842 }
4843
4844 // Test whether the given value is a vector value which will be legalized
4845 // into a load.
4846 static bool WillBeConstantPoolLoad(SDNode *N) {
4847   if (N->getOpcode() != ISD::BUILD_VECTOR)
4848     return false;
4849
4850   // Check for any non-constant elements.
4851   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4852     switch (N->getOperand(i).getNode()->getOpcode()) {
4853     case ISD::UNDEF:
4854     case ISD::ConstantFP:
4855     case ISD::Constant:
4856       break;
4857     default:
4858       return false;
4859     }
4860
4861   // Vectors of all-zeros and all-ones are materialized with special
4862   // instructions rather than being loaded.
4863   return !ISD::isBuildVectorAllZeros(N) &&
4864          !ISD::isBuildVectorAllOnes(N);
4865 }
4866
4867 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4868 /// match movlp{s|d}. The lower half elements should come from lower half of
4869 /// V1 (and in order), and the upper half elements should come from the upper
4870 /// half of V2 (and in order). And since V1 will become the source of the
4871 /// MOVLP, it must be either a vector load or a scalar load to vector.
4872 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4873                                ArrayRef<int> Mask, MVT VT) {
4874   if (!VT.is128BitVector())
4875     return false;
4876
4877   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4878     return false;
4879   // Is V2 is a vector load, don't do this transformation. We will try to use
4880   // load folding shufps op.
4881   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4882     return false;
4883
4884   unsigned NumElems = VT.getVectorNumElements();
4885
4886   if (NumElems != 2 && NumElems != 4)
4887     return false;
4888   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4889     if (!isUndefOrEqual(Mask[i], i))
4890       return false;
4891   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4892     if (!isUndefOrEqual(Mask[i], i+NumElems))
4893       return false;
4894   return true;
4895 }
4896
4897 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4898 /// to an zero vector.
4899 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4900 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4901   SDValue V1 = N->getOperand(0);
4902   SDValue V2 = N->getOperand(1);
4903   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4904   for (unsigned i = 0; i != NumElems; ++i) {
4905     int Idx = N->getMaskElt(i);
4906     if (Idx >= (int)NumElems) {
4907       unsigned Opc = V2.getOpcode();
4908       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4909         continue;
4910       if (Opc != ISD::BUILD_VECTOR ||
4911           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4912         return false;
4913     } else if (Idx >= 0) {
4914       unsigned Opc = V1.getOpcode();
4915       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4916         continue;
4917       if (Opc != ISD::BUILD_VECTOR ||
4918           !X86::isZeroNode(V1.getOperand(Idx)))
4919         return false;
4920     }
4921   }
4922   return true;
4923 }
4924
4925 /// getZeroVector - Returns a vector of specified type with all zero elements.
4926 ///
4927 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4928                              SelectionDAG &DAG, SDLoc dl) {
4929   assert(VT.isVector() && "Expected a vector type");
4930
4931   // Always build SSE zero vectors as <4 x i32> bitcasted
4932   // to their dest type. This ensures they get CSE'd.
4933   SDValue Vec;
4934   if (VT.is128BitVector()) {  // SSE
4935     if (Subtarget->hasSSE2()) {  // SSE2
4936       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4937       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4938     } else { // SSE1
4939       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4940       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4941     }
4942   } else if (VT.is256BitVector()) { // AVX
4943     if (Subtarget->hasInt256()) { // AVX2
4944       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4945       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4946       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4947     } else {
4948       // 256-bit logic and arithmetic instructions in AVX are all
4949       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4950       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4951       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4952       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4953     }
4954   } else if (VT.is512BitVector()) { // AVX-512
4955       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4956       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4957                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4958       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4959   } else if (VT.getScalarType() == MVT::i1) {
4960     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4961     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4962     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4963     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4964   } else
4965     llvm_unreachable("Unexpected vector type");
4966
4967   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4968 }
4969
4970 /// getOnesVector - Returns a vector of specified type with all bits set.
4971 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4972 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4973 /// Then bitcast to their original type, ensuring they get CSE'd.
4974 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4975                              SDLoc dl) {
4976   assert(VT.isVector() && "Expected a vector type");
4977
4978   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4979   SDValue Vec;
4980   if (VT.is256BitVector()) {
4981     if (HasInt256) { // AVX2
4982       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4983       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4984     } else { // AVX
4985       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4986       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4987     }
4988   } else if (VT.is128BitVector()) {
4989     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4990   } else
4991     llvm_unreachable("Unexpected vector type");
4992
4993   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4994 }
4995
4996 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4997 /// that point to V2 points to its first element.
4998 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4999   for (unsigned i = 0; i != NumElems; ++i) {
5000     if (Mask[i] > (int)NumElems) {
5001       Mask[i] = NumElems;
5002     }
5003   }
5004 }
5005
5006 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5007 /// operation of specified width.
5008 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5009                        SDValue V2) {
5010   unsigned NumElems = VT.getVectorNumElements();
5011   SmallVector<int, 8> Mask;
5012   Mask.push_back(NumElems);
5013   for (unsigned i = 1; i != NumElems; ++i)
5014     Mask.push_back(i);
5015   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5016 }
5017
5018 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5019 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5020                           SDValue V2) {
5021   unsigned NumElems = VT.getVectorNumElements();
5022   SmallVector<int, 8> Mask;
5023   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5024     Mask.push_back(i);
5025     Mask.push_back(i + NumElems);
5026   }
5027   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5028 }
5029
5030 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5031 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5032                           SDValue V2) {
5033   unsigned NumElems = VT.getVectorNumElements();
5034   SmallVector<int, 8> Mask;
5035   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5036     Mask.push_back(i + Half);
5037     Mask.push_back(i + NumElems + Half);
5038   }
5039   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5040 }
5041
5042 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5043 // a generic shuffle instruction because the target has no such instructions.
5044 // Generate shuffles which repeat i16 and i8 several times until they can be
5045 // represented by v4f32 and then be manipulated by target suported shuffles.
5046 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5047   MVT VT = V.getSimpleValueType();
5048   int NumElems = VT.getVectorNumElements();
5049   SDLoc dl(V);
5050
5051   while (NumElems > 4) {
5052     if (EltNo < NumElems/2) {
5053       V = getUnpackl(DAG, dl, VT, V, V);
5054     } else {
5055       V = getUnpackh(DAG, dl, VT, V, V);
5056       EltNo -= NumElems/2;
5057     }
5058     NumElems >>= 1;
5059   }
5060   return V;
5061 }
5062
5063 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5064 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5065   MVT VT = V.getSimpleValueType();
5066   SDLoc dl(V);
5067
5068   if (VT.is128BitVector()) {
5069     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5070     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5071     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5072                              &SplatMask[0]);
5073   } else if (VT.is256BitVector()) {
5074     // To use VPERMILPS to splat scalars, the second half of indicies must
5075     // refer to the higher part, which is a duplication of the lower one,
5076     // because VPERMILPS can only handle in-lane permutations.
5077     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5078                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5079
5080     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5081     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5082                              &SplatMask[0]);
5083   } else
5084     llvm_unreachable("Vector size not supported");
5085
5086   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5087 }
5088
5089 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5090 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5091   MVT SrcVT = SV->getSimpleValueType(0);
5092   SDValue V1 = SV->getOperand(0);
5093   SDLoc dl(SV);
5094
5095   int EltNo = SV->getSplatIndex();
5096   int NumElems = SrcVT.getVectorNumElements();
5097   bool Is256BitVec = SrcVT.is256BitVector();
5098
5099   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5100          "Unknown how to promote splat for type");
5101
5102   // Extract the 128-bit part containing the splat element and update
5103   // the splat element index when it refers to the higher register.
5104   if (Is256BitVec) {
5105     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5106     if (EltNo >= NumElems/2)
5107       EltNo -= NumElems/2;
5108   }
5109
5110   // All i16 and i8 vector types can't be used directly by a generic shuffle
5111   // instruction because the target has no such instruction. Generate shuffles
5112   // which repeat i16 and i8 several times until they fit in i32, and then can
5113   // be manipulated by target suported shuffles.
5114   MVT EltVT = SrcVT.getVectorElementType();
5115   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5116     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5117
5118   // Recreate the 256-bit vector and place the same 128-bit vector
5119   // into the low and high part. This is necessary because we want
5120   // to use VPERM* to shuffle the vectors
5121   if (Is256BitVec) {
5122     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5123   }
5124
5125   return getLegalSplat(DAG, V1, EltNo);
5126 }
5127
5128 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5129 /// vector of zero or undef vector.  This produces a shuffle where the low
5130 /// element of V2 is swizzled into the zero/undef vector, landing at element
5131 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5132 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5133                                            bool IsZero,
5134                                            const X86Subtarget *Subtarget,
5135                                            SelectionDAG &DAG) {
5136   MVT VT = V2.getSimpleValueType();
5137   SDValue V1 = IsZero
5138     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5139   unsigned NumElems = VT.getVectorNumElements();
5140   SmallVector<int, 16> MaskVec;
5141   for (unsigned i = 0; i != NumElems; ++i)
5142     // If this is the insertion idx, put the low elt of V2 here.
5143     MaskVec.push_back(i == Idx ? NumElems : i);
5144   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5145 }
5146
5147 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5148 /// target specific opcode. Returns true if the Mask could be calculated.
5149 /// Sets IsUnary to true if only uses one source.
5150 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5151                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5152   unsigned NumElems = VT.getVectorNumElements();
5153   SDValue ImmN;
5154
5155   IsUnary = false;
5156   switch(N->getOpcode()) {
5157   case X86ISD::SHUFP:
5158     ImmN = N->getOperand(N->getNumOperands()-1);
5159     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160     break;
5161   case X86ISD::UNPCKH:
5162     DecodeUNPCKHMask(VT, Mask);
5163     break;
5164   case X86ISD::UNPCKL:
5165     DecodeUNPCKLMask(VT, Mask);
5166     break;
5167   case X86ISD::MOVHLPS:
5168     DecodeMOVHLPSMask(NumElems, Mask);
5169     break;
5170   case X86ISD::MOVLHPS:
5171     DecodeMOVLHPSMask(NumElems, Mask);
5172     break;
5173   case X86ISD::PALIGNR:
5174     ImmN = N->getOperand(N->getNumOperands()-1);
5175     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5176     break;
5177   case X86ISD::PSHUFD:
5178   case X86ISD::VPERMILP:
5179     ImmN = N->getOperand(N->getNumOperands()-1);
5180     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5181     IsUnary = true;
5182     break;
5183   case X86ISD::PSHUFHW:
5184     ImmN = N->getOperand(N->getNumOperands()-1);
5185     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5186     IsUnary = true;
5187     break;
5188   case X86ISD::PSHUFLW:
5189     ImmN = N->getOperand(N->getNumOperands()-1);
5190     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5191     IsUnary = true;
5192     break;
5193   case X86ISD::VPERMI:
5194     ImmN = N->getOperand(N->getNumOperands()-1);
5195     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5196     IsUnary = true;
5197     break;
5198   case X86ISD::MOVSS:
5199   case X86ISD::MOVSD: {
5200     // The index 0 always comes from the first element of the second source,
5201     // this is why MOVSS and MOVSD are used in the first place. The other
5202     // elements come from the other positions of the first source vector
5203     Mask.push_back(NumElems);
5204     for (unsigned i = 1; i != NumElems; ++i) {
5205       Mask.push_back(i);
5206     }
5207     break;
5208   }
5209   case X86ISD::VPERM2X128:
5210     ImmN = N->getOperand(N->getNumOperands()-1);
5211     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5212     if (Mask.empty()) return false;
5213     break;
5214   case X86ISD::MOVDDUP:
5215   case X86ISD::MOVLHPD:
5216   case X86ISD::MOVLPD:
5217   case X86ISD::MOVLPS:
5218   case X86ISD::MOVSHDUP:
5219   case X86ISD::MOVSLDUP:
5220     // Not yet implemented
5221     return false;
5222   default: llvm_unreachable("unknown target shuffle node");
5223   }
5224
5225   return true;
5226 }
5227
5228 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5229 /// element of the result of the vector shuffle.
5230 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5231                                    unsigned Depth) {
5232   if (Depth == 6)
5233     return SDValue();  // Limit search depth.
5234
5235   SDValue V = SDValue(N, 0);
5236   EVT VT = V.getValueType();
5237   unsigned Opcode = V.getOpcode();
5238
5239   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5240   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5241     int Elt = SV->getMaskElt(Index);
5242
5243     if (Elt < 0)
5244       return DAG.getUNDEF(VT.getVectorElementType());
5245
5246     unsigned NumElems = VT.getVectorNumElements();
5247     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5248                                          : SV->getOperand(1);
5249     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5250   }
5251
5252   // Recurse into target specific vector shuffles to find scalars.
5253   if (isTargetShuffle(Opcode)) {
5254     MVT ShufVT = V.getSimpleValueType();
5255     unsigned NumElems = ShufVT.getVectorNumElements();
5256     SmallVector<int, 16> ShuffleMask;
5257     bool IsUnary;
5258
5259     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5260       return SDValue();
5261
5262     int Elt = ShuffleMask[Index];
5263     if (Elt < 0)
5264       return DAG.getUNDEF(ShufVT.getVectorElementType());
5265
5266     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5267                                          : N->getOperand(1);
5268     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5269                                Depth+1);
5270   }
5271
5272   // Actual nodes that may contain scalar elements
5273   if (Opcode == ISD::BITCAST) {
5274     V = V.getOperand(0);
5275     EVT SrcVT = V.getValueType();
5276     unsigned NumElems = VT.getVectorNumElements();
5277
5278     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5279       return SDValue();
5280   }
5281
5282   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5283     return (Index == 0) ? V.getOperand(0)
5284                         : DAG.getUNDEF(VT.getVectorElementType());
5285
5286   if (V.getOpcode() == ISD::BUILD_VECTOR)
5287     return V.getOperand(Index);
5288
5289   return SDValue();
5290 }
5291
5292 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5293 /// shuffle operation which come from a consecutively from a zero. The
5294 /// search can start in two different directions, from left or right.
5295 /// We count undefs as zeros until PreferredNum is reached.
5296 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5297                                          unsigned NumElems, bool ZerosFromLeft,
5298                                          SelectionDAG &DAG,
5299                                          unsigned PreferredNum = -1U) {
5300   unsigned NumZeros = 0;
5301   for (unsigned i = 0; i != NumElems; ++i) {
5302     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5303     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5304     if (!Elt.getNode())
5305       break;
5306
5307     if (X86::isZeroNode(Elt))
5308       ++NumZeros;
5309     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5310       NumZeros = std::min(NumZeros + 1, PreferredNum);
5311     else
5312       break;
5313   }
5314
5315   return NumZeros;
5316 }
5317
5318 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5319 /// correspond consecutively to elements from one of the vector operands,
5320 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5321 static
5322 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5323                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5324                               unsigned NumElems, unsigned &OpNum) {
5325   bool SeenV1 = false;
5326   bool SeenV2 = false;
5327
5328   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5329     int Idx = SVOp->getMaskElt(i);
5330     // Ignore undef indicies
5331     if (Idx < 0)
5332       continue;
5333
5334     if (Idx < (int)NumElems)
5335       SeenV1 = true;
5336     else
5337       SeenV2 = true;
5338
5339     // Only accept consecutive elements from the same vector
5340     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5341       return false;
5342   }
5343
5344   OpNum = SeenV1 ? 0 : 1;
5345   return true;
5346 }
5347
5348 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5349 /// logical left shift of a vector.
5350 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5351                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5352   unsigned NumElems =
5353     SVOp->getSimpleValueType(0).getVectorNumElements();
5354   unsigned NumZeros = getNumOfConsecutiveZeros(
5355       SVOp, NumElems, false /* check zeros from right */, DAG,
5356       SVOp->getMaskElt(0));
5357   unsigned OpSrc;
5358
5359   if (!NumZeros)
5360     return false;
5361
5362   // Considering the elements in the mask that are not consecutive zeros,
5363   // check if they consecutively come from only one of the source vectors.
5364   //
5365   //               V1 = {X, A, B, C}     0
5366   //                         \  \  \    /
5367   //   vector_shuffle V1, V2 <1, 2, 3, X>
5368   //
5369   if (!isShuffleMaskConsecutive(SVOp,
5370             0,                   // Mask Start Index
5371             NumElems-NumZeros,   // Mask End Index(exclusive)
5372             NumZeros,            // Where to start looking in the src vector
5373             NumElems,            // Number of elements in vector
5374             OpSrc))              // Which source operand ?
5375     return false;
5376
5377   isLeft = false;
5378   ShAmt = NumZeros;
5379   ShVal = SVOp->getOperand(OpSrc);
5380   return true;
5381 }
5382
5383 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5384 /// logical left shift of a vector.
5385 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5386                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5387   unsigned NumElems =
5388     SVOp->getSimpleValueType(0).getVectorNumElements();
5389   unsigned NumZeros = getNumOfConsecutiveZeros(
5390       SVOp, NumElems, true /* check zeros from left */, DAG,
5391       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5392   unsigned OpSrc;
5393
5394   if (!NumZeros)
5395     return false;
5396
5397   // Considering the elements in the mask that are not consecutive zeros,
5398   // check if they consecutively come from only one of the source vectors.
5399   //
5400   //                           0    { A, B, X, X } = V2
5401   //                          / \    /  /
5402   //   vector_shuffle V1, V2 <X, X, 4, 5>
5403   //
5404   if (!isShuffleMaskConsecutive(SVOp,
5405             NumZeros,     // Mask Start Index
5406             NumElems,     // Mask End Index(exclusive)
5407             0,            // Where to start looking in the src vector
5408             NumElems,     // Number of elements in vector
5409             OpSrc))       // Which source operand ?
5410     return false;
5411
5412   isLeft = true;
5413   ShAmt = NumZeros;
5414   ShVal = SVOp->getOperand(OpSrc);
5415   return true;
5416 }
5417
5418 /// isVectorShift - Returns true if the shuffle can be implemented as a
5419 /// logical left or right shift of a vector.
5420 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5421                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5422   // Although the logic below support any bitwidth size, there are no
5423   // shift instructions which handle more than 128-bit vectors.
5424   if (!SVOp->getSimpleValueType(0).is128BitVector())
5425     return false;
5426
5427   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5428       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5429     return true;
5430
5431   return false;
5432 }
5433
5434 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5435 ///
5436 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5437                                        unsigned NumNonZero, unsigned NumZero,
5438                                        SelectionDAG &DAG,
5439                                        const X86Subtarget* Subtarget,
5440                                        const TargetLowering &TLI) {
5441   if (NumNonZero > 8)
5442     return SDValue();
5443
5444   SDLoc dl(Op);
5445   SDValue V;
5446   bool First = true;
5447   for (unsigned i = 0; i < 16; ++i) {
5448     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5449     if (ThisIsNonZero && First) {
5450       if (NumZero)
5451         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5452       else
5453         V = DAG.getUNDEF(MVT::v8i16);
5454       First = false;
5455     }
5456
5457     if ((i & 1) != 0) {
5458       SDValue ThisElt, LastElt;
5459       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5460       if (LastIsNonZero) {
5461         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5462                               MVT::i16, Op.getOperand(i-1));
5463       }
5464       if (ThisIsNonZero) {
5465         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5466         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5467                               ThisElt, DAG.getConstant(8, MVT::i8));
5468         if (LastIsNonZero)
5469           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5470       } else
5471         ThisElt = LastElt;
5472
5473       if (ThisElt.getNode())
5474         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5475                         DAG.getIntPtrConstant(i/2));
5476     }
5477   }
5478
5479   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5480 }
5481
5482 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5483 ///
5484 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5485                                      unsigned NumNonZero, unsigned NumZero,
5486                                      SelectionDAG &DAG,
5487                                      const X86Subtarget* Subtarget,
5488                                      const TargetLowering &TLI) {
5489   if (NumNonZero > 4)
5490     return SDValue();
5491
5492   SDLoc dl(Op);
5493   SDValue V;
5494   bool First = true;
5495   for (unsigned i = 0; i < 8; ++i) {
5496     bool isNonZero = (NonZeros & (1 << i)) != 0;
5497     if (isNonZero) {
5498       if (First) {
5499         if (NumZero)
5500           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5501         else
5502           V = DAG.getUNDEF(MVT::v8i16);
5503         First = false;
5504       }
5505       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5506                       MVT::v8i16, V, Op.getOperand(i),
5507                       DAG.getIntPtrConstant(i));
5508     }
5509   }
5510
5511   return V;
5512 }
5513
5514 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5515 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5516                                      unsigned NonZeros, unsigned NumNonZero,
5517                                      unsigned NumZero, SelectionDAG &DAG,
5518                                      const X86Subtarget *Subtarget,
5519                                      const TargetLowering &TLI) {
5520   // We know there's at least one non-zero element
5521   unsigned FirstNonZeroIdx = 0;
5522   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5523   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5524          X86::isZeroNode(FirstNonZero)) {
5525     ++FirstNonZeroIdx;
5526     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5527   }
5528
5529   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5530       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5531     return SDValue();
5532
5533   SDValue V = FirstNonZero.getOperand(0);
5534   MVT VVT = V.getSimpleValueType();
5535   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5536     return SDValue();
5537
5538   unsigned FirstNonZeroDst =
5539       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5540   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5541   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5542   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5543
5544   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5545     SDValue Elem = Op.getOperand(Idx);
5546     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5547       continue;
5548
5549     // TODO: What else can be here? Deal with it.
5550     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5551       return SDValue();
5552
5553     // TODO: Some optimizations are still possible here
5554     // ex: Getting one element from a vector, and the rest from another.
5555     if (Elem.getOperand(0) != V)
5556       return SDValue();
5557
5558     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5559     if (Dst == Idx)
5560       ++CorrectIdx;
5561     else if (IncorrectIdx == -1U) {
5562       IncorrectIdx = Idx;
5563       IncorrectDst = Dst;
5564     } else
5565       // There was already one element with an incorrect index.
5566       // We can't optimize this case to an insertps.
5567       return SDValue();
5568   }
5569
5570   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5571     SDLoc dl(Op);
5572     EVT VT = Op.getSimpleValueType();
5573     unsigned ElementMoveMask = 0;
5574     if (IncorrectIdx == -1U)
5575       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5576     else
5577       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5578
5579     SDValue InsertpsMask =
5580         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5581     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5582   }
5583
5584   return SDValue();
5585 }
5586
5587 /// getVShift - Return a vector logical shift node.
5588 ///
5589 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5590                          unsigned NumBits, SelectionDAG &DAG,
5591                          const TargetLowering &TLI, SDLoc dl) {
5592   assert(VT.is128BitVector() && "Unknown type for VShift");
5593   EVT ShVT = MVT::v2i64;
5594   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5595   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5596   return DAG.getNode(ISD::BITCAST, dl, VT,
5597                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5598                              DAG.getConstant(NumBits,
5599                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5600 }
5601
5602 static SDValue
5603 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5604
5605   // Check if the scalar load can be widened into a vector load. And if
5606   // the address is "base + cst" see if the cst can be "absorbed" into
5607   // the shuffle mask.
5608   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5609     SDValue Ptr = LD->getBasePtr();
5610     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5611       return SDValue();
5612     EVT PVT = LD->getValueType(0);
5613     if (PVT != MVT::i32 && PVT != MVT::f32)
5614       return SDValue();
5615
5616     int FI = -1;
5617     int64_t Offset = 0;
5618     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5619       FI = FINode->getIndex();
5620       Offset = 0;
5621     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5622                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5623       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5624       Offset = Ptr.getConstantOperandVal(1);
5625       Ptr = Ptr.getOperand(0);
5626     } else {
5627       return SDValue();
5628     }
5629
5630     // FIXME: 256-bit vector instructions don't require a strict alignment,
5631     // improve this code to support it better.
5632     unsigned RequiredAlign = VT.getSizeInBits()/8;
5633     SDValue Chain = LD->getChain();
5634     // Make sure the stack object alignment is at least 16 or 32.
5635     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5636     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5637       if (MFI->isFixedObjectIndex(FI)) {
5638         // Can't change the alignment. FIXME: It's possible to compute
5639         // the exact stack offset and reference FI + adjust offset instead.
5640         // If someone *really* cares about this. That's the way to implement it.
5641         return SDValue();
5642       } else {
5643         MFI->setObjectAlignment(FI, RequiredAlign);
5644       }
5645     }
5646
5647     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5648     // Ptr + (Offset & ~15).
5649     if (Offset < 0)
5650       return SDValue();
5651     if ((Offset % RequiredAlign) & 3)
5652       return SDValue();
5653     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5654     if (StartOffset)
5655       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5656                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5657
5658     int EltNo = (Offset - StartOffset) >> 2;
5659     unsigned NumElems = VT.getVectorNumElements();
5660
5661     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5662     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5663                              LD->getPointerInfo().getWithOffset(StartOffset),
5664                              false, false, false, 0);
5665
5666     SmallVector<int, 8> Mask;
5667     for (unsigned i = 0; i != NumElems; ++i)
5668       Mask.push_back(EltNo);
5669
5670     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5671   }
5672
5673   return SDValue();
5674 }
5675
5676 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5677 /// vector of type 'VT', see if the elements can be replaced by a single large
5678 /// load which has the same value as a build_vector whose operands are 'elts'.
5679 ///
5680 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5681 ///
5682 /// FIXME: we'd also like to handle the case where the last elements are zero
5683 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5684 /// There's even a handy isZeroNode for that purpose.
5685 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5686                                         SDLoc &DL, SelectionDAG &DAG,
5687                                         bool isAfterLegalize) {
5688   EVT EltVT = VT.getVectorElementType();
5689   unsigned NumElems = Elts.size();
5690
5691   LoadSDNode *LDBase = nullptr;
5692   unsigned LastLoadedElt = -1U;
5693
5694   // For each element in the initializer, see if we've found a load or an undef.
5695   // If we don't find an initial load element, or later load elements are
5696   // non-consecutive, bail out.
5697   for (unsigned i = 0; i < NumElems; ++i) {
5698     SDValue Elt = Elts[i];
5699
5700     if (!Elt.getNode() ||
5701         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5702       return SDValue();
5703     if (!LDBase) {
5704       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5705         return SDValue();
5706       LDBase = cast<LoadSDNode>(Elt.getNode());
5707       LastLoadedElt = i;
5708       continue;
5709     }
5710     if (Elt.getOpcode() == ISD::UNDEF)
5711       continue;
5712
5713     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5714     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5715       return SDValue();
5716     LastLoadedElt = i;
5717   }
5718
5719   // If we have found an entire vector of loads and undefs, then return a large
5720   // load of the entire vector width starting at the base pointer.  If we found
5721   // consecutive loads for the low half, generate a vzext_load node.
5722   if (LastLoadedElt == NumElems - 1) {
5723
5724     if (isAfterLegalize &&
5725         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5726       return SDValue();
5727
5728     SDValue NewLd = SDValue();
5729
5730     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5731       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5732                           LDBase->getPointerInfo(),
5733                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5734                           LDBase->isInvariant(), 0);
5735     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5736                         LDBase->getPointerInfo(),
5737                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5738                         LDBase->isInvariant(), LDBase->getAlignment());
5739
5740     if (LDBase->hasAnyUseOfValue(1)) {
5741       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5742                                      SDValue(LDBase, 1),
5743                                      SDValue(NewLd.getNode(), 1));
5744       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5745       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5746                              SDValue(NewLd.getNode(), 1));
5747     }
5748
5749     return NewLd;
5750   }
5751   if (NumElems == 4 && LastLoadedElt == 1 &&
5752       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5753     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5754     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5755     SDValue ResNode =
5756         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5757                                 LDBase->getPointerInfo(),
5758                                 LDBase->getAlignment(),
5759                                 false/*isVolatile*/, true/*ReadMem*/,
5760                                 false/*WriteMem*/);
5761
5762     // Make sure the newly-created LOAD is in the same position as LDBase in
5763     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5764     // update uses of LDBase's output chain to use the TokenFactor.
5765     if (LDBase->hasAnyUseOfValue(1)) {
5766       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5767                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5768       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5769       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5770                              SDValue(ResNode.getNode(), 1));
5771     }
5772
5773     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5774   }
5775   return SDValue();
5776 }
5777
5778 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5779 /// to generate a splat value for the following cases:
5780 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5781 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5782 /// a scalar load, or a constant.
5783 /// The VBROADCAST node is returned when a pattern is found,
5784 /// or SDValue() otherwise.
5785 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5786                                     SelectionDAG &DAG) {
5787   if (!Subtarget->hasFp256())
5788     return SDValue();
5789
5790   MVT VT = Op.getSimpleValueType();
5791   SDLoc dl(Op);
5792
5793   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5794          "Unsupported vector type for broadcast.");
5795
5796   SDValue Ld;
5797   bool ConstSplatVal;
5798
5799   switch (Op.getOpcode()) {
5800     default:
5801       // Unknown pattern found.
5802       return SDValue();
5803
5804     case ISD::BUILD_VECTOR: {
5805       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5806       BitVector UndefElements;
5807       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5808
5809       // We need a splat of a single value to use broadcast, and it doesn't
5810       // make any sense if the value is only in one element of the vector.
5811       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5812         return SDValue();
5813
5814       Ld = Splat;
5815       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5816                        Ld.getOpcode() == ISD::ConstantFP);
5817
5818       // Make sure that all of the users of a non-constant load are from the
5819       // BUILD_VECTOR node.
5820       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5821         return SDValue();
5822       break;
5823     }
5824
5825     case ISD::VECTOR_SHUFFLE: {
5826       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5827
5828       // Shuffles must have a splat mask where the first element is
5829       // broadcasted.
5830       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5831         return SDValue();
5832
5833       SDValue Sc = Op.getOperand(0);
5834       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5835           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5836
5837         if (!Subtarget->hasInt256())
5838           return SDValue();
5839
5840         // Use the register form of the broadcast instruction available on AVX2.
5841         if (VT.getSizeInBits() >= 256)
5842           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5843         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5844       }
5845
5846       Ld = Sc.getOperand(0);
5847       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5848                        Ld.getOpcode() == ISD::ConstantFP);
5849
5850       // The scalar_to_vector node and the suspected
5851       // load node must have exactly one user.
5852       // Constants may have multiple users.
5853
5854       // AVX-512 has register version of the broadcast
5855       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5856         Ld.getValueType().getSizeInBits() >= 32;
5857       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5858           !hasRegVer))
5859         return SDValue();
5860       break;
5861     }
5862   }
5863
5864   bool IsGE256 = (VT.getSizeInBits() >= 256);
5865
5866   // Handle the broadcasting a single constant scalar from the constant pool
5867   // into a vector. On Sandybridge it is still better to load a constant vector
5868   // from the constant pool and not to broadcast it from a scalar.
5869   if (ConstSplatVal && Subtarget->hasInt256()) {
5870     EVT CVT = Ld.getValueType();
5871     assert(!CVT.isVector() && "Must not broadcast a vector type");
5872     unsigned ScalarSize = CVT.getSizeInBits();
5873
5874     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5875       const Constant *C = nullptr;
5876       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5877         C = CI->getConstantIntValue();
5878       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5879         C = CF->getConstantFPValue();
5880
5881       assert(C && "Invalid constant type");
5882
5883       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5884       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5885       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5886       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5887                        MachinePointerInfo::getConstantPool(),
5888                        false, false, false, Alignment);
5889
5890       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5891     }
5892   }
5893
5894   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5895   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5896
5897   // Handle AVX2 in-register broadcasts.
5898   if (!IsLoad && Subtarget->hasInt256() &&
5899       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5900     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5901
5902   // The scalar source must be a normal load.
5903   if (!IsLoad)
5904     return SDValue();
5905
5906   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5907     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5908
5909   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5910   // double since there is no vbroadcastsd xmm
5911   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5912     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5913       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5914   }
5915
5916   // Unsupported broadcast.
5917   return SDValue();
5918 }
5919
5920 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5921 /// underlying vector and index.
5922 ///
5923 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5924 /// index.
5925 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5926                                          SDValue ExtIdx) {
5927   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5928   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5929     return Idx;
5930
5931   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5932   // lowered this:
5933   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5934   // to:
5935   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5936   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5937   //                           undef)
5938   //                       Constant<0>)
5939   // In this case the vector is the extract_subvector expression and the index
5940   // is 2, as specified by the shuffle.
5941   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5942   SDValue ShuffleVec = SVOp->getOperand(0);
5943   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5944   assert(ShuffleVecVT.getVectorElementType() ==
5945          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5946
5947   int ShuffleIdx = SVOp->getMaskElt(Idx);
5948   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5949     ExtractedFromVec = ShuffleVec;
5950     return ShuffleIdx;
5951   }
5952   return Idx;
5953 }
5954
5955 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5956   MVT VT = Op.getSimpleValueType();
5957
5958   // Skip if insert_vec_elt is not supported.
5959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5960   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5961     return SDValue();
5962
5963   SDLoc DL(Op);
5964   unsigned NumElems = Op.getNumOperands();
5965
5966   SDValue VecIn1;
5967   SDValue VecIn2;
5968   SmallVector<unsigned, 4> InsertIndices;
5969   SmallVector<int, 8> Mask(NumElems, -1);
5970
5971   for (unsigned i = 0; i != NumElems; ++i) {
5972     unsigned Opc = Op.getOperand(i).getOpcode();
5973
5974     if (Opc == ISD::UNDEF)
5975       continue;
5976
5977     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5978       // Quit if more than 1 elements need inserting.
5979       if (InsertIndices.size() > 1)
5980         return SDValue();
5981
5982       InsertIndices.push_back(i);
5983       continue;
5984     }
5985
5986     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5987     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5988     // Quit if non-constant index.
5989     if (!isa<ConstantSDNode>(ExtIdx))
5990       return SDValue();
5991     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5992
5993     // Quit if extracted from vector of different type.
5994     if (ExtractedFromVec.getValueType() != VT)
5995       return SDValue();
5996
5997     if (!VecIn1.getNode())
5998       VecIn1 = ExtractedFromVec;
5999     else if (VecIn1 != ExtractedFromVec) {
6000       if (!VecIn2.getNode())
6001         VecIn2 = ExtractedFromVec;
6002       else if (VecIn2 != ExtractedFromVec)
6003         // Quit if more than 2 vectors to shuffle
6004         return SDValue();
6005     }
6006
6007     if (ExtractedFromVec == VecIn1)
6008       Mask[i] = Idx;
6009     else if (ExtractedFromVec == VecIn2)
6010       Mask[i] = Idx + NumElems;
6011   }
6012
6013   if (!VecIn1.getNode())
6014     return SDValue();
6015
6016   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6017   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6018   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6019     unsigned Idx = InsertIndices[i];
6020     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6021                      DAG.getIntPtrConstant(Idx));
6022   }
6023
6024   return NV;
6025 }
6026
6027 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6028 SDValue
6029 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6030
6031   MVT VT = Op.getSimpleValueType();
6032   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6033          "Unexpected type in LowerBUILD_VECTORvXi1!");
6034
6035   SDLoc dl(Op);
6036   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6037     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6038     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6039     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6040   }
6041
6042   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6043     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6044     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6045     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6046   }
6047
6048   bool AllContants = true;
6049   uint64_t Immediate = 0;
6050   int NonConstIdx = -1;
6051   bool IsSplat = true;
6052   unsigned NumNonConsts = 0;
6053   unsigned NumConsts = 0;
6054   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6055     SDValue In = Op.getOperand(idx);
6056     if (In.getOpcode() == ISD::UNDEF)
6057       continue;
6058     if (!isa<ConstantSDNode>(In)) {
6059       AllContants = false;
6060       NonConstIdx = idx;
6061       NumNonConsts++;
6062     }
6063     else {
6064       NumConsts++;
6065       if (cast<ConstantSDNode>(In)->getZExtValue())
6066       Immediate |= (1ULL << idx);
6067     }
6068     if (In != Op.getOperand(0))
6069       IsSplat = false;
6070   }
6071
6072   if (AllContants) {
6073     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6074       DAG.getConstant(Immediate, MVT::i16));
6075     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6076                        DAG.getIntPtrConstant(0));
6077   }
6078
6079   if (NumNonConsts == 1 && NonConstIdx != 0) {
6080     SDValue DstVec;
6081     if (NumConsts) {
6082       SDValue VecAsImm = DAG.getConstant(Immediate,
6083                                          MVT::getIntegerVT(VT.getSizeInBits()));
6084       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6085     }
6086     else 
6087       DstVec = DAG.getUNDEF(VT);
6088     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6089                        Op.getOperand(NonConstIdx),
6090                        DAG.getIntPtrConstant(NonConstIdx));
6091   }
6092   if (!IsSplat && (NonConstIdx != 0))
6093     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6094   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6095   SDValue Select;
6096   if (IsSplat)
6097     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6098                           DAG.getConstant(-1, SelectVT),
6099                           DAG.getConstant(0, SelectVT));
6100   else
6101     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6102                          DAG.getConstant((Immediate | 1), SelectVT),
6103                          DAG.getConstant(Immediate, SelectVT));
6104   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6105 }
6106
6107 /// \brief Return true if \p N implements a horizontal binop and return the
6108 /// operands for the horizontal binop into V0 and V1.
6109 /// 
6110 /// This is a helper function of PerformBUILD_VECTORCombine.
6111 /// This function checks that the build_vector \p N in input implements a
6112 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6113 /// operation to match.
6114 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6115 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6116 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6117 /// arithmetic sub.
6118 ///
6119 /// This function only analyzes elements of \p N whose indices are
6120 /// in range [BaseIdx, LastIdx).
6121 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6122                               SelectionDAG &DAG,
6123                               unsigned BaseIdx, unsigned LastIdx,
6124                               SDValue &V0, SDValue &V1) {
6125   EVT VT = N->getValueType(0);
6126
6127   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6128   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6129          "Invalid Vector in input!");
6130   
6131   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6132   bool CanFold = true;
6133   unsigned ExpectedVExtractIdx = BaseIdx;
6134   unsigned NumElts = LastIdx - BaseIdx;
6135   V0 = DAG.getUNDEF(VT);
6136   V1 = DAG.getUNDEF(VT);
6137
6138   // Check if N implements a horizontal binop.
6139   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6140     SDValue Op = N->getOperand(i + BaseIdx);
6141
6142     // Skip UNDEFs.
6143     if (Op->getOpcode() == ISD::UNDEF) {
6144       // Update the expected vector extract index.
6145       if (i * 2 == NumElts)
6146         ExpectedVExtractIdx = BaseIdx;
6147       ExpectedVExtractIdx += 2;
6148       continue;
6149     }
6150
6151     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6152
6153     if (!CanFold)
6154       break;
6155
6156     SDValue Op0 = Op.getOperand(0);
6157     SDValue Op1 = Op.getOperand(1);
6158
6159     // Try to match the following pattern:
6160     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6161     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6162         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6163         Op0.getOperand(0) == Op1.getOperand(0) &&
6164         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6165         isa<ConstantSDNode>(Op1.getOperand(1)));
6166     if (!CanFold)
6167       break;
6168
6169     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6170     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6171
6172     if (i * 2 < NumElts) {
6173       if (V0.getOpcode() == ISD::UNDEF)
6174         V0 = Op0.getOperand(0);
6175     } else {
6176       if (V1.getOpcode() == ISD::UNDEF)
6177         V1 = Op0.getOperand(0);
6178       if (i * 2 == NumElts)
6179         ExpectedVExtractIdx = BaseIdx;
6180     }
6181
6182     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6183     if (I0 == ExpectedVExtractIdx)
6184       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6185     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6186       // Try to match the following dag sequence:
6187       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6188       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6189     } else
6190       CanFold = false;
6191
6192     ExpectedVExtractIdx += 2;
6193   }
6194
6195   return CanFold;
6196 }
6197
6198 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6199 /// a concat_vector. 
6200 ///
6201 /// This is a helper function of PerformBUILD_VECTORCombine.
6202 /// This function expects two 256-bit vectors called V0 and V1.
6203 /// At first, each vector is split into two separate 128-bit vectors.
6204 /// Then, the resulting 128-bit vectors are used to implement two
6205 /// horizontal binary operations. 
6206 ///
6207 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6208 ///
6209 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6210 /// the two new horizontal binop.
6211 /// When Mode is set, the first horizontal binop dag node would take as input
6212 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6213 /// horizontal binop dag node would take as input the lower 128-bit of V1
6214 /// and the upper 128-bit of V1.
6215 ///   Example:
6216 ///     HADD V0_LO, V0_HI
6217 ///     HADD V1_LO, V1_HI
6218 ///
6219 /// Otherwise, the first horizontal binop dag node takes as input the lower
6220 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6221 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6222 ///   Example:
6223 ///     HADD V0_LO, V1_LO
6224 ///     HADD V0_HI, V1_HI
6225 ///
6226 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6227 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6228 /// the upper 128-bits of the result.
6229 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6230                                      SDLoc DL, SelectionDAG &DAG,
6231                                      unsigned X86Opcode, bool Mode,
6232                                      bool isUndefLO, bool isUndefHI) {
6233   EVT VT = V0.getValueType();
6234   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6235          "Invalid nodes in input!");
6236
6237   unsigned NumElts = VT.getVectorNumElements();
6238   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6239   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6240   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6241   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6242   EVT NewVT = V0_LO.getValueType();
6243
6244   SDValue LO = DAG.getUNDEF(NewVT);
6245   SDValue HI = DAG.getUNDEF(NewVT);
6246
6247   if (Mode) {
6248     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6249     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6250       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6251     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6252       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6253   } else {
6254     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6255     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6256                        V1_LO->getOpcode() != ISD::UNDEF))
6257       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6258
6259     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6260                        V1_HI->getOpcode() != ISD::UNDEF))
6261       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6262   }
6263
6264   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6265 }
6266
6267 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6268 /// sequence of 'vadd + vsub + blendi'.
6269 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6270                            const X86Subtarget *Subtarget) {
6271   SDLoc DL(BV);
6272   EVT VT = BV->getValueType(0);
6273   unsigned NumElts = VT.getVectorNumElements();
6274   SDValue InVec0 = DAG.getUNDEF(VT);
6275   SDValue InVec1 = DAG.getUNDEF(VT);
6276
6277   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6278           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6279
6280   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6282   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6283     return SDValue();
6284
6285   // Odd-numbered elements in the input build vector are obtained from
6286   // adding two integer/float elements.
6287   // Even-numbered elements in the input build vector are obtained from
6288   // subtracting two integer/float elements.
6289   unsigned ExpectedOpcode = ISD::FSUB;
6290   unsigned NextExpectedOpcode = ISD::FADD;
6291   bool AddFound = false;
6292   bool SubFound = false;
6293
6294   for (unsigned i = 0, e = NumElts; i != e; i++) {
6295     SDValue Op = BV->getOperand(i);
6296       
6297     // Skip 'undef' values.
6298     unsigned Opcode = Op.getOpcode();
6299     if (Opcode == ISD::UNDEF) {
6300       std::swap(ExpectedOpcode, NextExpectedOpcode);
6301       continue;
6302     }
6303       
6304     // Early exit if we found an unexpected opcode.
6305     if (Opcode != ExpectedOpcode)
6306       return SDValue();
6307
6308     SDValue Op0 = Op.getOperand(0);
6309     SDValue Op1 = Op.getOperand(1);
6310
6311     // Try to match the following pattern:
6312     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6313     // Early exit if we cannot match that sequence.
6314     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6315         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6316         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6317         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6318         Op0.getOperand(1) != Op1.getOperand(1))
6319       return SDValue();
6320
6321     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6322     if (I0 != i)
6323       return SDValue();
6324
6325     // We found a valid add/sub node. Update the information accordingly.
6326     if (i & 1)
6327       AddFound = true;
6328     else
6329       SubFound = true;
6330
6331     // Update InVec0 and InVec1.
6332     if (InVec0.getOpcode() == ISD::UNDEF)
6333       InVec0 = Op0.getOperand(0);
6334     if (InVec1.getOpcode() == ISD::UNDEF)
6335       InVec1 = Op1.getOperand(0);
6336
6337     // Make sure that operands in input to each add/sub node always
6338     // come from a same pair of vectors.
6339     if (InVec0 != Op0.getOperand(0)) {
6340       if (ExpectedOpcode == ISD::FSUB)
6341         return SDValue();
6342
6343       // FADD is commutable. Try to commute the operands
6344       // and then test again.
6345       std::swap(Op0, Op1);
6346       if (InVec0 != Op0.getOperand(0))
6347         return SDValue();
6348     }
6349
6350     if (InVec1 != Op1.getOperand(0))
6351       return SDValue();
6352
6353     // Update the pair of expected opcodes.
6354     std::swap(ExpectedOpcode, NextExpectedOpcode);
6355   }
6356
6357   // Don't try to fold this build_vector into a VSELECT if it has
6358   // too many UNDEF operands.
6359   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6360       InVec1.getOpcode() != ISD::UNDEF) {
6361     // Emit a sequence of vector add and sub followed by a VSELECT.
6362     // The new VSELECT will be lowered into a BLENDI.
6363     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6364     // and emit a single ADDSUB instruction.
6365     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6366     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6367
6368     // Construct the VSELECT mask.
6369     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6370     EVT SVT = MaskVT.getVectorElementType();
6371     unsigned SVTBits = SVT.getSizeInBits();
6372     SmallVector<SDValue, 8> Ops;
6373
6374     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6375       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6376                             APInt::getAllOnesValue(SVTBits);
6377       SDValue Constant = DAG.getConstant(Value, SVT);
6378       Ops.push_back(Constant);
6379     }
6380
6381     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6382     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6383   }
6384   
6385   return SDValue();
6386 }
6387
6388 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6389                                           const X86Subtarget *Subtarget) {
6390   SDLoc DL(N);
6391   EVT VT = N->getValueType(0);
6392   unsigned NumElts = VT.getVectorNumElements();
6393   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6394   SDValue InVec0, InVec1;
6395
6396   // Try to match an ADDSUB.
6397   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6398       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6399     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6400     if (Value.getNode())
6401       return Value;
6402   }
6403
6404   // Try to match horizontal ADD/SUB.
6405   unsigned NumUndefsLO = 0;
6406   unsigned NumUndefsHI = 0;
6407   unsigned Half = NumElts/2;
6408
6409   // Count the number of UNDEF operands in the build_vector in input.
6410   for (unsigned i = 0, e = Half; i != e; ++i)
6411     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6412       NumUndefsLO++;
6413
6414   for (unsigned i = Half, e = NumElts; i != e; ++i)
6415     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6416       NumUndefsHI++;
6417
6418   // Early exit if this is either a build_vector of all UNDEFs or all the
6419   // operands but one are UNDEF.
6420   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6421     return SDValue();
6422
6423   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6424     // Try to match an SSE3 float HADD/HSUB.
6425     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6426       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6427     
6428     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6429       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6430   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6431     // Try to match an SSSE3 integer HADD/HSUB.
6432     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6433       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6434     
6435     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6436       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6437   }
6438   
6439   if (!Subtarget->hasAVX())
6440     return SDValue();
6441
6442   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6443     // Try to match an AVX horizontal add/sub of packed single/double
6444     // precision floating point values from 256-bit vectors.
6445     SDValue InVec2, InVec3;
6446     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6447         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6448         ((InVec0.getOpcode() == ISD::UNDEF ||
6449           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6450         ((InVec1.getOpcode() == ISD::UNDEF ||
6451           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6452       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6453
6454     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6455         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6456         ((InVec0.getOpcode() == ISD::UNDEF ||
6457           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6458         ((InVec1.getOpcode() == ISD::UNDEF ||
6459           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6460       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6461   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6462     // Try to match an AVX2 horizontal add/sub of signed integers.
6463     SDValue InVec2, InVec3;
6464     unsigned X86Opcode;
6465     bool CanFold = true;
6466
6467     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6468         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6469         ((InVec0.getOpcode() == ISD::UNDEF ||
6470           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6471         ((InVec1.getOpcode() == ISD::UNDEF ||
6472           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6473       X86Opcode = X86ISD::HADD;
6474     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6475         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6476         ((InVec0.getOpcode() == ISD::UNDEF ||
6477           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6478         ((InVec1.getOpcode() == ISD::UNDEF ||
6479           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6480       X86Opcode = X86ISD::HSUB;
6481     else
6482       CanFold = false;
6483
6484     if (CanFold) {
6485       // Fold this build_vector into a single horizontal add/sub.
6486       // Do this only if the target has AVX2.
6487       if (Subtarget->hasAVX2())
6488         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6489  
6490       // Do not try to expand this build_vector into a pair of horizontal
6491       // add/sub if we can emit a pair of scalar add/sub.
6492       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6493         return SDValue();
6494
6495       // Convert this build_vector into a pair of horizontal binop followed by
6496       // a concat vector.
6497       bool isUndefLO = NumUndefsLO == Half;
6498       bool isUndefHI = NumUndefsHI == Half;
6499       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6500                                    isUndefLO, isUndefHI);
6501     }
6502   }
6503
6504   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6505        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6506     unsigned X86Opcode;
6507     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6508       X86Opcode = X86ISD::HADD;
6509     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6510       X86Opcode = X86ISD::HSUB;
6511     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6512       X86Opcode = X86ISD::FHADD;
6513     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6514       X86Opcode = X86ISD::FHSUB;
6515     else
6516       return SDValue();
6517
6518     // Don't try to expand this build_vector into a pair of horizontal add/sub
6519     // if we can simply emit a pair of scalar add/sub.
6520     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6521       return SDValue();
6522
6523     // Convert this build_vector into two horizontal add/sub followed by
6524     // a concat vector.
6525     bool isUndefLO = NumUndefsLO == Half;
6526     bool isUndefHI = NumUndefsHI == Half;
6527     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6528                                  isUndefLO, isUndefHI);
6529   }
6530
6531   return SDValue();
6532 }
6533
6534 SDValue
6535 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6536   SDLoc dl(Op);
6537
6538   MVT VT = Op.getSimpleValueType();
6539   MVT ExtVT = VT.getVectorElementType();
6540   unsigned NumElems = Op.getNumOperands();
6541
6542   // Generate vectors for predicate vectors.
6543   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6544     return LowerBUILD_VECTORvXi1(Op, DAG);
6545
6546   // Vectors containing all zeros can be matched by pxor and xorps later
6547   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6548     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6549     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6550     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6551       return Op;
6552
6553     return getZeroVector(VT, Subtarget, DAG, dl);
6554   }
6555
6556   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6557   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6558   // vpcmpeqd on 256-bit vectors.
6559   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6560     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6561       return Op;
6562
6563     if (!VT.is512BitVector())
6564       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6565   }
6566
6567   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6568   if (Broadcast.getNode())
6569     return Broadcast;
6570
6571   unsigned EVTBits = ExtVT.getSizeInBits();
6572
6573   unsigned NumZero  = 0;
6574   unsigned NumNonZero = 0;
6575   unsigned NonZeros = 0;
6576   bool IsAllConstants = true;
6577   SmallSet<SDValue, 8> Values;
6578   for (unsigned i = 0; i < NumElems; ++i) {
6579     SDValue Elt = Op.getOperand(i);
6580     if (Elt.getOpcode() == ISD::UNDEF)
6581       continue;
6582     Values.insert(Elt);
6583     if (Elt.getOpcode() != ISD::Constant &&
6584         Elt.getOpcode() != ISD::ConstantFP)
6585       IsAllConstants = false;
6586     if (X86::isZeroNode(Elt))
6587       NumZero++;
6588     else {
6589       NonZeros |= (1 << i);
6590       NumNonZero++;
6591     }
6592   }
6593
6594   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6595   if (NumNonZero == 0)
6596     return DAG.getUNDEF(VT);
6597
6598   // Special case for single non-zero, non-undef, element.
6599   if (NumNonZero == 1) {
6600     unsigned Idx = countTrailingZeros(NonZeros);
6601     SDValue Item = Op.getOperand(Idx);
6602
6603     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6604     // the value are obviously zero, truncate the value to i32 and do the
6605     // insertion that way.  Only do this if the value is non-constant or if the
6606     // value is a constant being inserted into element 0.  It is cheaper to do
6607     // a constant pool load than it is to do a movd + shuffle.
6608     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6609         (!IsAllConstants || Idx == 0)) {
6610       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6611         // Handle SSE only.
6612         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6613         EVT VecVT = MVT::v4i32;
6614         unsigned VecElts = 4;
6615
6616         // Truncate the value (which may itself be a constant) to i32, and
6617         // convert it to a vector with movd (S2V+shuffle to zero extend).
6618         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6619         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6620         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6621
6622         // Now we have our 32-bit value zero extended in the low element of
6623         // a vector.  If Idx != 0, swizzle it into place.
6624         if (Idx != 0) {
6625           SmallVector<int, 4> Mask;
6626           Mask.push_back(Idx);
6627           for (unsigned i = 1; i != VecElts; ++i)
6628             Mask.push_back(i);
6629           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6630                                       &Mask[0]);
6631         }
6632         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6633       }
6634     }
6635
6636     // If we have a constant or non-constant insertion into the low element of
6637     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6638     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6639     // depending on what the source datatype is.
6640     if (Idx == 0) {
6641       if (NumZero == 0)
6642         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6643
6644       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6645           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6646         if (VT.is256BitVector() || VT.is512BitVector()) {
6647           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6648           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6649                              Item, DAG.getIntPtrConstant(0));
6650         }
6651         assert(VT.is128BitVector() && "Expected an SSE value type!");
6652         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6653         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6654         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6655       }
6656
6657       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6658         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6659         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6660         if (VT.is256BitVector()) {
6661           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6662           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6663         } else {
6664           assert(VT.is128BitVector() && "Expected an SSE value type!");
6665           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6666         }
6667         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6668       }
6669     }
6670
6671     // Is it a vector logical left shift?
6672     if (NumElems == 2 && Idx == 1 &&
6673         X86::isZeroNode(Op.getOperand(0)) &&
6674         !X86::isZeroNode(Op.getOperand(1))) {
6675       unsigned NumBits = VT.getSizeInBits();
6676       return getVShift(true, VT,
6677                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6678                                    VT, Op.getOperand(1)),
6679                        NumBits/2, DAG, *this, dl);
6680     }
6681
6682     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6683       return SDValue();
6684
6685     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6686     // is a non-constant being inserted into an element other than the low one,
6687     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6688     // movd/movss) to move this into the low element, then shuffle it into
6689     // place.
6690     if (EVTBits == 32) {
6691       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6692
6693       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6694       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6695       SmallVector<int, 8> MaskVec;
6696       for (unsigned i = 0; i != NumElems; ++i)
6697         MaskVec.push_back(i == Idx ? 0 : 1);
6698       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6699     }
6700   }
6701
6702   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6703   if (Values.size() == 1) {
6704     if (EVTBits == 32) {
6705       // Instead of a shuffle like this:
6706       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6707       // Check if it's possible to issue this instead.
6708       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6709       unsigned Idx = countTrailingZeros(NonZeros);
6710       SDValue Item = Op.getOperand(Idx);
6711       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6712         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6713     }
6714     return SDValue();
6715   }
6716
6717   // A vector full of immediates; various special cases are already
6718   // handled, so this is best done with a single constant-pool load.
6719   if (IsAllConstants)
6720     return SDValue();
6721
6722   // For AVX-length vectors, build the individual 128-bit pieces and use
6723   // shuffles to put them in place.
6724   if (VT.is256BitVector() || VT.is512BitVector()) {
6725     SmallVector<SDValue, 64> V;
6726     for (unsigned i = 0; i != NumElems; ++i)
6727       V.push_back(Op.getOperand(i));
6728
6729     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6730
6731     // Build both the lower and upper subvector.
6732     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6733                                 makeArrayRef(&V[0], NumElems/2));
6734     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6735                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6736
6737     // Recreate the wider vector with the lower and upper part.
6738     if (VT.is256BitVector())
6739       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6740     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6741   }
6742
6743   // Let legalizer expand 2-wide build_vectors.
6744   if (EVTBits == 64) {
6745     if (NumNonZero == 1) {
6746       // One half is zero or undef.
6747       unsigned Idx = countTrailingZeros(NonZeros);
6748       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6749                                  Op.getOperand(Idx));
6750       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6751     }
6752     return SDValue();
6753   }
6754
6755   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6756   if (EVTBits == 8 && NumElems == 16) {
6757     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6758                                         Subtarget, *this);
6759     if (V.getNode()) return V;
6760   }
6761
6762   if (EVTBits == 16 && NumElems == 8) {
6763     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6764                                       Subtarget, *this);
6765     if (V.getNode()) return V;
6766   }
6767
6768   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6769   if (EVTBits == 32 && NumElems == 4) {
6770     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6771                                       NumZero, DAG, Subtarget, *this);
6772     if (V.getNode())
6773       return V;
6774   }
6775
6776   // If element VT is == 32 bits, turn it into a number of shuffles.
6777   SmallVector<SDValue, 8> V(NumElems);
6778   if (NumElems == 4 && NumZero > 0) {
6779     for (unsigned i = 0; i < 4; ++i) {
6780       bool isZero = !(NonZeros & (1 << i));
6781       if (isZero)
6782         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6783       else
6784         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6785     }
6786
6787     for (unsigned i = 0; i < 2; ++i) {
6788       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6789         default: break;
6790         case 0:
6791           V[i] = V[i*2];  // Must be a zero vector.
6792           break;
6793         case 1:
6794           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6795           break;
6796         case 2:
6797           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6798           break;
6799         case 3:
6800           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6801           break;
6802       }
6803     }
6804
6805     bool Reverse1 = (NonZeros & 0x3) == 2;
6806     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6807     int MaskVec[] = {
6808       Reverse1 ? 1 : 0,
6809       Reverse1 ? 0 : 1,
6810       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6811       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6812     };
6813     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6814   }
6815
6816   if (Values.size() > 1 && VT.is128BitVector()) {
6817     // Check for a build vector of consecutive loads.
6818     for (unsigned i = 0; i < NumElems; ++i)
6819       V[i] = Op.getOperand(i);
6820
6821     // Check for elements which are consecutive loads.
6822     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6823     if (LD.getNode())
6824       return LD;
6825
6826     // Check for a build vector from mostly shuffle plus few inserting.
6827     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6828     if (Sh.getNode())
6829       return Sh;
6830
6831     // For SSE 4.1, use insertps to put the high elements into the low element.
6832     if (getSubtarget()->hasSSE41()) {
6833       SDValue Result;
6834       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6835         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6836       else
6837         Result = DAG.getUNDEF(VT);
6838
6839       for (unsigned i = 1; i < NumElems; ++i) {
6840         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6841         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6842                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6843       }
6844       return Result;
6845     }
6846
6847     // Otherwise, expand into a number of unpckl*, start by extending each of
6848     // our (non-undef) elements to the full vector width with the element in the
6849     // bottom slot of the vector (which generates no code for SSE).
6850     for (unsigned i = 0; i < NumElems; ++i) {
6851       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6852         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6853       else
6854         V[i] = DAG.getUNDEF(VT);
6855     }
6856
6857     // Next, we iteratively mix elements, e.g. for v4f32:
6858     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6859     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6860     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6861     unsigned EltStride = NumElems >> 1;
6862     while (EltStride != 0) {
6863       for (unsigned i = 0; i < EltStride; ++i) {
6864         // If V[i+EltStride] is undef and this is the first round of mixing,
6865         // then it is safe to just drop this shuffle: V[i] is already in the
6866         // right place, the one element (since it's the first round) being
6867         // inserted as undef can be dropped.  This isn't safe for successive
6868         // rounds because they will permute elements within both vectors.
6869         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6870             EltStride == NumElems/2)
6871           continue;
6872
6873         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6874       }
6875       EltStride >>= 1;
6876     }
6877     return V[0];
6878   }
6879   return SDValue();
6880 }
6881
6882 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6883 // to create 256-bit vectors from two other 128-bit ones.
6884 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6885   SDLoc dl(Op);
6886   MVT ResVT = Op.getSimpleValueType();
6887
6888   assert((ResVT.is256BitVector() ||
6889           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6890
6891   SDValue V1 = Op.getOperand(0);
6892   SDValue V2 = Op.getOperand(1);
6893   unsigned NumElems = ResVT.getVectorNumElements();
6894   if(ResVT.is256BitVector())
6895     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6896
6897   if (Op.getNumOperands() == 4) {
6898     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6899                                 ResVT.getVectorNumElements()/2);
6900     SDValue V3 = Op.getOperand(2);
6901     SDValue V4 = Op.getOperand(3);
6902     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6903       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6904   }
6905   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6906 }
6907
6908 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6909   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6910   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6911          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6912           Op.getNumOperands() == 4)));
6913
6914   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6915   // from two other 128-bit ones.
6916
6917   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6918   return LowerAVXCONCAT_VECTORS(Op, DAG);
6919 }
6920
6921
6922 //===----------------------------------------------------------------------===//
6923 // Vector shuffle lowering
6924 //
6925 // This is an experimental code path for lowering vector shuffles on x86. It is
6926 // designed to handle arbitrary vector shuffles and blends, gracefully
6927 // degrading performance as necessary. It works hard to recognize idiomatic
6928 // shuffles and lower them to optimal instruction patterns without leaving
6929 // a framework that allows reasonably efficient handling of all vector shuffle
6930 // patterns.
6931 //===----------------------------------------------------------------------===//
6932
6933 /// \brief Tiny helper function to identify a no-op mask.
6934 ///
6935 /// This is a somewhat boring predicate function. It checks whether the mask
6936 /// array input, which is assumed to be a single-input shuffle mask of the kind
6937 /// used by the X86 shuffle instructions (not a fully general
6938 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6939 /// in-place shuffle are 'no-op's.
6940 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6941   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6942     if (Mask[i] != -1 && Mask[i] != i)
6943       return false;
6944   return true;
6945 }
6946
6947 /// \brief Helper function to classify a mask as a single-input mask.
6948 ///
6949 /// This isn't a generic single-input test because in the vector shuffle
6950 /// lowering we canonicalize single inputs to be the first input operand. This
6951 /// means we can more quickly test for a single input by only checking whether
6952 /// an input from the second operand exists. We also assume that the size of
6953 /// mask corresponds to the size of the input vectors which isn't true in the
6954 /// fully general case.
6955 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6956   for (int M : Mask)
6957     if (M >= (int)Mask.size())
6958       return false;
6959   return true;
6960 }
6961
6962 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6963 ///
6964 /// This helper function produces an 8-bit shuffle immediate corresponding to
6965 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6966 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6967 /// example.
6968 ///
6969 /// NB: We rely heavily on "undef" masks preserving the input lane.
6970 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6971                                           SelectionDAG &DAG) {
6972   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6973   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6974   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6975   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6976   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6977
6978   unsigned Imm = 0;
6979   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6980   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6981   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6982   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6983   return DAG.getConstant(Imm, MVT::i8);
6984 }
6985
6986 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6987 ///
6988 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6989 /// support for floating point shuffles but not integer shuffles. These
6990 /// instructions will incur a domain crossing penalty on some chips though so
6991 /// it is better to avoid lowering through this for integer vectors where
6992 /// possible.
6993 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6994                                        const X86Subtarget *Subtarget,
6995                                        SelectionDAG &DAG) {
6996   SDLoc DL(Op);
6997   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6998   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6999   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7000   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7001   ArrayRef<int> Mask = SVOp->getMask();
7002   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7003
7004   if (isSingleInputShuffleMask(Mask)) {
7005     // Straight shuffle of a single input vector. Simulate this by using the
7006     // single input as both of the "inputs" to this instruction..
7007     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7008     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7009                        DAG.getConstant(SHUFPDMask, MVT::i8));
7010   }
7011   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7012   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7013
7014   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7015   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7016                      DAG.getConstant(SHUFPDMask, MVT::i8));
7017 }
7018
7019 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7020 ///
7021 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7022 /// the integer unit to minimize domain crossing penalties. However, for blends
7023 /// it falls back to the floating point shuffle operation with appropriate bit
7024 /// casting.
7025 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7026                                        const X86Subtarget *Subtarget,
7027                                        SelectionDAG &DAG) {
7028   SDLoc DL(Op);
7029   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7030   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7031   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7032   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7033   ArrayRef<int> Mask = SVOp->getMask();
7034   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7035
7036   if (isSingleInputShuffleMask(Mask)) {
7037     // Straight shuffle of a single input vector. For everything from SSE2
7038     // onward this has a single fast instruction with no scary immediates.
7039     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7040     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7041     int WidenedMask[4] = {
7042         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7043         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7044     return DAG.getNode(
7045         ISD::BITCAST, DL, MVT::v2i64,
7046         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7047                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7048   }
7049
7050   // We implement this with SHUFPD which is pretty lame because it will likely
7051   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7052   // However, all the alternatives are still more cycles and newer chips don't
7053   // have this problem. It would be really nice if x86 had better shuffles here.
7054   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7055   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7056   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7057                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7058 }
7059
7060 /// \brief Lower 4-lane 32-bit floating point shuffles.
7061 ///
7062 /// Uses instructions exclusively from the floating point unit to minimize
7063 /// domain crossing penalties, as these are sufficient to implement all v4f32
7064 /// shuffles.
7065 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7066                                        const X86Subtarget *Subtarget,
7067                                        SelectionDAG &DAG) {
7068   SDLoc DL(Op);
7069   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7070   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7071   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7073   ArrayRef<int> Mask = SVOp->getMask();
7074   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7075
7076   SDValue LowV = V1, HighV = V2;
7077   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7078
7079   int NumV2Elements =
7080       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7081
7082   if (NumV2Elements == 0)
7083     // Straight shuffle of a single input vector. We pass the input vector to
7084     // both operands to simulate this with a SHUFPS.
7085     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7086                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7087
7088   if (NumV2Elements == 1) {
7089     int V2Index =
7090         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7091         Mask.begin();
7092     // Compute the index adjacent to V2Index and in the same half by toggling
7093     // the low bit.
7094     int V2AdjIndex = V2Index ^ 1;
7095
7096     if (Mask[V2AdjIndex] == -1) {
7097       // Handles all the cases where we have a single V2 element and an undef.
7098       // This will only ever happen in the high lanes because we commute the
7099       // vector otherwise.
7100       if (V2Index < 2)
7101         std::swap(LowV, HighV);
7102       NewMask[V2Index] -= 4;
7103     } else {
7104       // Handle the case where the V2 element ends up adjacent to a V1 element.
7105       // To make this work, blend them together as the first step.
7106       int V1Index = V2AdjIndex;
7107       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7108       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7109                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7110
7111       // Now proceed to reconstruct the final blend as we have the necessary
7112       // high or low half formed.
7113       if (V2Index < 2) {
7114         LowV = V2;
7115         HighV = V1;
7116       } else {
7117         HighV = V2;
7118       }
7119       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7120       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7121     }
7122   } else if (NumV2Elements == 2) {
7123     if (Mask[0] < 4 && Mask[1] < 4) {
7124       // Handle the easy case where we have V1 in the low lanes and V2 in the
7125       // high lanes. We never see this reversed because we sort the shuffle.
7126       NewMask[2] -= 4;
7127       NewMask[3] -= 4;
7128     } else {
7129       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7130       // trying to place elements directly, just blend them and set up the final
7131       // shuffle to place them.
7132
7133       // The first two blend mask elements are for V1, the second two are for
7134       // V2.
7135       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7136                           Mask[2] < 4 ? Mask[2] : Mask[3],
7137                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7138                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7139       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7140                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7141
7142       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7143       // a blend.
7144       LowV = HighV = V1;
7145       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7146       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7147       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7148       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7149     }
7150   }
7151   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7152                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7153 }
7154
7155 /// \brief Lower 4-lane i32 vector shuffles.
7156 ///
7157 /// We try to handle these with integer-domain shuffles where we can, but for
7158 /// blends we use the floating point domain blend instructions.
7159 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7160                                        const X86Subtarget *Subtarget,
7161                                        SelectionDAG &DAG) {
7162   SDLoc DL(Op);
7163   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7164   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7165   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7166   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7167   ArrayRef<int> Mask = SVOp->getMask();
7168   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7169
7170   if (isSingleInputShuffleMask(Mask))
7171     // Straight shuffle of a single input vector. For everything from SSE2
7172     // onward this has a single fast instruction with no scary immediates.
7173     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7174                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7175
7176   // We implement this with SHUFPS because it can blend from two vectors.
7177   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7178   // up the inputs, bypassing domain shift penalties that we would encur if we
7179   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7180   // relevant.
7181   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7182                      DAG.getVectorShuffle(
7183                          MVT::v4f32, DL,
7184                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7185                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7186 }
7187
7188 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7189 /// shuffle lowering, and the most complex part.
7190 ///
7191 /// The lowering strategy is to try to form pairs of input lanes which are
7192 /// targeted at the same half of the final vector, and then use a dword shuffle
7193 /// to place them onto the right half, and finally unpack the paired lanes into
7194 /// their final position.
7195 ///
7196 /// The exact breakdown of how to form these dword pairs and align them on the
7197 /// correct sides is really tricky. See the comments within the function for
7198 /// more of the details.
7199 static SDValue lowerV8I16SingleInputVectorShuffle(
7200     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7201     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7202   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7203   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7204   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7205
7206   SmallVector<int, 4> LoInputs;
7207   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7208                [](int M) { return M >= 0; });
7209   std::sort(LoInputs.begin(), LoInputs.end());
7210   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7211   SmallVector<int, 4> HiInputs;
7212   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7213                [](int M) { return M >= 0; });
7214   std::sort(HiInputs.begin(), HiInputs.end());
7215   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7216   int NumLToL =
7217       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7218   int NumHToL = LoInputs.size() - NumLToL;
7219   int NumLToH =
7220       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7221   int NumHToH = HiInputs.size() - NumLToH;
7222   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7223   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7224   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7225   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7226
7227   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7228   // such inputs we can swap two of the dwords across the half mark and end up
7229   // with <=2 inputs to each half in each half. Once there, we can fall through
7230   // to the generic code below. For example:
7231   //
7232   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7233   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7234   //
7235   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7236   // and 2-2.
7237   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7238                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7239     // Compute the index of dword with only one word among the three inputs in
7240     // a half by taking the sum of the half with three inputs and subtracting
7241     // the sum of the actual three inputs. The difference is the remaining
7242     // slot.
7243     int DWordA = (ThreeInputHalfSum -
7244                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7245                  2;
7246     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7247
7248     int PSHUFDMask[] = {0, 1, 2, 3};
7249     PSHUFDMask[DWordA] = DWordB;
7250     PSHUFDMask[DWordB] = DWordA;
7251     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7252                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7253                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7254                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7255
7256     // Adjust the mask to match the new locations of A and B.
7257     for (int &M : Mask)
7258       if (M != -1 && M/2 == DWordA)
7259         M = 2 * DWordB + M % 2;
7260       else if (M != -1 && M/2 == DWordB)
7261         M = 2 * DWordA + M % 2;
7262
7263     // Recurse back into this routine to re-compute state now that this isn't
7264     // a 3 and 1 problem.
7265     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7266                                 Mask);
7267   };
7268   if (NumLToL == 3 && NumHToL == 1)
7269     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7270   else if (NumLToL == 1 && NumHToL == 3)
7271     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7272   else if (NumLToH == 1 && NumHToH == 3)
7273     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7274   else if (NumLToH == 3 && NumHToH == 1)
7275     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7276
7277   // At this point there are at most two inputs to the low and high halves from
7278   // each half. That means the inputs can always be grouped into dwords and
7279   // those dwords can then be moved to the correct half with a dword shuffle.
7280   // We use at most one low and one high word shuffle to collect these paired
7281   // inputs into dwords, and finally a dword shuffle to place them.
7282   int PSHUFLMask[4] = {-1, -1, -1, -1};
7283   int PSHUFHMask[4] = {-1, -1, -1, -1};
7284   int PSHUFDMask[4] = {-1, -1, -1, -1};
7285
7286   // First fix the masks for all the inputs that are staying in their
7287   // original halves. This will then dictate the targets of the cross-half
7288   // shuffles.
7289   auto fixInPlaceInputs = [&PSHUFDMask](
7290       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7291       MutableArrayRef<int> HalfMask, int HalfOffset) {
7292     if (InPlaceInputs.empty())
7293       return;
7294     if (InPlaceInputs.size() == 1) {
7295       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7296           InPlaceInputs[0] - HalfOffset;
7297       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7298       return;
7299     }
7300
7301     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7302     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7303         InPlaceInputs[0] - HalfOffset;
7304     // Put the second input next to the first so that they are packed into
7305     // a dword. We find the adjacent index by toggling the low bit.
7306     int AdjIndex = InPlaceInputs[0] ^ 1;
7307     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7308     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7309     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7310   };
7311   if (!HToLInputs.empty())
7312     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7313   if (!LToHInputs.empty())
7314     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7315
7316   // Now gather the cross-half inputs and place them into a free dword of
7317   // their target half.
7318   // FIXME: This operation could almost certainly be simplified dramatically to
7319   // look more like the 3-1 fixing operation.
7320   auto moveInputsToRightHalf = [&PSHUFDMask](
7321       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7322       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7323       int SourceOffset, int DestOffset) {
7324     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7325       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7326     };
7327     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7328                                                int Word) {
7329       int LowWord = Word & ~1;
7330       int HighWord = Word | 1;
7331       return isWordClobbered(SourceHalfMask, LowWord) ||
7332              isWordClobbered(SourceHalfMask, HighWord);
7333     };
7334
7335     if (IncomingInputs.empty())
7336       return;
7337
7338     if (ExistingInputs.empty()) {
7339       // Map any dwords with inputs from them into the right half.
7340       for (int Input : IncomingInputs) {
7341         // If the source half mask maps over the inputs, turn those into
7342         // swaps and use the swapped lane.
7343         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7344           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7345             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7346                 Input - SourceOffset;
7347             // We have to swap the uses in our half mask in one sweep.
7348             for (int &M : HalfMask)
7349               if (M == SourceHalfMask[Input - SourceOffset])
7350                 M = Input;
7351               else if (M == Input)
7352                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7353           } else {
7354             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7355                        Input - SourceOffset &&
7356                    "Previous placement doesn't match!");
7357           }
7358           // Note that this correctly re-maps both when we do a swap and when
7359           // we observe the other side of the swap above. We rely on that to
7360           // avoid swapping the members of the input list directly.
7361           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7362         }
7363
7364         // Map the input's dword into the correct half.
7365         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7366           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7367         else
7368           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7369                      Input / 2 &&
7370                  "Previous placement doesn't match!");
7371       }
7372
7373       // And just directly shift any other-half mask elements to be same-half
7374       // as we will have mirrored the dword containing the element into the
7375       // same position within that half.
7376       for (int &M : HalfMask)
7377         if (M >= SourceOffset && M < SourceOffset + 4) {
7378           M = M - SourceOffset + DestOffset;
7379           assert(M >= 0 && "This should never wrap below zero!");
7380         }
7381       return;
7382     }
7383
7384     // Ensure we have the input in a viable dword of its current half. This
7385     // is particularly tricky because the original position may be clobbered
7386     // by inputs being moved and *staying* in that half.
7387     if (IncomingInputs.size() == 1) {
7388       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7389         int InputFixed = std::find(std::begin(SourceHalfMask),
7390                                    std::end(SourceHalfMask), -1) -
7391                          std::begin(SourceHalfMask) + SourceOffset;
7392         SourceHalfMask[InputFixed - SourceOffset] =
7393             IncomingInputs[0] - SourceOffset;
7394         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7395                      InputFixed);
7396         IncomingInputs[0] = InputFixed;
7397       }
7398     } else if (IncomingInputs.size() == 2) {
7399       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7400           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7401         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7402         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7403                "Not all dwords can be clobbered!");
7404         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7405         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7406         for (int &M : HalfMask)
7407           if (M == IncomingInputs[0])
7408             M = SourceDWordBase + SourceOffset;
7409           else if (M == IncomingInputs[1])
7410             M = SourceDWordBase + 1 + SourceOffset;
7411         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7412         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7413       }
7414     } else {
7415       llvm_unreachable("Unhandled input size!");
7416     }
7417
7418     // Now hoist the DWord down to the right half.
7419     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7420     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7421     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7422     for (int Input : IncomingInputs)
7423       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7424                    FreeDWord * 2 + Input % 2);
7425   };
7426   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7427                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7428   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7429                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7430
7431   // Now enact all the shuffles we've computed to move the inputs into their
7432   // target half.
7433   if (!isNoopShuffleMask(PSHUFLMask))
7434     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7435                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7436   if (!isNoopShuffleMask(PSHUFHMask))
7437     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7438                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7439   if (!isNoopShuffleMask(PSHUFDMask))
7440     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7441                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7442                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7443                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7444
7445   // At this point, each half should contain all its inputs, and we can then
7446   // just shuffle them into their final position.
7447   assert(std::count_if(LoMask.begin(), LoMask.end(),
7448                        [](int M) { return M >= 4; }) == 0 &&
7449          "Failed to lift all the high half inputs to the low mask!");
7450   assert(std::count_if(HiMask.begin(), HiMask.end(),
7451                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7452          "Failed to lift all the low half inputs to the high mask!");
7453
7454   // Do a half shuffle for the low mask.
7455   if (!isNoopShuffleMask(LoMask))
7456     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7457                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7458
7459   // Do a half shuffle with the high mask after shifting its values down.
7460   for (int &M : HiMask)
7461     if (M >= 0)
7462       M -= 4;
7463   if (!isNoopShuffleMask(HiMask))
7464     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7465                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7466
7467   return V;
7468 }
7469
7470 /// \brief Detect whether the mask pattern should be lowered through
7471 /// interleaving.
7472 ///
7473 /// This essentially tests whether viewing the mask as an interleaving of two
7474 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7475 /// lowering it through interleaving is a significantly better strategy.
7476 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7477   int NumEvenInputs[2] = {0, 0};
7478   int NumOddInputs[2] = {0, 0};
7479   int NumLoInputs[2] = {0, 0};
7480   int NumHiInputs[2] = {0, 0};
7481   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7482     if (Mask[i] < 0)
7483       continue;
7484
7485     int InputIdx = Mask[i] >= Size;
7486
7487     if (i < Size / 2)
7488       ++NumLoInputs[InputIdx];
7489     else
7490       ++NumHiInputs[InputIdx];
7491
7492     if ((i % 2) == 0)
7493       ++NumEvenInputs[InputIdx];
7494     else
7495       ++NumOddInputs[InputIdx];
7496   }
7497
7498   // The minimum number of cross-input results for both the interleaved and
7499   // split cases. If interleaving results in fewer cross-input results, return
7500   // true.
7501   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7502                                     NumEvenInputs[0] + NumOddInputs[1]);
7503   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7504                               NumLoInputs[0] + NumHiInputs[1]);
7505   return InterleavedCrosses < SplitCrosses;
7506 }
7507
7508 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7509 ///
7510 /// This strategy only works when the inputs from each vector fit into a single
7511 /// half of that vector, and generally there are not so many inputs as to leave
7512 /// the in-place shuffles required highly constrained (and thus expensive). It
7513 /// shifts all the inputs into a single side of both input vectors and then
7514 /// uses an unpack to interleave these inputs in a single vector. At that
7515 /// point, we will fall back on the generic single input shuffle lowering.
7516 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7517                                                  SDValue V2,
7518                                                  MutableArrayRef<int> Mask,
7519                                                  const X86Subtarget *Subtarget,
7520                                                  SelectionDAG &DAG) {
7521   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7522   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7523   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7524   for (int i = 0; i < 8; ++i)
7525     if (Mask[i] >= 0 && Mask[i] < 4)
7526       LoV1Inputs.push_back(i);
7527     else if (Mask[i] >= 4 && Mask[i] < 8)
7528       HiV1Inputs.push_back(i);
7529     else if (Mask[i] >= 8 && Mask[i] < 12)
7530       LoV2Inputs.push_back(i);
7531     else if (Mask[i] >= 12)
7532       HiV2Inputs.push_back(i);
7533
7534   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7535   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7536   (void)NumV1Inputs;
7537   (void)NumV2Inputs;
7538   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7539   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7540   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7541
7542   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7543                      HiV1Inputs.size() + HiV2Inputs.size();
7544
7545   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7546                               ArrayRef<int> HiInputs, bool MoveToLo,
7547                               int MaskOffset) {
7548     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7549     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7550     if (BadInputs.empty())
7551       return V;
7552
7553     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7554     int MoveOffset = MoveToLo ? 0 : 4;
7555
7556     if (GoodInputs.empty()) {
7557       for (int BadInput : BadInputs) {
7558         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7559         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7560       }
7561     } else {
7562       if (GoodInputs.size() == 2) {
7563         // If the low inputs are spread across two dwords, pack them into
7564         // a single dword.
7565         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7566             Mask[GoodInputs[0]] - MaskOffset;
7567         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7568             Mask[GoodInputs[1]] - MaskOffset;
7569         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7570         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7571       } else {
7572         // Otherwise pin the low inputs.
7573         for (int GoodInput : GoodInputs)
7574           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7575       }
7576
7577       int MoveMaskIdx =
7578           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7579           std::begin(MoveMask);
7580       assert(MoveMaskIdx >= MoveOffset && "Established above");
7581
7582       if (BadInputs.size() == 2) {
7583         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7584         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7585         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7586             Mask[BadInputs[0]] - MaskOffset;
7587         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7588             Mask[BadInputs[1]] - MaskOffset;
7589         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7590         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7591       } else {
7592         assert(BadInputs.size() == 1 && "All sizes handled");
7593         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7594         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7595       }
7596     }
7597
7598     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7599                                 MoveMask);
7600   };
7601   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7602                         /*MaskOffset*/ 0);
7603   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7604                         /*MaskOffset*/ 8);
7605
7606   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7607   // cross-half traffic in the final shuffle.
7608
7609   // Munge the mask to be a single-input mask after the unpack merges the
7610   // results.
7611   for (int &M : Mask)
7612     if (M != -1)
7613       M = 2 * (M % 4) + (M / 8);
7614
7615   return DAG.getVectorShuffle(
7616       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7617                                   DL, MVT::v8i16, V1, V2),
7618       DAG.getUNDEF(MVT::v8i16), Mask);
7619 }
7620
7621 /// \brief Generic lowering of 8-lane i16 shuffles.
7622 ///
7623 /// This handles both single-input shuffles and combined shuffle/blends with
7624 /// two inputs. The single input shuffles are immediately delegated to
7625 /// a dedicated lowering routine.
7626 ///
7627 /// The blends are lowered in one of three fundamental ways. If there are few
7628 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7629 /// of the input is significantly cheaper when lowered as an interleaving of
7630 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7631 /// halves of the inputs separately (making them have relatively few inputs)
7632 /// and then concatenate them.
7633 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7634                                        const X86Subtarget *Subtarget,
7635                                        SelectionDAG &DAG) {
7636   SDLoc DL(Op);
7637   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7638   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7639   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7640   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7641   ArrayRef<int> OrigMask = SVOp->getMask();
7642   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7643                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7644   MutableArrayRef<int> Mask(MaskStorage);
7645
7646   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7647
7648   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7649   auto isV2 = [](int M) { return M >= 8; };
7650
7651   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7652   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7653
7654   if (NumV2Inputs == 0)
7655     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7656
7657   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7658                             "to be V1-input shuffles.");
7659
7660   if (NumV1Inputs + NumV2Inputs <= 4)
7661     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7662
7663   // Check whether an interleaving lowering is likely to be more efficient.
7664   // This isn't perfect but it is a strong heuristic that tends to work well on
7665   // the kinds of shuffles that show up in practice.
7666   //
7667   // FIXME: Handle 1x, 2x, and 4x interleaving.
7668   if (shouldLowerAsInterleaving(Mask)) {
7669     // FIXME: Figure out whether we should pack these into the low or high
7670     // halves.
7671
7672     int EMask[8], OMask[8];
7673     for (int i = 0; i < 4; ++i) {
7674       EMask[i] = Mask[2*i];
7675       OMask[i] = Mask[2*i + 1];
7676       EMask[i + 4] = -1;
7677       OMask[i + 4] = -1;
7678     }
7679
7680     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7681     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7682
7683     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7684   }
7685
7686   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7687   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7688
7689   for (int i = 0; i < 4; ++i) {
7690     LoBlendMask[i] = Mask[i];
7691     HiBlendMask[i] = Mask[i + 4];
7692   }
7693
7694   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7695   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7696   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7697   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7698
7699   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7700                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7701 }
7702
7703 /// \brief Generic lowering of v16i8 shuffles.
7704 ///
7705 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7706 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7707 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7708 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7709 /// back together.
7710 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7711                                        const X86Subtarget *Subtarget,
7712                                        SelectionDAG &DAG) {
7713   SDLoc DL(Op);
7714   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7715   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7716   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7718   ArrayRef<int> OrigMask = SVOp->getMask();
7719   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7720   int MaskStorage[16] = {
7721       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7722       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7723       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7724       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7725   MutableArrayRef<int> Mask(MaskStorage);
7726   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7727   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7728
7729   // For single-input shuffles, there are some nicer lowering tricks we can use.
7730   if (isSingleInputShuffleMask(Mask)) {
7731     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7732     // Notably, this handles splat and partial-splat shuffles more efficiently.
7733     // However, it only makes sense if the pre-duplication shuffle simplifies
7734     // things significantly. Currently, this means we need to be able to
7735     // express the pre-duplication shuffle as an i16 shuffle.
7736     //
7737     // FIXME: We should check for other patterns which can be widened into an
7738     // i16 shuffle as well.
7739     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7740       for (int i = 0; i < 16; i += 2) {
7741         if (Mask[i] != Mask[i + 1])
7742           return false;
7743       }
7744       return true;
7745     };
7746     auto tryToWidenViaDuplication = [&]() -> SDValue {
7747       if (!canWidenViaDuplication(Mask))
7748         return SDValue();
7749       SmallVector<int, 4> LoInputs;
7750       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7751                    [](int M) { return M >= 0 && M < 8; });
7752       std::sort(LoInputs.begin(), LoInputs.end());
7753       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7754                      LoInputs.end());
7755       SmallVector<int, 4> HiInputs;
7756       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7757                    [](int M) { return M >= 8; });
7758       std::sort(HiInputs.begin(), HiInputs.end());
7759       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7760                      HiInputs.end());
7761
7762       bool TargetLo = LoInputs.size() >= HiInputs.size();
7763       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7764       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7765
7766       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7767       SmallDenseMap<int, int, 8> LaneMap;
7768       for (int I : InPlaceInputs) {
7769         PreDupI16Shuffle[I/2] = I/2;
7770         LaneMap[I] = I;
7771       }
7772       int j = TargetLo ? 0 : 4, je = j + 4;
7773       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7774         // Check if j is already a shuffle of this input. This happens when
7775         // there are two adjacent bytes after we move the low one.
7776         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7777           // If we haven't yet mapped the input, search for a slot into which
7778           // we can map it.
7779           while (j < je && PreDupI16Shuffle[j] != -1)
7780             ++j;
7781
7782           if (j == je)
7783             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7784             return SDValue();
7785
7786           // Map this input with the i16 shuffle.
7787           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7788         }
7789
7790         // Update the lane map based on the mapping we ended up with.
7791         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7792       }
7793       V1 = DAG.getNode(
7794           ISD::BITCAST, DL, MVT::v16i8,
7795           DAG.getVectorShuffle(MVT::v8i16, DL,
7796                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7797                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7798
7799       // Unpack the bytes to form the i16s that will be shuffled into place.
7800       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7801                        MVT::v16i8, V1, V1);
7802
7803       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7804       for (int i = 0; i < 16; i += 2) {
7805         if (Mask[i] != -1)
7806           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7807         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7808       }
7809       return DAG.getNode(
7810           ISD::BITCAST, DL, MVT::v16i8,
7811           DAG.getVectorShuffle(MVT::v8i16, DL,
7812                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7813                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7814     };
7815     if (SDValue V = tryToWidenViaDuplication())
7816       return V;
7817   }
7818
7819   // Check whether an interleaving lowering is likely to be more efficient.
7820   // This isn't perfect but it is a strong heuristic that tends to work well on
7821   // the kinds of shuffles that show up in practice.
7822   //
7823   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7824   if (shouldLowerAsInterleaving(Mask)) {
7825     // FIXME: Figure out whether we should pack these into the low or high
7826     // halves.
7827
7828     int EMask[16], OMask[16];
7829     for (int i = 0; i < 8; ++i) {
7830       EMask[i] = Mask[2*i];
7831       OMask[i] = Mask[2*i + 1];
7832       EMask[i + 8] = -1;
7833       OMask[i + 8] = -1;
7834     }
7835
7836     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7837     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7838
7839     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7840   }
7841
7842   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7843   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7844   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7845   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7846
7847   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7848                             MutableArrayRef<int> V1HalfBlendMask,
7849                             MutableArrayRef<int> V2HalfBlendMask) {
7850     for (int i = 0; i < 8; ++i)
7851       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7852         V1HalfBlendMask[i] = HalfMask[i];
7853         HalfMask[i] = i;
7854       } else if (HalfMask[i] >= 16) {
7855         V2HalfBlendMask[i] = HalfMask[i] - 16;
7856         HalfMask[i] = i + 8;
7857       }
7858   };
7859   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7860   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7861
7862   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7863
7864   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7865                              MutableArrayRef<int> HiBlendMask) {
7866     SDValue V1, V2;
7867     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7868     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7869     // i16s.
7870     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7871                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7872         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7873                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7874       // Use a mask to drop the high bytes.
7875       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7876       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7877                        DAG.getConstant(0x00FF, MVT::v8i16));
7878
7879       // This will be a single vector shuffle instead of a blend so nuke V2.
7880       V2 = DAG.getUNDEF(MVT::v8i16);
7881
7882       // Squash the masks to point directly into V1.
7883       for (int &M : LoBlendMask)
7884         if (M >= 0)
7885           M /= 2;
7886       for (int &M : HiBlendMask)
7887         if (M >= 0)
7888           M /= 2;
7889     } else {
7890       // Otherwise just unpack the low half of V into V1 and the high half into
7891       // V2 so that we can blend them as i16s.
7892       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7893                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7894       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7895                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7896     }
7897
7898     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7899     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7900     return std::make_pair(BlendedLo, BlendedHi);
7901   };
7902   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7903   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7904   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7905
7906   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7907   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7908
7909   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7910 }
7911
7912 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7913 ///
7914 /// This routine breaks down the specific type of 128-bit shuffle and
7915 /// dispatches to the lowering routines accordingly.
7916 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7917                                         MVT VT, const X86Subtarget *Subtarget,
7918                                         SelectionDAG &DAG) {
7919   switch (VT.SimpleTy) {
7920   case MVT::v2i64:
7921     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7922   case MVT::v2f64:
7923     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7924   case MVT::v4i32:
7925     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7926   case MVT::v4f32:
7927     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7928   case MVT::v8i16:
7929     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7930   case MVT::v16i8:
7931     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7932
7933   default:
7934     llvm_unreachable("Unimplemented!");
7935   }
7936 }
7937
7938 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7939 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7940   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7941     if (Mask[i] + 1 != Mask[i+1])
7942       return false;
7943
7944   return true;
7945 }
7946
7947 /// \brief Top-level lowering for x86 vector shuffles.
7948 ///
7949 /// This handles decomposition, canonicalization, and lowering of all x86
7950 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7951 /// above in helper routines. The canonicalization attempts to widen shuffles
7952 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7953 /// s.t. only one of the two inputs needs to be tested, etc.
7954 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7955                                   SelectionDAG &DAG) {
7956   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7957   ArrayRef<int> Mask = SVOp->getMask();
7958   SDValue V1 = Op.getOperand(0);
7959   SDValue V2 = Op.getOperand(1);
7960   MVT VT = Op.getSimpleValueType();
7961   int NumElements = VT.getVectorNumElements();
7962   SDLoc dl(Op);
7963
7964   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7965
7966   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7967   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7968   if (V1IsUndef && V2IsUndef)
7969     return DAG.getUNDEF(VT);
7970
7971   // When we create a shuffle node we put the UNDEF node to second operand,
7972   // but in some cases the first operand may be transformed to UNDEF.
7973   // In this case we should just commute the node.
7974   if (V1IsUndef)
7975     return DAG.getCommutedVectorShuffle(*SVOp);
7976
7977   // Check for non-undef masks pointing at an undef vector and make the masks
7978   // undef as well. This makes it easier to match the shuffle based solely on
7979   // the mask.
7980   if (V2IsUndef)
7981     for (int M : Mask)
7982       if (M >= NumElements) {
7983         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7984         for (int &M : NewMask)
7985           if (M >= NumElements)
7986             M = -1;
7987         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7988       }
7989
7990   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7991   // lanes but wider integers. We cap this to not form integers larger than i64
7992   // but it might be interesting to form i128 integers to handle flipping the
7993   // low and high halves of AVX 256-bit vectors.
7994   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7995       areAdjacentMasksSequential(Mask)) {
7996     SmallVector<int, 8> NewMask;
7997     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7998       NewMask.push_back(Mask[i] / 2);
7999     MVT NewVT =
8000         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8001                          VT.getVectorNumElements() / 2);
8002     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8003     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8004     return DAG.getNode(ISD::BITCAST, dl, VT,
8005                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8006   }
8007
8008   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8009   for (int M : SVOp->getMask())
8010     if (M < 0)
8011       ++NumUndefElements;
8012     else if (M < NumElements)
8013       ++NumV1Elements;
8014     else
8015       ++NumV2Elements;
8016
8017   // Commute the shuffle as needed such that more elements come from V1 than
8018   // V2. This allows us to match the shuffle pattern strictly on how many
8019   // elements come from V1 without handling the symmetric cases.
8020   if (NumV2Elements > NumV1Elements)
8021     return DAG.getCommutedVectorShuffle(*SVOp);
8022
8023   // When the number of V1 and V2 elements are the same, try to minimize the
8024   // number of uses of V2 in the low half of the vector.
8025   if (NumV1Elements == NumV2Elements) {
8026     int LowV1Elements = 0, LowV2Elements = 0;
8027     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8028       if (M >= NumElements)
8029         ++LowV2Elements;
8030       else if (M >= 0)
8031         ++LowV1Elements;
8032     if (LowV2Elements > LowV1Elements)
8033       return DAG.getCommutedVectorShuffle(*SVOp);
8034   }
8035
8036   // For each vector width, delegate to a specialized lowering routine.
8037   if (VT.getSizeInBits() == 128)
8038     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8039
8040   llvm_unreachable("Unimplemented!");
8041 }
8042
8043
8044 //===----------------------------------------------------------------------===//
8045 // Legacy vector shuffle lowering
8046 //
8047 // This code is the legacy code handling vector shuffles until the above
8048 // replaces its functionality and performance.
8049 //===----------------------------------------------------------------------===//
8050
8051 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8052                         bool hasInt256, unsigned *MaskOut = nullptr) {
8053   MVT EltVT = VT.getVectorElementType();
8054
8055   // There is no blend with immediate in AVX-512.
8056   if (VT.is512BitVector())
8057     return false;
8058
8059   if (!hasSSE41 || EltVT == MVT::i8)
8060     return false;
8061   if (!hasInt256 && VT == MVT::v16i16)
8062     return false;
8063
8064   unsigned MaskValue = 0;
8065   unsigned NumElems = VT.getVectorNumElements();
8066   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8067   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8068   unsigned NumElemsInLane = NumElems / NumLanes;
8069
8070   // Blend for v16i16 should be symetric for the both lanes.
8071   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8072
8073     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8074     int EltIdx = MaskVals[i];
8075
8076     if ((EltIdx < 0 || EltIdx == (int)i) &&
8077         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8078       continue;
8079
8080     if (((unsigned)EltIdx == (i + NumElems)) &&
8081         (SndLaneEltIdx < 0 ||
8082          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8083       MaskValue |= (1 << i);
8084     else
8085       return false;
8086   }
8087
8088   if (MaskOut)
8089     *MaskOut = MaskValue;
8090   return true;
8091 }
8092
8093 // Try to lower a shuffle node into a simple blend instruction.
8094 // This function assumes isBlendMask returns true for this
8095 // SuffleVectorSDNode
8096 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8097                                           unsigned MaskValue,
8098                                           const X86Subtarget *Subtarget,
8099                                           SelectionDAG &DAG) {
8100   MVT VT = SVOp->getSimpleValueType(0);
8101   MVT EltVT = VT.getVectorElementType();
8102   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8103                      Subtarget->hasInt256() && "Trying to lower a "
8104                                                "VECTOR_SHUFFLE to a Blend but "
8105                                                "with the wrong mask"));
8106   SDValue V1 = SVOp->getOperand(0);
8107   SDValue V2 = SVOp->getOperand(1);
8108   SDLoc dl(SVOp);
8109   unsigned NumElems = VT.getVectorNumElements();
8110
8111   // Convert i32 vectors to floating point if it is not AVX2.
8112   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8113   MVT BlendVT = VT;
8114   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8115     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8116                                NumElems);
8117     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8118     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8119   }
8120
8121   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8122                             DAG.getConstant(MaskValue, MVT::i32));
8123   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8124 }
8125
8126 /// In vector type \p VT, return true if the element at index \p InputIdx
8127 /// falls on a different 128-bit lane than \p OutputIdx.
8128 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8129                                      unsigned OutputIdx) {
8130   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8131   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8132 }
8133
8134 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8135 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8136 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8137 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8138 /// zero.
8139 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8140                          SelectionDAG &DAG) {
8141   MVT VT = V1.getSimpleValueType();
8142   assert(VT.is128BitVector() || VT.is256BitVector());
8143
8144   MVT EltVT = VT.getVectorElementType();
8145   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8146   unsigned NumElts = VT.getVectorNumElements();
8147
8148   SmallVector<SDValue, 32> PshufbMask;
8149   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8150     int InputIdx = MaskVals[OutputIdx];
8151     unsigned InputByteIdx;
8152
8153     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8154       InputByteIdx = 0x80;
8155     else {
8156       // Cross lane is not allowed.
8157       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8158         return SDValue();
8159       InputByteIdx = InputIdx * EltSizeInBytes;
8160       // Index is an byte offset within the 128-bit lane.
8161       InputByteIdx &= 0xf;
8162     }
8163
8164     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8165       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8166       if (InputByteIdx != 0x80)
8167         ++InputByteIdx;
8168     }
8169   }
8170
8171   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8172   if (ShufVT != VT)
8173     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8174   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8175                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8176 }
8177
8178 // v8i16 shuffles - Prefer shuffles in the following order:
8179 // 1. [all]   pshuflw, pshufhw, optional move
8180 // 2. [ssse3] 1 x pshufb
8181 // 3. [ssse3] 2 x pshufb + 1 x por
8182 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8183 static SDValue
8184 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8185                          SelectionDAG &DAG) {
8186   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8187   SDValue V1 = SVOp->getOperand(0);
8188   SDValue V2 = SVOp->getOperand(1);
8189   SDLoc dl(SVOp);
8190   SmallVector<int, 8> MaskVals;
8191
8192   // Determine if more than 1 of the words in each of the low and high quadwords
8193   // of the result come from the same quadword of one of the two inputs.  Undef
8194   // mask values count as coming from any quadword, for better codegen.
8195   //
8196   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8197   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8198   unsigned LoQuad[] = { 0, 0, 0, 0 };
8199   unsigned HiQuad[] = { 0, 0, 0, 0 };
8200   // Indices of quads used.
8201   std::bitset<4> InputQuads;
8202   for (unsigned i = 0; i < 8; ++i) {
8203     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8204     int EltIdx = SVOp->getMaskElt(i);
8205     MaskVals.push_back(EltIdx);
8206     if (EltIdx < 0) {
8207       ++Quad[0];
8208       ++Quad[1];
8209       ++Quad[2];
8210       ++Quad[3];
8211       continue;
8212     }
8213     ++Quad[EltIdx / 4];
8214     InputQuads.set(EltIdx / 4);
8215   }
8216
8217   int BestLoQuad = -1;
8218   unsigned MaxQuad = 1;
8219   for (unsigned i = 0; i < 4; ++i) {
8220     if (LoQuad[i] > MaxQuad) {
8221       BestLoQuad = i;
8222       MaxQuad = LoQuad[i];
8223     }
8224   }
8225
8226   int BestHiQuad = -1;
8227   MaxQuad = 1;
8228   for (unsigned i = 0; i < 4; ++i) {
8229     if (HiQuad[i] > MaxQuad) {
8230       BestHiQuad = i;
8231       MaxQuad = HiQuad[i];
8232     }
8233   }
8234
8235   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8236   // of the two input vectors, shuffle them into one input vector so only a
8237   // single pshufb instruction is necessary. If there are more than 2 input
8238   // quads, disable the next transformation since it does not help SSSE3.
8239   bool V1Used = InputQuads[0] || InputQuads[1];
8240   bool V2Used = InputQuads[2] || InputQuads[3];
8241   if (Subtarget->hasSSSE3()) {
8242     if (InputQuads.count() == 2 && V1Used && V2Used) {
8243       BestLoQuad = InputQuads[0] ? 0 : 1;
8244       BestHiQuad = InputQuads[2] ? 2 : 3;
8245     }
8246     if (InputQuads.count() > 2) {
8247       BestLoQuad = -1;
8248       BestHiQuad = -1;
8249     }
8250   }
8251
8252   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8253   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8254   // words from all 4 input quadwords.
8255   SDValue NewV;
8256   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8257     int MaskV[] = {
8258       BestLoQuad < 0 ? 0 : BestLoQuad,
8259       BestHiQuad < 0 ? 1 : BestHiQuad
8260     };
8261     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8262                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8263                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8264     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8265
8266     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8267     // source words for the shuffle, to aid later transformations.
8268     bool AllWordsInNewV = true;
8269     bool InOrder[2] = { true, true };
8270     for (unsigned i = 0; i != 8; ++i) {
8271       int idx = MaskVals[i];
8272       if (idx != (int)i)
8273         InOrder[i/4] = false;
8274       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8275         continue;
8276       AllWordsInNewV = false;
8277       break;
8278     }
8279
8280     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8281     if (AllWordsInNewV) {
8282       for (int i = 0; i != 8; ++i) {
8283         int idx = MaskVals[i];
8284         if (idx < 0)
8285           continue;
8286         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8287         if ((idx != i) && idx < 4)
8288           pshufhw = false;
8289         if ((idx != i) && idx > 3)
8290           pshuflw = false;
8291       }
8292       V1 = NewV;
8293       V2Used = false;
8294       BestLoQuad = 0;
8295       BestHiQuad = 1;
8296     }
8297
8298     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8299     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8300     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8301       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8302       unsigned TargetMask = 0;
8303       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8304                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8305       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8306       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8307                              getShufflePSHUFLWImmediate(SVOp);
8308       V1 = NewV.getOperand(0);
8309       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8310     }
8311   }
8312
8313   // Promote splats to a larger type which usually leads to more efficient code.
8314   // FIXME: Is this true if pshufb is available?
8315   if (SVOp->isSplat())
8316     return PromoteSplat(SVOp, DAG);
8317
8318   // If we have SSSE3, and all words of the result are from 1 input vector,
8319   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8320   // is present, fall back to case 4.
8321   if (Subtarget->hasSSSE3()) {
8322     SmallVector<SDValue,16> pshufbMask;
8323
8324     // If we have elements from both input vectors, set the high bit of the
8325     // shuffle mask element to zero out elements that come from V2 in the V1
8326     // mask, and elements that come from V1 in the V2 mask, so that the two
8327     // results can be OR'd together.
8328     bool TwoInputs = V1Used && V2Used;
8329     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8330     if (!TwoInputs)
8331       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8332
8333     // Calculate the shuffle mask for the second input, shuffle it, and
8334     // OR it with the first shuffled input.
8335     CommuteVectorShuffleMask(MaskVals, 8);
8336     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8337     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8338     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8339   }
8340
8341   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8342   // and update MaskVals with new element order.
8343   std::bitset<8> InOrder;
8344   if (BestLoQuad >= 0) {
8345     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8346     for (int i = 0; i != 4; ++i) {
8347       int idx = MaskVals[i];
8348       if (idx < 0) {
8349         InOrder.set(i);
8350       } else if ((idx / 4) == BestLoQuad) {
8351         MaskV[i] = idx & 3;
8352         InOrder.set(i);
8353       }
8354     }
8355     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8356                                 &MaskV[0]);
8357
8358     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8359       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8360       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8361                                   NewV.getOperand(0),
8362                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8363     }
8364   }
8365
8366   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8367   // and update MaskVals with the new element order.
8368   if (BestHiQuad >= 0) {
8369     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8370     for (unsigned i = 4; i != 8; ++i) {
8371       int idx = MaskVals[i];
8372       if (idx < 0) {
8373         InOrder.set(i);
8374       } else if ((idx / 4) == BestHiQuad) {
8375         MaskV[i] = (idx & 3) + 4;
8376         InOrder.set(i);
8377       }
8378     }
8379     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8380                                 &MaskV[0]);
8381
8382     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8383       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8384       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8385                                   NewV.getOperand(0),
8386                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8387     }
8388   }
8389
8390   // In case BestHi & BestLo were both -1, which means each quadword has a word
8391   // from each of the four input quadwords, calculate the InOrder bitvector now
8392   // before falling through to the insert/extract cleanup.
8393   if (BestLoQuad == -1 && BestHiQuad == -1) {
8394     NewV = V1;
8395     for (int i = 0; i != 8; ++i)
8396       if (MaskVals[i] < 0 || MaskVals[i] == i)
8397         InOrder.set(i);
8398   }
8399
8400   // The other elements are put in the right place using pextrw and pinsrw.
8401   for (unsigned i = 0; i != 8; ++i) {
8402     if (InOrder[i])
8403       continue;
8404     int EltIdx = MaskVals[i];
8405     if (EltIdx < 0)
8406       continue;
8407     SDValue ExtOp = (EltIdx < 8) ?
8408       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8409                   DAG.getIntPtrConstant(EltIdx)) :
8410       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8411                   DAG.getIntPtrConstant(EltIdx - 8));
8412     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8413                        DAG.getIntPtrConstant(i));
8414   }
8415   return NewV;
8416 }
8417
8418 /// \brief v16i16 shuffles
8419 ///
8420 /// FIXME: We only support generation of a single pshufb currently.  We can
8421 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8422 /// well (e.g 2 x pshufb + 1 x por).
8423 static SDValue
8424 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8426   SDValue V1 = SVOp->getOperand(0);
8427   SDValue V2 = SVOp->getOperand(1);
8428   SDLoc dl(SVOp);
8429
8430   if (V2.getOpcode() != ISD::UNDEF)
8431     return SDValue();
8432
8433   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8434   return getPSHUFB(MaskVals, V1, dl, DAG);
8435 }
8436
8437 // v16i8 shuffles - Prefer shuffles in the following order:
8438 // 1. [ssse3] 1 x pshufb
8439 // 2. [ssse3] 2 x pshufb + 1 x por
8440 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8441 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8442                                         const X86Subtarget* Subtarget,
8443                                         SelectionDAG &DAG) {
8444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8445   SDValue V1 = SVOp->getOperand(0);
8446   SDValue V2 = SVOp->getOperand(1);
8447   SDLoc dl(SVOp);
8448   ArrayRef<int> MaskVals = SVOp->getMask();
8449
8450   // Promote splats to a larger type which usually leads to more efficient code.
8451   // FIXME: Is this true if pshufb is available?
8452   if (SVOp->isSplat())
8453     return PromoteSplat(SVOp, DAG);
8454
8455   // If we have SSSE3, case 1 is generated when all result bytes come from
8456   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8457   // present, fall back to case 3.
8458
8459   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8460   if (Subtarget->hasSSSE3()) {
8461     SmallVector<SDValue,16> pshufbMask;
8462
8463     // If all result elements are from one input vector, then only translate
8464     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8465     //
8466     // Otherwise, we have elements from both input vectors, and must zero out
8467     // elements that come from V2 in the first mask, and V1 in the second mask
8468     // so that we can OR them together.
8469     for (unsigned i = 0; i != 16; ++i) {
8470       int EltIdx = MaskVals[i];
8471       if (EltIdx < 0 || EltIdx >= 16)
8472         EltIdx = 0x80;
8473       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8474     }
8475     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8476                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8477                                  MVT::v16i8, pshufbMask));
8478
8479     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8480     // the 2nd operand if it's undefined or zero.
8481     if (V2.getOpcode() == ISD::UNDEF ||
8482         ISD::isBuildVectorAllZeros(V2.getNode()))
8483       return V1;
8484
8485     // Calculate the shuffle mask for the second input, shuffle it, and
8486     // OR it with the first shuffled input.
8487     pshufbMask.clear();
8488     for (unsigned i = 0; i != 16; ++i) {
8489       int EltIdx = MaskVals[i];
8490       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8491       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8492     }
8493     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8494                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8495                                  MVT::v16i8, pshufbMask));
8496     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8497   }
8498
8499   // No SSSE3 - Calculate in place words and then fix all out of place words
8500   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8501   // the 16 different words that comprise the two doublequadword input vectors.
8502   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8503   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8504   SDValue NewV = V1;
8505   for (int i = 0; i != 8; ++i) {
8506     int Elt0 = MaskVals[i*2];
8507     int Elt1 = MaskVals[i*2+1];
8508
8509     // This word of the result is all undef, skip it.
8510     if (Elt0 < 0 && Elt1 < 0)
8511       continue;
8512
8513     // This word of the result is already in the correct place, skip it.
8514     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8515       continue;
8516
8517     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8518     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8519     SDValue InsElt;
8520
8521     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8522     // using a single extract together, load it and store it.
8523     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8524       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8525                            DAG.getIntPtrConstant(Elt1 / 2));
8526       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8527                         DAG.getIntPtrConstant(i));
8528       continue;
8529     }
8530
8531     // If Elt1 is defined, extract it from the appropriate source.  If the
8532     // source byte is not also odd, shift the extracted word left 8 bits
8533     // otherwise clear the bottom 8 bits if we need to do an or.
8534     if (Elt1 >= 0) {
8535       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8536                            DAG.getIntPtrConstant(Elt1 / 2));
8537       if ((Elt1 & 1) == 0)
8538         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8539                              DAG.getConstant(8,
8540                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8541       else if (Elt0 >= 0)
8542         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8543                              DAG.getConstant(0xFF00, MVT::i16));
8544     }
8545     // If Elt0 is defined, extract it from the appropriate source.  If the
8546     // source byte is not also even, shift the extracted word right 8 bits. If
8547     // Elt1 was also defined, OR the extracted values together before
8548     // inserting them in the result.
8549     if (Elt0 >= 0) {
8550       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8551                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8552       if ((Elt0 & 1) != 0)
8553         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8554                               DAG.getConstant(8,
8555                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8556       else if (Elt1 >= 0)
8557         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8558                              DAG.getConstant(0x00FF, MVT::i16));
8559       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8560                          : InsElt0;
8561     }
8562     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8563                        DAG.getIntPtrConstant(i));
8564   }
8565   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8566 }
8567
8568 // v32i8 shuffles - Translate to VPSHUFB if possible.
8569 static
8570 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8571                                  const X86Subtarget *Subtarget,
8572                                  SelectionDAG &DAG) {
8573   MVT VT = SVOp->getSimpleValueType(0);
8574   SDValue V1 = SVOp->getOperand(0);
8575   SDValue V2 = SVOp->getOperand(1);
8576   SDLoc dl(SVOp);
8577   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8578
8579   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8580   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8581   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8582
8583   // VPSHUFB may be generated if
8584   // (1) one of input vector is undefined or zeroinitializer.
8585   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8586   // And (2) the mask indexes don't cross the 128-bit lane.
8587   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8588       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8589     return SDValue();
8590
8591   if (V1IsAllZero && !V2IsAllZero) {
8592     CommuteVectorShuffleMask(MaskVals, 32);
8593     V1 = V2;
8594   }
8595   return getPSHUFB(MaskVals, V1, dl, DAG);
8596 }
8597
8598 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8599 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8600 /// done when every pair / quad of shuffle mask elements point to elements in
8601 /// the right sequence. e.g.
8602 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8603 static
8604 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8605                                  SelectionDAG &DAG) {
8606   MVT VT = SVOp->getSimpleValueType(0);
8607   SDLoc dl(SVOp);
8608   unsigned NumElems = VT.getVectorNumElements();
8609   MVT NewVT;
8610   unsigned Scale;
8611   switch (VT.SimpleTy) {
8612   default: llvm_unreachable("Unexpected!");
8613   case MVT::v2i64:
8614   case MVT::v2f64:
8615            return SDValue(SVOp, 0);
8616   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8617   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8618   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8619   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8620   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8621   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8622   }
8623
8624   SmallVector<int, 8> MaskVec;
8625   for (unsigned i = 0; i != NumElems; i += Scale) {
8626     int StartIdx = -1;
8627     for (unsigned j = 0; j != Scale; ++j) {
8628       int EltIdx = SVOp->getMaskElt(i+j);
8629       if (EltIdx < 0)
8630         continue;
8631       if (StartIdx < 0)
8632         StartIdx = (EltIdx / Scale);
8633       if (EltIdx != (int)(StartIdx*Scale + j))
8634         return SDValue();
8635     }
8636     MaskVec.push_back(StartIdx);
8637   }
8638
8639   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8640   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8641   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8642 }
8643
8644 /// getVZextMovL - Return a zero-extending vector move low node.
8645 ///
8646 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8647                             SDValue SrcOp, SelectionDAG &DAG,
8648                             const X86Subtarget *Subtarget, SDLoc dl) {
8649   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8650     LoadSDNode *LD = nullptr;
8651     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8652       LD = dyn_cast<LoadSDNode>(SrcOp);
8653     if (!LD) {
8654       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8655       // instead.
8656       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8657       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8658           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8659           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8660           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8661         // PR2108
8662         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8663         return DAG.getNode(ISD::BITCAST, dl, VT,
8664                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8665                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8666                                                    OpVT,
8667                                                    SrcOp.getOperand(0)
8668                                                           .getOperand(0))));
8669       }
8670     }
8671   }
8672
8673   return DAG.getNode(ISD::BITCAST, dl, VT,
8674                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8675                                  DAG.getNode(ISD::BITCAST, dl,
8676                                              OpVT, SrcOp)));
8677 }
8678
8679 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8680 /// which could not be matched by any known target speficic shuffle
8681 static SDValue
8682 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8683
8684   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8685   if (NewOp.getNode())
8686     return NewOp;
8687
8688   MVT VT = SVOp->getSimpleValueType(0);
8689
8690   unsigned NumElems = VT.getVectorNumElements();
8691   unsigned NumLaneElems = NumElems / 2;
8692
8693   SDLoc dl(SVOp);
8694   MVT EltVT = VT.getVectorElementType();
8695   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8696   SDValue Output[2];
8697
8698   SmallVector<int, 16> Mask;
8699   for (unsigned l = 0; l < 2; ++l) {
8700     // Build a shuffle mask for the output, discovering on the fly which
8701     // input vectors to use as shuffle operands (recorded in InputUsed).
8702     // If building a suitable shuffle vector proves too hard, then bail
8703     // out with UseBuildVector set.
8704     bool UseBuildVector = false;
8705     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8706     unsigned LaneStart = l * NumLaneElems;
8707     for (unsigned i = 0; i != NumLaneElems; ++i) {
8708       // The mask element.  This indexes into the input.
8709       int Idx = SVOp->getMaskElt(i+LaneStart);
8710       if (Idx < 0) {
8711         // the mask element does not index into any input vector.
8712         Mask.push_back(-1);
8713         continue;
8714       }
8715
8716       // The input vector this mask element indexes into.
8717       int Input = Idx / NumLaneElems;
8718
8719       // Turn the index into an offset from the start of the input vector.
8720       Idx -= Input * NumLaneElems;
8721
8722       // Find or create a shuffle vector operand to hold this input.
8723       unsigned OpNo;
8724       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8725         if (InputUsed[OpNo] == Input)
8726           // This input vector is already an operand.
8727           break;
8728         if (InputUsed[OpNo] < 0) {
8729           // Create a new operand for this input vector.
8730           InputUsed[OpNo] = Input;
8731           break;
8732         }
8733       }
8734
8735       if (OpNo >= array_lengthof(InputUsed)) {
8736         // More than two input vectors used!  Give up on trying to create a
8737         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8738         UseBuildVector = true;
8739         break;
8740       }
8741
8742       // Add the mask index for the new shuffle vector.
8743       Mask.push_back(Idx + OpNo * NumLaneElems);
8744     }
8745
8746     if (UseBuildVector) {
8747       SmallVector<SDValue, 16> SVOps;
8748       for (unsigned i = 0; i != NumLaneElems; ++i) {
8749         // The mask element.  This indexes into the input.
8750         int Idx = SVOp->getMaskElt(i+LaneStart);
8751         if (Idx < 0) {
8752           SVOps.push_back(DAG.getUNDEF(EltVT));
8753           continue;
8754         }
8755
8756         // The input vector this mask element indexes into.
8757         int Input = Idx / NumElems;
8758
8759         // Turn the index into an offset from the start of the input vector.
8760         Idx -= Input * NumElems;
8761
8762         // Extract the vector element by hand.
8763         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8764                                     SVOp->getOperand(Input),
8765                                     DAG.getIntPtrConstant(Idx)));
8766       }
8767
8768       // Construct the output using a BUILD_VECTOR.
8769       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8770     } else if (InputUsed[0] < 0) {
8771       // No input vectors were used! The result is undefined.
8772       Output[l] = DAG.getUNDEF(NVT);
8773     } else {
8774       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8775                                         (InputUsed[0] % 2) * NumLaneElems,
8776                                         DAG, dl);
8777       // If only one input was used, use an undefined vector for the other.
8778       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8779         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8780                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8781       // At least one input vector was used. Create a new shuffle vector.
8782       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8783     }
8784
8785     Mask.clear();
8786   }
8787
8788   // Concatenate the result back
8789   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8790 }
8791
8792 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8793 /// 4 elements, and match them with several different shuffle types.
8794 static SDValue
8795 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8796   SDValue V1 = SVOp->getOperand(0);
8797   SDValue V2 = SVOp->getOperand(1);
8798   SDLoc dl(SVOp);
8799   MVT VT = SVOp->getSimpleValueType(0);
8800
8801   assert(VT.is128BitVector() && "Unsupported vector size");
8802
8803   std::pair<int, int> Locs[4];
8804   int Mask1[] = { -1, -1, -1, -1 };
8805   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8806
8807   unsigned NumHi = 0;
8808   unsigned NumLo = 0;
8809   for (unsigned i = 0; i != 4; ++i) {
8810     int Idx = PermMask[i];
8811     if (Idx < 0) {
8812       Locs[i] = std::make_pair(-1, -1);
8813     } else {
8814       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8815       if (Idx < 4) {
8816         Locs[i] = std::make_pair(0, NumLo);
8817         Mask1[NumLo] = Idx;
8818         NumLo++;
8819       } else {
8820         Locs[i] = std::make_pair(1, NumHi);
8821         if (2+NumHi < 4)
8822           Mask1[2+NumHi] = Idx;
8823         NumHi++;
8824       }
8825     }
8826   }
8827
8828   if (NumLo <= 2 && NumHi <= 2) {
8829     // If no more than two elements come from either vector. This can be
8830     // implemented with two shuffles. First shuffle gather the elements.
8831     // The second shuffle, which takes the first shuffle as both of its
8832     // vector operands, put the elements into the right order.
8833     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8834
8835     int Mask2[] = { -1, -1, -1, -1 };
8836
8837     for (unsigned i = 0; i != 4; ++i)
8838       if (Locs[i].first != -1) {
8839         unsigned Idx = (i < 2) ? 0 : 4;
8840         Idx += Locs[i].first * 2 + Locs[i].second;
8841         Mask2[i] = Idx;
8842       }
8843
8844     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8845   }
8846
8847   if (NumLo == 3 || NumHi == 3) {
8848     // Otherwise, we must have three elements from one vector, call it X, and
8849     // one element from the other, call it Y.  First, use a shufps to build an
8850     // intermediate vector with the one element from Y and the element from X
8851     // that will be in the same half in the final destination (the indexes don't
8852     // matter). Then, use a shufps to build the final vector, taking the half
8853     // containing the element from Y from the intermediate, and the other half
8854     // from X.
8855     if (NumHi == 3) {
8856       // Normalize it so the 3 elements come from V1.
8857       CommuteVectorShuffleMask(PermMask, 4);
8858       std::swap(V1, V2);
8859     }
8860
8861     // Find the element from V2.
8862     unsigned HiIndex;
8863     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8864       int Val = PermMask[HiIndex];
8865       if (Val < 0)
8866         continue;
8867       if (Val >= 4)
8868         break;
8869     }
8870
8871     Mask1[0] = PermMask[HiIndex];
8872     Mask1[1] = -1;
8873     Mask1[2] = PermMask[HiIndex^1];
8874     Mask1[3] = -1;
8875     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8876
8877     if (HiIndex >= 2) {
8878       Mask1[0] = PermMask[0];
8879       Mask1[1] = PermMask[1];
8880       Mask1[2] = HiIndex & 1 ? 6 : 4;
8881       Mask1[3] = HiIndex & 1 ? 4 : 6;
8882       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8883     }
8884
8885     Mask1[0] = HiIndex & 1 ? 2 : 0;
8886     Mask1[1] = HiIndex & 1 ? 0 : 2;
8887     Mask1[2] = PermMask[2];
8888     Mask1[3] = PermMask[3];
8889     if (Mask1[2] >= 0)
8890       Mask1[2] += 4;
8891     if (Mask1[3] >= 0)
8892       Mask1[3] += 4;
8893     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8894   }
8895
8896   // Break it into (shuffle shuffle_hi, shuffle_lo).
8897   int LoMask[] = { -1, -1, -1, -1 };
8898   int HiMask[] = { -1, -1, -1, -1 };
8899
8900   int *MaskPtr = LoMask;
8901   unsigned MaskIdx = 0;
8902   unsigned LoIdx = 0;
8903   unsigned HiIdx = 2;
8904   for (unsigned i = 0; i != 4; ++i) {
8905     if (i == 2) {
8906       MaskPtr = HiMask;
8907       MaskIdx = 1;
8908       LoIdx = 0;
8909       HiIdx = 2;
8910     }
8911     int Idx = PermMask[i];
8912     if (Idx < 0) {
8913       Locs[i] = std::make_pair(-1, -1);
8914     } else if (Idx < 4) {
8915       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8916       MaskPtr[LoIdx] = Idx;
8917       LoIdx++;
8918     } else {
8919       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8920       MaskPtr[HiIdx] = Idx;
8921       HiIdx++;
8922     }
8923   }
8924
8925   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8926   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8927   int MaskOps[] = { -1, -1, -1, -1 };
8928   for (unsigned i = 0; i != 4; ++i)
8929     if (Locs[i].first != -1)
8930       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8931   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8932 }
8933
8934 static bool MayFoldVectorLoad(SDValue V) {
8935   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8936     V = V.getOperand(0);
8937
8938   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8939     V = V.getOperand(0);
8940   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8941       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8942     // BUILD_VECTOR (load), undef
8943     V = V.getOperand(0);
8944
8945   return MayFoldLoad(V);
8946 }
8947
8948 static
8949 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8950   MVT VT = Op.getSimpleValueType();
8951
8952   // Canonizalize to v2f64.
8953   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8954   return DAG.getNode(ISD::BITCAST, dl, VT,
8955                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8956                                           V1, DAG));
8957 }
8958
8959 static
8960 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8961                         bool HasSSE2) {
8962   SDValue V1 = Op.getOperand(0);
8963   SDValue V2 = Op.getOperand(1);
8964   MVT VT = Op.getSimpleValueType();
8965
8966   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8967
8968   if (HasSSE2 && VT == MVT::v2f64)
8969     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8970
8971   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8972   return DAG.getNode(ISD::BITCAST, dl, VT,
8973                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8974                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8975                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8976 }
8977
8978 static
8979 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8980   SDValue V1 = Op.getOperand(0);
8981   SDValue V2 = Op.getOperand(1);
8982   MVT VT = Op.getSimpleValueType();
8983
8984   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8985          "unsupported shuffle type");
8986
8987   if (V2.getOpcode() == ISD::UNDEF)
8988     V2 = V1;
8989
8990   // v4i32 or v4f32
8991   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8992 }
8993
8994 static
8995 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8996   SDValue V1 = Op.getOperand(0);
8997   SDValue V2 = Op.getOperand(1);
8998   MVT VT = Op.getSimpleValueType();
8999   unsigned NumElems = VT.getVectorNumElements();
9000
9001   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9002   // operand of these instructions is only memory, so check if there's a
9003   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9004   // same masks.
9005   bool CanFoldLoad = false;
9006
9007   // Trivial case, when V2 comes from a load.
9008   if (MayFoldVectorLoad(V2))
9009     CanFoldLoad = true;
9010
9011   // When V1 is a load, it can be folded later into a store in isel, example:
9012   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9013   //    turns into:
9014   //  (MOVLPSmr addr:$src1, VR128:$src2)
9015   // So, recognize this potential and also use MOVLPS or MOVLPD
9016   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9017     CanFoldLoad = true;
9018
9019   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9020   if (CanFoldLoad) {
9021     if (HasSSE2 && NumElems == 2)
9022       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9023
9024     if (NumElems == 4)
9025       // If we don't care about the second element, proceed to use movss.
9026       if (SVOp->getMaskElt(1) != -1)
9027         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9028   }
9029
9030   // movl and movlp will both match v2i64, but v2i64 is never matched by
9031   // movl earlier because we make it strict to avoid messing with the movlp load
9032   // folding logic (see the code above getMOVLP call). Match it here then,
9033   // this is horrible, but will stay like this until we move all shuffle
9034   // matching to x86 specific nodes. Note that for the 1st condition all
9035   // types are matched with movsd.
9036   if (HasSSE2) {
9037     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9038     // as to remove this logic from here, as much as possible
9039     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9040       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9041     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9042   }
9043
9044   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9045
9046   // Invert the operand order and use SHUFPS to match it.
9047   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9048                               getShuffleSHUFImmediate(SVOp), DAG);
9049 }
9050
9051 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9052                                          SelectionDAG &DAG) {
9053   SDLoc dl(Load);
9054   MVT VT = Load->getSimpleValueType(0);
9055   MVT EVT = VT.getVectorElementType();
9056   SDValue Addr = Load->getOperand(1);
9057   SDValue NewAddr = DAG.getNode(
9058       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9059       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9060
9061   SDValue NewLoad =
9062       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9063                   DAG.getMachineFunction().getMachineMemOperand(
9064                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9065   return NewLoad;
9066 }
9067
9068 // It is only safe to call this function if isINSERTPSMask is true for
9069 // this shufflevector mask.
9070 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9071                            SelectionDAG &DAG) {
9072   // Generate an insertps instruction when inserting an f32 from memory onto a
9073   // v4f32 or when copying a member from one v4f32 to another.
9074   // We also use it for transferring i32 from one register to another,
9075   // since it simply copies the same bits.
9076   // If we're transferring an i32 from memory to a specific element in a
9077   // register, we output a generic DAG that will match the PINSRD
9078   // instruction.
9079   MVT VT = SVOp->getSimpleValueType(0);
9080   MVT EVT = VT.getVectorElementType();
9081   SDValue V1 = SVOp->getOperand(0);
9082   SDValue V2 = SVOp->getOperand(1);
9083   auto Mask = SVOp->getMask();
9084   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9085          "unsupported vector type for insertps/pinsrd");
9086
9087   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9088   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9089   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9090
9091   SDValue From;
9092   SDValue To;
9093   unsigned DestIndex;
9094   if (FromV1 == 1) {
9095     From = V1;
9096     To = V2;
9097     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9098                 Mask.begin();
9099
9100     // If we have 1 element from each vector, we have to check if we're
9101     // changing V1's element's place. If so, we're done. Otherwise, we
9102     // should assume we're changing V2's element's place and behave
9103     // accordingly.
9104     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9105     assert(DestIndex <= INT32_MAX && "truncated destination index");
9106     if (FromV1 == FromV2 &&
9107         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9108       From = V2;
9109       To = V1;
9110       DestIndex =
9111           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9112     }
9113   } else {
9114     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9115            "More than one element from V1 and from V2, or no elements from one "
9116            "of the vectors. This case should not have returned true from "
9117            "isINSERTPSMask");
9118     From = V2;
9119     To = V1;
9120     DestIndex =
9121         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9122   }
9123
9124   // Get an index into the source vector in the range [0,4) (the mask is
9125   // in the range [0,8) because it can address V1 and V2)
9126   unsigned SrcIndex = Mask[DestIndex] % 4;
9127   if (MayFoldLoad(From)) {
9128     // Trivial case, when From comes from a load and is only used by the
9129     // shuffle. Make it use insertps from the vector that we need from that
9130     // load.
9131     SDValue NewLoad =
9132         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9133     if (!NewLoad.getNode())
9134       return SDValue();
9135
9136     if (EVT == MVT::f32) {
9137       // Create this as a scalar to vector to match the instruction pattern.
9138       SDValue LoadScalarToVector =
9139           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9140       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9141       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9142                          InsertpsMask);
9143     } else { // EVT == MVT::i32
9144       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9145       // instruction, to match the PINSRD instruction, which loads an i32 to a
9146       // certain vector element.
9147       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9148                          DAG.getConstant(DestIndex, MVT::i32));
9149     }
9150   }
9151
9152   // Vector-element-to-vector
9153   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9154   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9155 }
9156
9157 // Reduce a vector shuffle to zext.
9158 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9159                                     SelectionDAG &DAG) {
9160   // PMOVZX is only available from SSE41.
9161   if (!Subtarget->hasSSE41())
9162     return SDValue();
9163
9164   MVT VT = Op.getSimpleValueType();
9165
9166   // Only AVX2 support 256-bit vector integer extending.
9167   if (!Subtarget->hasInt256() && VT.is256BitVector())
9168     return SDValue();
9169
9170   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9171   SDLoc DL(Op);
9172   SDValue V1 = Op.getOperand(0);
9173   SDValue V2 = Op.getOperand(1);
9174   unsigned NumElems = VT.getVectorNumElements();
9175
9176   // Extending is an unary operation and the element type of the source vector
9177   // won't be equal to or larger than i64.
9178   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9179       VT.getVectorElementType() == MVT::i64)
9180     return SDValue();
9181
9182   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9183   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9184   while ((1U << Shift) < NumElems) {
9185     if (SVOp->getMaskElt(1U << Shift) == 1)
9186       break;
9187     Shift += 1;
9188     // The maximal ratio is 8, i.e. from i8 to i64.
9189     if (Shift > 3)
9190       return SDValue();
9191   }
9192
9193   // Check the shuffle mask.
9194   unsigned Mask = (1U << Shift) - 1;
9195   for (unsigned i = 0; i != NumElems; ++i) {
9196     int EltIdx = SVOp->getMaskElt(i);
9197     if ((i & Mask) != 0 && EltIdx != -1)
9198       return SDValue();
9199     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9200       return SDValue();
9201   }
9202
9203   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9204   MVT NeVT = MVT::getIntegerVT(NBits);
9205   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9206
9207   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9208     return SDValue();
9209
9210   // Simplify the operand as it's prepared to be fed into shuffle.
9211   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9212   if (V1.getOpcode() == ISD::BITCAST &&
9213       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9214       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9215       V1.getOperand(0).getOperand(0)
9216         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9217     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9218     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9219     ConstantSDNode *CIdx =
9220       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9221     // If it's foldable, i.e. normal load with single use, we will let code
9222     // selection to fold it. Otherwise, we will short the conversion sequence.
9223     if (CIdx && CIdx->getZExtValue() == 0 &&
9224         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9225       MVT FullVT = V.getSimpleValueType();
9226       MVT V1VT = V1.getSimpleValueType();
9227       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9228         // The "ext_vec_elt" node is wider than the result node.
9229         // In this case we should extract subvector from V.
9230         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9231         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9232         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9233                                         FullVT.getVectorNumElements()/Ratio);
9234         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9235                         DAG.getIntPtrConstant(0));
9236       }
9237       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9238     }
9239   }
9240
9241   return DAG.getNode(ISD::BITCAST, DL, VT,
9242                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9243 }
9244
9245 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9246                                       SelectionDAG &DAG) {
9247   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9248   MVT VT = Op.getSimpleValueType();
9249   SDLoc dl(Op);
9250   SDValue V1 = Op.getOperand(0);
9251   SDValue V2 = Op.getOperand(1);
9252
9253   if (isZeroShuffle(SVOp))
9254     return getZeroVector(VT, Subtarget, DAG, dl);
9255
9256   // Handle splat operations
9257   if (SVOp->isSplat()) {
9258     // Use vbroadcast whenever the splat comes from a foldable load
9259     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9260     if (Broadcast.getNode())
9261       return Broadcast;
9262   }
9263
9264   // Check integer expanding shuffles.
9265   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9266   if (NewOp.getNode())
9267     return NewOp;
9268
9269   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9270   // do it!
9271   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9272       VT == MVT::v32i8) {
9273     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9274     if (NewOp.getNode())
9275       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9276   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9277     // FIXME: Figure out a cleaner way to do this.
9278     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9279       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9280       if (NewOp.getNode()) {
9281         MVT NewVT = NewOp.getSimpleValueType();
9282         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9283                                NewVT, true, false))
9284           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9285                               dl);
9286       }
9287     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9288       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9289       if (NewOp.getNode()) {
9290         MVT NewVT = NewOp.getSimpleValueType();
9291         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9292           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9293                               dl);
9294       }
9295     }
9296   }
9297   return SDValue();
9298 }
9299
9300 SDValue
9301 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9302   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9303   SDValue V1 = Op.getOperand(0);
9304   SDValue V2 = Op.getOperand(1);
9305   MVT VT = Op.getSimpleValueType();
9306   SDLoc dl(Op);
9307   unsigned NumElems = VT.getVectorNumElements();
9308   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9309   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9310   bool V1IsSplat = false;
9311   bool V2IsSplat = false;
9312   bool HasSSE2 = Subtarget->hasSSE2();
9313   bool HasFp256    = Subtarget->hasFp256();
9314   bool HasInt256   = Subtarget->hasInt256();
9315   MachineFunction &MF = DAG.getMachineFunction();
9316   bool OptForSize = MF.getFunction()->getAttributes().
9317     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9318
9319   // Check if we should use the experimental vector shuffle lowering. If so,
9320   // delegate completely to that code path.
9321   if (ExperimentalVectorShuffleLowering)
9322     return lowerVectorShuffle(Op, Subtarget, DAG);
9323
9324   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9325
9326   if (V1IsUndef && V2IsUndef)
9327     return DAG.getUNDEF(VT);
9328
9329   // When we create a shuffle node we put the UNDEF node to second operand,
9330   // but in some cases the first operand may be transformed to UNDEF.
9331   // In this case we should just commute the node.
9332   if (V1IsUndef)
9333     return DAG.getCommutedVectorShuffle(*SVOp);
9334
9335   // Vector shuffle lowering takes 3 steps:
9336   //
9337   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9338   //    narrowing and commutation of operands should be handled.
9339   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9340   //    shuffle nodes.
9341   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9342   //    so the shuffle can be broken into other shuffles and the legalizer can
9343   //    try the lowering again.
9344   //
9345   // The general idea is that no vector_shuffle operation should be left to
9346   // be matched during isel, all of them must be converted to a target specific
9347   // node here.
9348
9349   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9350   // narrowing and commutation of operands should be handled. The actual code
9351   // doesn't include all of those, work in progress...
9352   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9353   if (NewOp.getNode())
9354     return NewOp;
9355
9356   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9357
9358   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9359   // unpckh_undef). Only use pshufd if speed is more important than size.
9360   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9361     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9362   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9363     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9364
9365   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9366       V2IsUndef && MayFoldVectorLoad(V1))
9367     return getMOVDDup(Op, dl, V1, DAG);
9368
9369   if (isMOVHLPS_v_undef_Mask(M, VT))
9370     return getMOVHighToLow(Op, dl, DAG);
9371
9372   // Use to match splats
9373   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9374       (VT == MVT::v2f64 || VT == MVT::v2i64))
9375     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9376
9377   if (isPSHUFDMask(M, VT)) {
9378     // The actual implementation will match the mask in the if above and then
9379     // during isel it can match several different instructions, not only pshufd
9380     // as its name says, sad but true, emulate the behavior for now...
9381     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9382       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9383
9384     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9385
9386     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9387       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9388
9389     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9390       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9391                                   DAG);
9392
9393     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9394                                 TargetMask, DAG);
9395   }
9396
9397   if (isPALIGNRMask(M, VT, Subtarget))
9398     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9399                                 getShufflePALIGNRImmediate(SVOp),
9400                                 DAG);
9401
9402   // Check if this can be converted into a logical shift.
9403   bool isLeft = false;
9404   unsigned ShAmt = 0;
9405   SDValue ShVal;
9406   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9407   if (isShift && ShVal.hasOneUse()) {
9408     // If the shifted value has multiple uses, it may be cheaper to use
9409     // v_set0 + movlhps or movhlps, etc.
9410     MVT EltVT = VT.getVectorElementType();
9411     ShAmt *= EltVT.getSizeInBits();
9412     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9413   }
9414
9415   if (isMOVLMask(M, VT)) {
9416     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9417       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9418     if (!isMOVLPMask(M, VT)) {
9419       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9420         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9421
9422       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9423         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9424     }
9425   }
9426
9427   // FIXME: fold these into legal mask.
9428   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9429     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9430
9431   if (isMOVHLPSMask(M, VT))
9432     return getMOVHighToLow(Op, dl, DAG);
9433
9434   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9435     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9436
9437   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9438     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9439
9440   if (isMOVLPMask(M, VT))
9441     return getMOVLP(Op, dl, DAG, HasSSE2);
9442
9443   if (ShouldXformToMOVHLPS(M, VT) ||
9444       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9445     return DAG.getCommutedVectorShuffle(*SVOp);
9446
9447   if (isShift) {
9448     // No better options. Use a vshldq / vsrldq.
9449     MVT EltVT = VT.getVectorElementType();
9450     ShAmt *= EltVT.getSizeInBits();
9451     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9452   }
9453
9454   bool Commuted = false;
9455   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9456   // 1,1,1,1 -> v8i16 though.
9457   BitVector UndefElements;
9458   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9459     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9460       V1IsSplat = true;
9461   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9462     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9463       V2IsSplat = true;
9464
9465   // Canonicalize the splat or undef, if present, to be on the RHS.
9466   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9467     CommuteVectorShuffleMask(M, NumElems);
9468     std::swap(V1, V2);
9469     std::swap(V1IsSplat, V2IsSplat);
9470     Commuted = true;
9471   }
9472
9473   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9474     // Shuffling low element of v1 into undef, just return v1.
9475     if (V2IsUndef)
9476       return V1;
9477     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9478     // the instruction selector will not match, so get a canonical MOVL with
9479     // swapped operands to undo the commute.
9480     return getMOVL(DAG, dl, VT, V2, V1);
9481   }
9482
9483   if (isUNPCKLMask(M, VT, HasInt256))
9484     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9485
9486   if (isUNPCKHMask(M, VT, HasInt256))
9487     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9488
9489   if (V2IsSplat) {
9490     // Normalize mask so all entries that point to V2 points to its first
9491     // element then try to match unpck{h|l} again. If match, return a
9492     // new vector_shuffle with the corrected mask.p
9493     SmallVector<int, 8> NewMask(M.begin(), M.end());
9494     NormalizeMask(NewMask, NumElems);
9495     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9496       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9497     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9498       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9499   }
9500
9501   if (Commuted) {
9502     // Commute is back and try unpck* again.
9503     // FIXME: this seems wrong.
9504     CommuteVectorShuffleMask(M, NumElems);
9505     std::swap(V1, V2);
9506     std::swap(V1IsSplat, V2IsSplat);
9507
9508     if (isUNPCKLMask(M, VT, HasInt256))
9509       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9510
9511     if (isUNPCKHMask(M, VT, HasInt256))
9512       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9513   }
9514
9515   // Normalize the node to match x86 shuffle ops if needed
9516   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9517     return DAG.getCommutedVectorShuffle(*SVOp);
9518
9519   // The checks below are all present in isShuffleMaskLegal, but they are
9520   // inlined here right now to enable us to directly emit target specific
9521   // nodes, and remove one by one until they don't return Op anymore.
9522
9523   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9524       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9525     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9526       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9527   }
9528
9529   if (isPSHUFHWMask(M, VT, HasInt256))
9530     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9531                                 getShufflePSHUFHWImmediate(SVOp),
9532                                 DAG);
9533
9534   if (isPSHUFLWMask(M, VT, HasInt256))
9535     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9536                                 getShufflePSHUFLWImmediate(SVOp),
9537                                 DAG);
9538
9539   unsigned MaskValue;
9540   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9541                   &MaskValue))
9542     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9543
9544   if (isSHUFPMask(M, VT))
9545     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9546                                 getShuffleSHUFImmediate(SVOp), DAG);
9547
9548   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9549     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9550   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9551     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9552
9553   //===--------------------------------------------------------------------===//
9554   // Generate target specific nodes for 128 or 256-bit shuffles only
9555   // supported in the AVX instruction set.
9556   //
9557
9558   // Handle VMOVDDUPY permutations
9559   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9560     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9561
9562   // Handle VPERMILPS/D* permutations
9563   if (isVPERMILPMask(M, VT)) {
9564     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9565       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9566                                   getShuffleSHUFImmediate(SVOp), DAG);
9567     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9568                                 getShuffleSHUFImmediate(SVOp), DAG);
9569   }
9570
9571   unsigned Idx;
9572   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9573     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9574                               Idx*(NumElems/2), DAG, dl);
9575
9576   // Handle VPERM2F128/VPERM2I128 permutations
9577   if (isVPERM2X128Mask(M, VT, HasFp256))
9578     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9579                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9580
9581   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9582     return getINSERTPS(SVOp, dl, DAG);
9583
9584   unsigned Imm8;
9585   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9586     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9587
9588   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9589       VT.is512BitVector()) {
9590     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9591     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9592     SmallVector<SDValue, 16> permclMask;
9593     for (unsigned i = 0; i != NumElems; ++i) {
9594       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9595     }
9596
9597     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9598     if (V2IsUndef)
9599       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9600       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9601                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9602     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9603                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9604   }
9605
9606   //===--------------------------------------------------------------------===//
9607   // Since no target specific shuffle was selected for this generic one,
9608   // lower it into other known shuffles. FIXME: this isn't true yet, but
9609   // this is the plan.
9610   //
9611
9612   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9613   if (VT == MVT::v8i16) {
9614     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9615     if (NewOp.getNode())
9616       return NewOp;
9617   }
9618
9619   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9620     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9621     if (NewOp.getNode())
9622       return NewOp;
9623   }
9624
9625   if (VT == MVT::v16i8) {
9626     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9627     if (NewOp.getNode())
9628       return NewOp;
9629   }
9630
9631   if (VT == MVT::v32i8) {
9632     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9633     if (NewOp.getNode())
9634       return NewOp;
9635   }
9636
9637   // Handle all 128-bit wide vectors with 4 elements, and match them with
9638   // several different shuffle types.
9639   if (NumElems == 4 && VT.is128BitVector())
9640     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9641
9642   // Handle general 256-bit shuffles
9643   if (VT.is256BitVector())
9644     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9645
9646   return SDValue();
9647 }
9648
9649 // This function assumes its argument is a BUILD_VECTOR of constants or
9650 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9651 // true.
9652 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9653                                     unsigned &MaskValue) {
9654   MaskValue = 0;
9655   unsigned NumElems = BuildVector->getNumOperands();
9656   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9657   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9658   unsigned NumElemsInLane = NumElems / NumLanes;
9659
9660   // Blend for v16i16 should be symetric for the both lanes.
9661   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9662     SDValue EltCond = BuildVector->getOperand(i);
9663     SDValue SndLaneEltCond =
9664         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9665
9666     int Lane1Cond = -1, Lane2Cond = -1;
9667     if (isa<ConstantSDNode>(EltCond))
9668       Lane1Cond = !isZero(EltCond);
9669     if (isa<ConstantSDNode>(SndLaneEltCond))
9670       Lane2Cond = !isZero(SndLaneEltCond);
9671
9672     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9673       // Lane1Cond != 0, means we want the first argument.
9674       // Lane1Cond == 0, means we want the second argument.
9675       // The encoding of this argument is 0 for the first argument, 1
9676       // for the second. Therefore, invert the condition.
9677       MaskValue |= !Lane1Cond << i;
9678     else if (Lane1Cond < 0)
9679       MaskValue |= !Lane2Cond << i;
9680     else
9681       return false;
9682   }
9683   return true;
9684 }
9685
9686 // Try to lower a vselect node into a simple blend instruction.
9687 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9688                                    SelectionDAG &DAG) {
9689   SDValue Cond = Op.getOperand(0);
9690   SDValue LHS = Op.getOperand(1);
9691   SDValue RHS = Op.getOperand(2);
9692   SDLoc dl(Op);
9693   MVT VT = Op.getSimpleValueType();
9694   MVT EltVT = VT.getVectorElementType();
9695   unsigned NumElems = VT.getVectorNumElements();
9696
9697   // There is no blend with immediate in AVX-512.
9698   if (VT.is512BitVector())
9699     return SDValue();
9700
9701   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9702     return SDValue();
9703   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9704     return SDValue();
9705
9706   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9707     return SDValue();
9708
9709   // Check the mask for BLEND and build the value.
9710   unsigned MaskValue = 0;
9711   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9712     return SDValue();
9713
9714   // Convert i32 vectors to floating point if it is not AVX2.
9715   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9716   MVT BlendVT = VT;
9717   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9718     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9719                                NumElems);
9720     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9721     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9722   }
9723
9724   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9725                             DAG.getConstant(MaskValue, MVT::i32));
9726   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9727 }
9728
9729 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9730   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9731   if (BlendOp.getNode())
9732     return BlendOp;
9733
9734   // Some types for vselect were previously set to Expand, not Legal or
9735   // Custom. Return an empty SDValue so we fall-through to Expand, after
9736   // the Custom lowering phase.
9737   MVT VT = Op.getSimpleValueType();
9738   switch (VT.SimpleTy) {
9739   default:
9740     break;
9741   case MVT::v8i16:
9742   case MVT::v16i16:
9743     return SDValue();
9744   }
9745
9746   // We couldn't create a "Blend with immediate" node.
9747   // This node should still be legal, but we'll have to emit a blendv*
9748   // instruction.
9749   return Op;
9750 }
9751
9752 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9753   MVT VT = Op.getSimpleValueType();
9754   SDLoc dl(Op);
9755
9756   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9757     return SDValue();
9758
9759   if (VT.getSizeInBits() == 8) {
9760     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9761                                   Op.getOperand(0), Op.getOperand(1));
9762     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9763                                   DAG.getValueType(VT));
9764     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9765   }
9766
9767   if (VT.getSizeInBits() == 16) {
9768     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9769     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9770     if (Idx == 0)
9771       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9772                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9773                                      DAG.getNode(ISD::BITCAST, dl,
9774                                                  MVT::v4i32,
9775                                                  Op.getOperand(0)),
9776                                      Op.getOperand(1)));
9777     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9778                                   Op.getOperand(0), Op.getOperand(1));
9779     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9780                                   DAG.getValueType(VT));
9781     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9782   }
9783
9784   if (VT == MVT::f32) {
9785     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9786     // the result back to FR32 register. It's only worth matching if the
9787     // result has a single use which is a store or a bitcast to i32.  And in
9788     // the case of a store, it's not worth it if the index is a constant 0,
9789     // because a MOVSSmr can be used instead, which is smaller and faster.
9790     if (!Op.hasOneUse())
9791       return SDValue();
9792     SDNode *User = *Op.getNode()->use_begin();
9793     if ((User->getOpcode() != ISD::STORE ||
9794          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9795           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9796         (User->getOpcode() != ISD::BITCAST ||
9797          User->getValueType(0) != MVT::i32))
9798       return SDValue();
9799     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9800                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9801                                               Op.getOperand(0)),
9802                                               Op.getOperand(1));
9803     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9804   }
9805
9806   if (VT == MVT::i32 || VT == MVT::i64) {
9807     // ExtractPS/pextrq works with constant index.
9808     if (isa<ConstantSDNode>(Op.getOperand(1)))
9809       return Op;
9810   }
9811   return SDValue();
9812 }
9813
9814 /// Extract one bit from mask vector, like v16i1 or v8i1.
9815 /// AVX-512 feature.
9816 SDValue
9817 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9818   SDValue Vec = Op.getOperand(0);
9819   SDLoc dl(Vec);
9820   MVT VecVT = Vec.getSimpleValueType();
9821   SDValue Idx = Op.getOperand(1);
9822   MVT EltVT = Op.getSimpleValueType();
9823
9824   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9825
9826   // variable index can't be handled in mask registers,
9827   // extend vector to VR512
9828   if (!isa<ConstantSDNode>(Idx)) {
9829     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9830     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9831     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9832                               ExtVT.getVectorElementType(), Ext, Idx);
9833     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9834   }
9835
9836   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9837   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9838   unsigned MaxSift = rc->getSize()*8 - 1;
9839   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9840                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9841   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9842                     DAG.getConstant(MaxSift, MVT::i8));
9843   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9844                        DAG.getIntPtrConstant(0));
9845 }
9846
9847 SDValue
9848 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9849                                            SelectionDAG &DAG) const {
9850   SDLoc dl(Op);
9851   SDValue Vec = Op.getOperand(0);
9852   MVT VecVT = Vec.getSimpleValueType();
9853   SDValue Idx = Op.getOperand(1);
9854
9855   if (Op.getSimpleValueType() == MVT::i1)
9856     return ExtractBitFromMaskVector(Op, DAG);
9857
9858   if (!isa<ConstantSDNode>(Idx)) {
9859     if (VecVT.is512BitVector() ||
9860         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9861          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9862
9863       MVT MaskEltVT =
9864         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9865       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9866                                     MaskEltVT.getSizeInBits());
9867
9868       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9869       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9870                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9871                                 Idx, DAG.getConstant(0, getPointerTy()));
9872       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9873       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9874                         Perm, DAG.getConstant(0, getPointerTy()));
9875     }
9876     return SDValue();
9877   }
9878
9879   // If this is a 256-bit vector result, first extract the 128-bit vector and
9880   // then extract the element from the 128-bit vector.
9881   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9882
9883     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9884     // Get the 128-bit vector.
9885     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9886     MVT EltVT = VecVT.getVectorElementType();
9887
9888     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9889
9890     //if (IdxVal >= NumElems/2)
9891     //  IdxVal -= NumElems/2;
9892     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9893     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9894                        DAG.getConstant(IdxVal, MVT::i32));
9895   }
9896
9897   assert(VecVT.is128BitVector() && "Unexpected vector length");
9898
9899   if (Subtarget->hasSSE41()) {
9900     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9901     if (Res.getNode())
9902       return Res;
9903   }
9904
9905   MVT VT = Op.getSimpleValueType();
9906   // TODO: handle v16i8.
9907   if (VT.getSizeInBits() == 16) {
9908     SDValue Vec = Op.getOperand(0);
9909     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9910     if (Idx == 0)
9911       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9912                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9913                                      DAG.getNode(ISD::BITCAST, dl,
9914                                                  MVT::v4i32, Vec),
9915                                      Op.getOperand(1)));
9916     // Transform it so it match pextrw which produces a 32-bit result.
9917     MVT EltVT = MVT::i32;
9918     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9919                                   Op.getOperand(0), Op.getOperand(1));
9920     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9921                                   DAG.getValueType(VT));
9922     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9923   }
9924
9925   if (VT.getSizeInBits() == 32) {
9926     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9927     if (Idx == 0)
9928       return Op;
9929
9930     // SHUFPS the element to the lowest double word, then movss.
9931     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9932     MVT VVT = Op.getOperand(0).getSimpleValueType();
9933     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9934                                        DAG.getUNDEF(VVT), Mask);
9935     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9936                        DAG.getIntPtrConstant(0));
9937   }
9938
9939   if (VT.getSizeInBits() == 64) {
9940     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9941     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9942     //        to match extract_elt for f64.
9943     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9944     if (Idx == 0)
9945       return Op;
9946
9947     // UNPCKHPD the element to the lowest double word, then movsd.
9948     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9949     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9950     int Mask[2] = { 1, -1 };
9951     MVT VVT = Op.getOperand(0).getSimpleValueType();
9952     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9953                                        DAG.getUNDEF(VVT), Mask);
9954     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9955                        DAG.getIntPtrConstant(0));
9956   }
9957
9958   return SDValue();
9959 }
9960
9961 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9962   MVT VT = Op.getSimpleValueType();
9963   MVT EltVT = VT.getVectorElementType();
9964   SDLoc dl(Op);
9965
9966   SDValue N0 = Op.getOperand(0);
9967   SDValue N1 = Op.getOperand(1);
9968   SDValue N2 = Op.getOperand(2);
9969
9970   if (!VT.is128BitVector())
9971     return SDValue();
9972
9973   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9974       isa<ConstantSDNode>(N2)) {
9975     unsigned Opc;
9976     if (VT == MVT::v8i16)
9977       Opc = X86ISD::PINSRW;
9978     else if (VT == MVT::v16i8)
9979       Opc = X86ISD::PINSRB;
9980     else
9981       Opc = X86ISD::PINSRB;
9982
9983     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9984     // argument.
9985     if (N1.getValueType() != MVT::i32)
9986       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9987     if (N2.getValueType() != MVT::i32)
9988       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9989     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9990   }
9991
9992   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9993     // Bits [7:6] of the constant are the source select.  This will always be
9994     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9995     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9996     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9997     // Bits [5:4] of the constant are the destination select.  This is the
9998     //  value of the incoming immediate.
9999     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10000     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10001     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10002     // Create this as a scalar to vector..
10003     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10004     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10005   }
10006
10007   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10008     // PINSR* works with constant index.
10009     return Op;
10010   }
10011   return SDValue();
10012 }
10013
10014 /// Insert one bit to mask vector, like v16i1 or v8i1.
10015 /// AVX-512 feature.
10016 SDValue 
10017 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10018   SDLoc dl(Op);
10019   SDValue Vec = Op.getOperand(0);
10020   SDValue Elt = Op.getOperand(1);
10021   SDValue Idx = Op.getOperand(2);
10022   MVT VecVT = Vec.getSimpleValueType();
10023
10024   if (!isa<ConstantSDNode>(Idx)) {
10025     // Non constant index. Extend source and destination,
10026     // insert element and then truncate the result.
10027     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10028     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10029     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10030       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10031       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10032     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10033   }
10034
10035   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10036   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10037   if (Vec.getOpcode() == ISD::UNDEF)
10038     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10039                        DAG.getConstant(IdxVal, MVT::i8));
10040   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10041   unsigned MaxSift = rc->getSize()*8 - 1;
10042   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10043                     DAG.getConstant(MaxSift, MVT::i8));
10044   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10045                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10046   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10047 }
10048 SDValue
10049 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10050   MVT VT = Op.getSimpleValueType();
10051   MVT EltVT = VT.getVectorElementType();
10052   
10053   if (EltVT == MVT::i1)
10054     return InsertBitToMaskVector(Op, DAG);
10055
10056   SDLoc dl(Op);
10057   SDValue N0 = Op.getOperand(0);
10058   SDValue N1 = Op.getOperand(1);
10059   SDValue N2 = Op.getOperand(2);
10060
10061   // If this is a 256-bit vector result, first extract the 128-bit vector,
10062   // insert the element into the extracted half and then place it back.
10063   if (VT.is256BitVector() || VT.is512BitVector()) {
10064     if (!isa<ConstantSDNode>(N2))
10065       return SDValue();
10066
10067     // Get the desired 128-bit vector half.
10068     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10069     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10070
10071     // Insert the element into the desired half.
10072     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10073     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10074
10075     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10076                     DAG.getConstant(IdxIn128, MVT::i32));
10077
10078     // Insert the changed part back to the 256-bit vector
10079     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10080   }
10081
10082   if (Subtarget->hasSSE41())
10083     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10084
10085   if (EltVT == MVT::i8)
10086     return SDValue();
10087
10088   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10089     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10090     // as its second argument.
10091     if (N1.getValueType() != MVT::i32)
10092       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10093     if (N2.getValueType() != MVT::i32)
10094       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10095     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10096   }
10097   return SDValue();
10098 }
10099
10100 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10101   SDLoc dl(Op);
10102   MVT OpVT = Op.getSimpleValueType();
10103
10104   // If this is a 256-bit vector result, first insert into a 128-bit
10105   // vector and then insert into the 256-bit vector.
10106   if (!OpVT.is128BitVector()) {
10107     // Insert into a 128-bit vector.
10108     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10109     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10110                                  OpVT.getVectorNumElements() / SizeFactor);
10111
10112     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10113
10114     // Insert the 128-bit vector.
10115     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10116   }
10117
10118   if (OpVT == MVT::v1i64 &&
10119       Op.getOperand(0).getValueType() == MVT::i64)
10120     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10121
10122   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10123   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10124   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10125                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10126 }
10127
10128 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10129 // a simple subregister reference or explicit instructions to grab
10130 // upper bits of a vector.
10131 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10132                                       SelectionDAG &DAG) {
10133   SDLoc dl(Op);
10134   SDValue In =  Op.getOperand(0);
10135   SDValue Idx = Op.getOperand(1);
10136   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10137   MVT ResVT   = Op.getSimpleValueType();
10138   MVT InVT    = In.getSimpleValueType();
10139
10140   if (Subtarget->hasFp256()) {
10141     if (ResVT.is128BitVector() &&
10142         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10143         isa<ConstantSDNode>(Idx)) {
10144       return Extract128BitVector(In, IdxVal, DAG, dl);
10145     }
10146     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10147         isa<ConstantSDNode>(Idx)) {
10148       return Extract256BitVector(In, IdxVal, DAG, dl);
10149     }
10150   }
10151   return SDValue();
10152 }
10153
10154 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10155 // simple superregister reference or explicit instructions to insert
10156 // the upper bits of a vector.
10157 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10158                                      SelectionDAG &DAG) {
10159   if (Subtarget->hasFp256()) {
10160     SDLoc dl(Op.getNode());
10161     SDValue Vec = Op.getNode()->getOperand(0);
10162     SDValue SubVec = Op.getNode()->getOperand(1);
10163     SDValue Idx = Op.getNode()->getOperand(2);
10164
10165     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10166          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10167         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10168         isa<ConstantSDNode>(Idx)) {
10169       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10170       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10171     }
10172
10173     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10174         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10175         isa<ConstantSDNode>(Idx)) {
10176       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10177       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10178     }
10179   }
10180   return SDValue();
10181 }
10182
10183 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10184 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10185 // one of the above mentioned nodes. It has to be wrapped because otherwise
10186 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10187 // be used to form addressing mode. These wrapped nodes will be selected
10188 // into MOV32ri.
10189 SDValue
10190 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10191   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10192
10193   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10194   // global base reg.
10195   unsigned char OpFlag = 0;
10196   unsigned WrapperKind = X86ISD::Wrapper;
10197   CodeModel::Model M = DAG.getTarget().getCodeModel();
10198
10199   if (Subtarget->isPICStyleRIPRel() &&
10200       (M == CodeModel::Small || M == CodeModel::Kernel))
10201     WrapperKind = X86ISD::WrapperRIP;
10202   else if (Subtarget->isPICStyleGOT())
10203     OpFlag = X86II::MO_GOTOFF;
10204   else if (Subtarget->isPICStyleStubPIC())
10205     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10206
10207   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10208                                              CP->getAlignment(),
10209                                              CP->getOffset(), OpFlag);
10210   SDLoc DL(CP);
10211   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10212   // With PIC, the address is actually $g + Offset.
10213   if (OpFlag) {
10214     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10215                          DAG.getNode(X86ISD::GlobalBaseReg,
10216                                      SDLoc(), getPointerTy()),
10217                          Result);
10218   }
10219
10220   return Result;
10221 }
10222
10223 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10224   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10225
10226   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10227   // global base reg.
10228   unsigned char OpFlag = 0;
10229   unsigned WrapperKind = X86ISD::Wrapper;
10230   CodeModel::Model M = DAG.getTarget().getCodeModel();
10231
10232   if (Subtarget->isPICStyleRIPRel() &&
10233       (M == CodeModel::Small || M == CodeModel::Kernel))
10234     WrapperKind = X86ISD::WrapperRIP;
10235   else if (Subtarget->isPICStyleGOT())
10236     OpFlag = X86II::MO_GOTOFF;
10237   else if (Subtarget->isPICStyleStubPIC())
10238     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10239
10240   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10241                                           OpFlag);
10242   SDLoc DL(JT);
10243   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10244
10245   // With PIC, the address is actually $g + Offset.
10246   if (OpFlag)
10247     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10248                          DAG.getNode(X86ISD::GlobalBaseReg,
10249                                      SDLoc(), getPointerTy()),
10250                          Result);
10251
10252   return Result;
10253 }
10254
10255 SDValue
10256 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10257   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10258
10259   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10260   // global base reg.
10261   unsigned char OpFlag = 0;
10262   unsigned WrapperKind = X86ISD::Wrapper;
10263   CodeModel::Model M = DAG.getTarget().getCodeModel();
10264
10265   if (Subtarget->isPICStyleRIPRel() &&
10266       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10267     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10268       OpFlag = X86II::MO_GOTPCREL;
10269     WrapperKind = X86ISD::WrapperRIP;
10270   } else if (Subtarget->isPICStyleGOT()) {
10271     OpFlag = X86II::MO_GOT;
10272   } else if (Subtarget->isPICStyleStubPIC()) {
10273     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10274   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10275     OpFlag = X86II::MO_DARWIN_NONLAZY;
10276   }
10277
10278   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10279
10280   SDLoc DL(Op);
10281   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10282
10283   // With PIC, the address is actually $g + Offset.
10284   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10285       !Subtarget->is64Bit()) {
10286     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10287                          DAG.getNode(X86ISD::GlobalBaseReg,
10288                                      SDLoc(), getPointerTy()),
10289                          Result);
10290   }
10291
10292   // For symbols that require a load from a stub to get the address, emit the
10293   // load.
10294   if (isGlobalStubReference(OpFlag))
10295     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10296                          MachinePointerInfo::getGOT(), false, false, false, 0);
10297
10298   return Result;
10299 }
10300
10301 SDValue
10302 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10303   // Create the TargetBlockAddressAddress node.
10304   unsigned char OpFlags =
10305     Subtarget->ClassifyBlockAddressReference();
10306   CodeModel::Model M = DAG.getTarget().getCodeModel();
10307   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10308   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10309   SDLoc dl(Op);
10310   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10311                                              OpFlags);
10312
10313   if (Subtarget->isPICStyleRIPRel() &&
10314       (M == CodeModel::Small || M == CodeModel::Kernel))
10315     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10316   else
10317     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10318
10319   // With PIC, the address is actually $g + Offset.
10320   if (isGlobalRelativeToPICBase(OpFlags)) {
10321     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10322                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10323                          Result);
10324   }
10325
10326   return Result;
10327 }
10328
10329 SDValue
10330 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10331                                       int64_t Offset, SelectionDAG &DAG) const {
10332   // Create the TargetGlobalAddress node, folding in the constant
10333   // offset if it is legal.
10334   unsigned char OpFlags =
10335       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10336   CodeModel::Model M = DAG.getTarget().getCodeModel();
10337   SDValue Result;
10338   if (OpFlags == X86II::MO_NO_FLAG &&
10339       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10340     // A direct static reference to a global.
10341     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10342     Offset = 0;
10343   } else {
10344     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10345   }
10346
10347   if (Subtarget->isPICStyleRIPRel() &&
10348       (M == CodeModel::Small || M == CodeModel::Kernel))
10349     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10350   else
10351     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10352
10353   // With PIC, the address is actually $g + Offset.
10354   if (isGlobalRelativeToPICBase(OpFlags)) {
10355     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10356                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10357                          Result);
10358   }
10359
10360   // For globals that require a load from a stub to get the address, emit the
10361   // load.
10362   if (isGlobalStubReference(OpFlags))
10363     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10364                          MachinePointerInfo::getGOT(), false, false, false, 0);
10365
10366   // If there was a non-zero offset that we didn't fold, create an explicit
10367   // addition for it.
10368   if (Offset != 0)
10369     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10370                          DAG.getConstant(Offset, getPointerTy()));
10371
10372   return Result;
10373 }
10374
10375 SDValue
10376 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10377   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10378   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10379   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10380 }
10381
10382 static SDValue
10383 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10384            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10385            unsigned char OperandFlags, bool LocalDynamic = false) {
10386   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10387   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10388   SDLoc dl(GA);
10389   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10390                                            GA->getValueType(0),
10391                                            GA->getOffset(),
10392                                            OperandFlags);
10393
10394   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10395                                            : X86ISD::TLSADDR;
10396
10397   if (InFlag) {
10398     SDValue Ops[] = { Chain,  TGA, *InFlag };
10399     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10400   } else {
10401     SDValue Ops[]  = { Chain, TGA };
10402     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10403   }
10404
10405   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10406   MFI->setAdjustsStack(true);
10407
10408   SDValue Flag = Chain.getValue(1);
10409   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10410 }
10411
10412 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10413 static SDValue
10414 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10415                                 const EVT PtrVT) {
10416   SDValue InFlag;
10417   SDLoc dl(GA);  // ? function entry point might be better
10418   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10419                                    DAG.getNode(X86ISD::GlobalBaseReg,
10420                                                SDLoc(), PtrVT), InFlag);
10421   InFlag = Chain.getValue(1);
10422
10423   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10424 }
10425
10426 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10427 static SDValue
10428 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10429                                 const EVT PtrVT) {
10430   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10431                     X86::RAX, X86II::MO_TLSGD);
10432 }
10433
10434 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10435                                            SelectionDAG &DAG,
10436                                            const EVT PtrVT,
10437                                            bool is64Bit) {
10438   SDLoc dl(GA);
10439
10440   // Get the start address of the TLS block for this module.
10441   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10442       .getInfo<X86MachineFunctionInfo>();
10443   MFI->incNumLocalDynamicTLSAccesses();
10444
10445   SDValue Base;
10446   if (is64Bit) {
10447     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10448                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10449   } else {
10450     SDValue InFlag;
10451     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10452         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10453     InFlag = Chain.getValue(1);
10454     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10455                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10456   }
10457
10458   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10459   // of Base.
10460
10461   // Build x@dtpoff.
10462   unsigned char OperandFlags = X86II::MO_DTPOFF;
10463   unsigned WrapperKind = X86ISD::Wrapper;
10464   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10465                                            GA->getValueType(0),
10466                                            GA->getOffset(), OperandFlags);
10467   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10468
10469   // Add x@dtpoff with the base.
10470   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10471 }
10472
10473 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10474 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10475                                    const EVT PtrVT, TLSModel::Model model,
10476                                    bool is64Bit, bool isPIC) {
10477   SDLoc dl(GA);
10478
10479   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10480   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10481                                                          is64Bit ? 257 : 256));
10482
10483   SDValue ThreadPointer =
10484       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10485                   MachinePointerInfo(Ptr), false, false, false, 0);
10486
10487   unsigned char OperandFlags = 0;
10488   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10489   // initialexec.
10490   unsigned WrapperKind = X86ISD::Wrapper;
10491   if (model == TLSModel::LocalExec) {
10492     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10493   } else if (model == TLSModel::InitialExec) {
10494     if (is64Bit) {
10495       OperandFlags = X86II::MO_GOTTPOFF;
10496       WrapperKind = X86ISD::WrapperRIP;
10497     } else {
10498       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10499     }
10500   } else {
10501     llvm_unreachable("Unexpected model");
10502   }
10503
10504   // emit "addl x@ntpoff,%eax" (local exec)
10505   // or "addl x@indntpoff,%eax" (initial exec)
10506   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10507   SDValue TGA =
10508       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10509                                  GA->getOffset(), OperandFlags);
10510   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10511
10512   if (model == TLSModel::InitialExec) {
10513     if (isPIC && !is64Bit) {
10514       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10515                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10516                            Offset);
10517     }
10518
10519     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10520                          MachinePointerInfo::getGOT(), false, false, false, 0);
10521   }
10522
10523   // The address of the thread local variable is the add of the thread
10524   // pointer with the offset of the variable.
10525   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10526 }
10527
10528 SDValue
10529 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10530
10531   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10532   const GlobalValue *GV = GA->getGlobal();
10533
10534   if (Subtarget->isTargetELF()) {
10535     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10536
10537     switch (model) {
10538       case TLSModel::GeneralDynamic:
10539         if (Subtarget->is64Bit())
10540           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10541         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10542       case TLSModel::LocalDynamic:
10543         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10544                                            Subtarget->is64Bit());
10545       case TLSModel::InitialExec:
10546       case TLSModel::LocalExec:
10547         return LowerToTLSExecModel(
10548             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10549             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10550     }
10551     llvm_unreachable("Unknown TLS model.");
10552   }
10553
10554   if (Subtarget->isTargetDarwin()) {
10555     // Darwin only has one model of TLS.  Lower to that.
10556     unsigned char OpFlag = 0;
10557     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10558                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10559
10560     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10561     // global base reg.
10562     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10563                  !Subtarget->is64Bit();
10564     if (PIC32)
10565       OpFlag = X86II::MO_TLVP_PIC_BASE;
10566     else
10567       OpFlag = X86II::MO_TLVP;
10568     SDLoc DL(Op);
10569     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10570                                                 GA->getValueType(0),
10571                                                 GA->getOffset(), OpFlag);
10572     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10573
10574     // With PIC32, the address is actually $g + Offset.
10575     if (PIC32)
10576       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10577                            DAG.getNode(X86ISD::GlobalBaseReg,
10578                                        SDLoc(), getPointerTy()),
10579                            Offset);
10580
10581     // Lowering the machine isd will make sure everything is in the right
10582     // location.
10583     SDValue Chain = DAG.getEntryNode();
10584     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10585     SDValue Args[] = { Chain, Offset };
10586     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10587
10588     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10589     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10590     MFI->setAdjustsStack(true);
10591
10592     // And our return value (tls address) is in the standard call return value
10593     // location.
10594     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10595     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10596                               Chain.getValue(1));
10597   }
10598
10599   if (Subtarget->isTargetKnownWindowsMSVC() ||
10600       Subtarget->isTargetWindowsGNU()) {
10601     // Just use the implicit TLS architecture
10602     // Need to generate someting similar to:
10603     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10604     //                                  ; from TEB
10605     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10606     //   mov     rcx, qword [rdx+rcx*8]
10607     //   mov     eax, .tls$:tlsvar
10608     //   [rax+rcx] contains the address
10609     // Windows 64bit: gs:0x58
10610     // Windows 32bit: fs:__tls_array
10611
10612     SDLoc dl(GA);
10613     SDValue Chain = DAG.getEntryNode();
10614
10615     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10616     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10617     // use its literal value of 0x2C.
10618     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10619                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10620                                                              256)
10621                                         : Type::getInt32PtrTy(*DAG.getContext(),
10622                                                               257));
10623
10624     SDValue TlsArray =
10625         Subtarget->is64Bit()
10626             ? DAG.getIntPtrConstant(0x58)
10627             : (Subtarget->isTargetWindowsGNU()
10628                    ? DAG.getIntPtrConstant(0x2C)
10629                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10630
10631     SDValue ThreadPointer =
10632         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10633                     MachinePointerInfo(Ptr), false, false, false, 0);
10634
10635     // Load the _tls_index variable
10636     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10637     if (Subtarget->is64Bit())
10638       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10639                            IDX, MachinePointerInfo(), MVT::i32,
10640                            false, false, 0);
10641     else
10642       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10643                         false, false, false, 0);
10644
10645     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10646                                     getPointerTy());
10647     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10648
10649     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10650     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10651                       false, false, false, 0);
10652
10653     // Get the offset of start of .tls section
10654     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10655                                              GA->getValueType(0),
10656                                              GA->getOffset(), X86II::MO_SECREL);
10657     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10658
10659     // The address of the thread local variable is the add of the thread
10660     // pointer with the offset of the variable.
10661     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10662   }
10663
10664   llvm_unreachable("TLS not implemented for this target.");
10665 }
10666
10667 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10668 /// and take a 2 x i32 value to shift plus a shift amount.
10669 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10670   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10671   MVT VT = Op.getSimpleValueType();
10672   unsigned VTBits = VT.getSizeInBits();
10673   SDLoc dl(Op);
10674   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10675   SDValue ShOpLo = Op.getOperand(0);
10676   SDValue ShOpHi = Op.getOperand(1);
10677   SDValue ShAmt  = Op.getOperand(2);
10678   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10679   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10680   // during isel.
10681   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10682                                   DAG.getConstant(VTBits - 1, MVT::i8));
10683   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10684                                      DAG.getConstant(VTBits - 1, MVT::i8))
10685                        : DAG.getConstant(0, VT);
10686
10687   SDValue Tmp2, Tmp3;
10688   if (Op.getOpcode() == ISD::SHL_PARTS) {
10689     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10690     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10691   } else {
10692     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10693     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10694   }
10695
10696   // If the shift amount is larger or equal than the width of a part we can't
10697   // rely on the results of shld/shrd. Insert a test and select the appropriate
10698   // values for large shift amounts.
10699   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10700                                 DAG.getConstant(VTBits, MVT::i8));
10701   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10702                              AndNode, DAG.getConstant(0, MVT::i8));
10703
10704   SDValue Hi, Lo;
10705   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10706   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10707   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10708
10709   if (Op.getOpcode() == ISD::SHL_PARTS) {
10710     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10711     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10712   } else {
10713     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10714     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10715   }
10716
10717   SDValue Ops[2] = { Lo, Hi };
10718   return DAG.getMergeValues(Ops, dl);
10719 }
10720
10721 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10722                                            SelectionDAG &DAG) const {
10723   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10724
10725   if (SrcVT.isVector())
10726     return SDValue();
10727
10728   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10729          "Unknown SINT_TO_FP to lower!");
10730
10731   // These are really Legal; return the operand so the caller accepts it as
10732   // Legal.
10733   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10734     return Op;
10735   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10736       Subtarget->is64Bit()) {
10737     return Op;
10738   }
10739
10740   SDLoc dl(Op);
10741   unsigned Size = SrcVT.getSizeInBits()/8;
10742   MachineFunction &MF = DAG.getMachineFunction();
10743   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10744   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10745   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10746                                StackSlot,
10747                                MachinePointerInfo::getFixedStack(SSFI),
10748                                false, false, 0);
10749   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10750 }
10751
10752 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10753                                      SDValue StackSlot,
10754                                      SelectionDAG &DAG) const {
10755   // Build the FILD
10756   SDLoc DL(Op);
10757   SDVTList Tys;
10758   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10759   if (useSSE)
10760     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10761   else
10762     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10763
10764   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10765
10766   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10767   MachineMemOperand *MMO;
10768   if (FI) {
10769     int SSFI = FI->getIndex();
10770     MMO =
10771       DAG.getMachineFunction()
10772       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10773                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10774   } else {
10775     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10776     StackSlot = StackSlot.getOperand(1);
10777   }
10778   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10779   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10780                                            X86ISD::FILD, DL,
10781                                            Tys, Ops, SrcVT, MMO);
10782
10783   if (useSSE) {
10784     Chain = Result.getValue(1);
10785     SDValue InFlag = Result.getValue(2);
10786
10787     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10788     // shouldn't be necessary except that RFP cannot be live across
10789     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10790     MachineFunction &MF = DAG.getMachineFunction();
10791     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10792     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10793     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10794     Tys = DAG.getVTList(MVT::Other);
10795     SDValue Ops[] = {
10796       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10797     };
10798     MachineMemOperand *MMO =
10799       DAG.getMachineFunction()
10800       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10801                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10802
10803     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10804                                     Ops, Op.getValueType(), MMO);
10805     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10806                          MachinePointerInfo::getFixedStack(SSFI),
10807                          false, false, false, 0);
10808   }
10809
10810   return Result;
10811 }
10812
10813 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10814 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10815                                                SelectionDAG &DAG) const {
10816   // This algorithm is not obvious. Here it is what we're trying to output:
10817   /*
10818      movq       %rax,  %xmm0
10819      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10820      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10821      #ifdef __SSE3__
10822        haddpd   %xmm0, %xmm0
10823      #else
10824        pshufd   $0x4e, %xmm0, %xmm1
10825        addpd    %xmm1, %xmm0
10826      #endif
10827   */
10828
10829   SDLoc dl(Op);
10830   LLVMContext *Context = DAG.getContext();
10831
10832   // Build some magic constants.
10833   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10834   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10835   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10836
10837   SmallVector<Constant*,2> CV1;
10838   CV1.push_back(
10839     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10840                                       APInt(64, 0x4330000000000000ULL))));
10841   CV1.push_back(
10842     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10843                                       APInt(64, 0x4530000000000000ULL))));
10844   Constant *C1 = ConstantVector::get(CV1);
10845   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10846
10847   // Load the 64-bit value into an XMM register.
10848   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10849                             Op.getOperand(0));
10850   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10851                               MachinePointerInfo::getConstantPool(),
10852                               false, false, false, 16);
10853   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10854                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10855                               CLod0);
10856
10857   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10858                               MachinePointerInfo::getConstantPool(),
10859                               false, false, false, 16);
10860   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10861   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10862   SDValue Result;
10863
10864   if (Subtarget->hasSSE3()) {
10865     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10866     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10867   } else {
10868     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10869     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10870                                            S2F, 0x4E, DAG);
10871     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10872                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10873                          Sub);
10874   }
10875
10876   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10877                      DAG.getIntPtrConstant(0));
10878 }
10879
10880 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10881 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10882                                                SelectionDAG &DAG) const {
10883   SDLoc dl(Op);
10884   // FP constant to bias correct the final result.
10885   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10886                                    MVT::f64);
10887
10888   // Load the 32-bit value into an XMM register.
10889   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10890                              Op.getOperand(0));
10891
10892   // Zero out the upper parts of the register.
10893   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10894
10895   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10896                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10897                      DAG.getIntPtrConstant(0));
10898
10899   // Or the load with the bias.
10900   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10901                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10902                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10903                                                    MVT::v2f64, Load)),
10904                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10905                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10906                                                    MVT::v2f64, Bias)));
10907   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10908                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10909                    DAG.getIntPtrConstant(0));
10910
10911   // Subtract the bias.
10912   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10913
10914   // Handle final rounding.
10915   EVT DestVT = Op.getValueType();
10916
10917   if (DestVT.bitsLT(MVT::f64))
10918     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10919                        DAG.getIntPtrConstant(0));
10920   if (DestVT.bitsGT(MVT::f64))
10921     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10922
10923   // Handle final rounding.
10924   return Sub;
10925 }
10926
10927 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10928                                                SelectionDAG &DAG) const {
10929   SDValue N0 = Op.getOperand(0);
10930   MVT SVT = N0.getSimpleValueType();
10931   SDLoc dl(Op);
10932
10933   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10934           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10935          "Custom UINT_TO_FP is not supported!");
10936
10937   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10938   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10939                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10940 }
10941
10942 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10943                                            SelectionDAG &DAG) const {
10944   SDValue N0 = Op.getOperand(0);
10945   SDLoc dl(Op);
10946
10947   if (Op.getValueType().isVector())
10948     return lowerUINT_TO_FP_vec(Op, DAG);
10949
10950   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10951   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10952   // the optimization here.
10953   if (DAG.SignBitIsZero(N0))
10954     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10955
10956   MVT SrcVT = N0.getSimpleValueType();
10957   MVT DstVT = Op.getSimpleValueType();
10958   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10959     return LowerUINT_TO_FP_i64(Op, DAG);
10960   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10961     return LowerUINT_TO_FP_i32(Op, DAG);
10962   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10963     return SDValue();
10964
10965   // Make a 64-bit buffer, and use it to build an FILD.
10966   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10967   if (SrcVT == MVT::i32) {
10968     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10969     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10970                                      getPointerTy(), StackSlot, WordOff);
10971     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10972                                   StackSlot, MachinePointerInfo(),
10973                                   false, false, 0);
10974     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10975                                   OffsetSlot, MachinePointerInfo(),
10976                                   false, false, 0);
10977     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10978     return Fild;
10979   }
10980
10981   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10982   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10983                                StackSlot, MachinePointerInfo(),
10984                                false, false, 0);
10985   // For i64 source, we need to add the appropriate power of 2 if the input
10986   // was negative.  This is the same as the optimization in
10987   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10988   // we must be careful to do the computation in x87 extended precision, not
10989   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10990   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10991   MachineMemOperand *MMO =
10992     DAG.getMachineFunction()
10993     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10994                           MachineMemOperand::MOLoad, 8, 8);
10995
10996   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10997   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10998   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10999                                          MVT::i64, MMO);
11000
11001   APInt FF(32, 0x5F800000ULL);
11002
11003   // Check whether the sign bit is set.
11004   SDValue SignSet = DAG.getSetCC(dl,
11005                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11006                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11007                                  ISD::SETLT);
11008
11009   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11010   SDValue FudgePtr = DAG.getConstantPool(
11011                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11012                                          getPointerTy());
11013
11014   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11015   SDValue Zero = DAG.getIntPtrConstant(0);
11016   SDValue Four = DAG.getIntPtrConstant(4);
11017   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11018                                Zero, Four);
11019   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11020
11021   // Load the value out, extending it from f32 to f80.
11022   // FIXME: Avoid the extend by constructing the right constant pool?
11023   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11024                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11025                                  MVT::f32, false, false, 4);
11026   // Extend everything to 80 bits to force it to be done on x87.
11027   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11028   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11029 }
11030
11031 std::pair<SDValue,SDValue>
11032 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11033                                     bool IsSigned, bool IsReplace) const {
11034   SDLoc DL(Op);
11035
11036   EVT DstTy = Op.getValueType();
11037
11038   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11039     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11040     DstTy = MVT::i64;
11041   }
11042
11043   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11044          DstTy.getSimpleVT() >= MVT::i16 &&
11045          "Unknown FP_TO_INT to lower!");
11046
11047   // These are really Legal.
11048   if (DstTy == MVT::i32 &&
11049       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11050     return std::make_pair(SDValue(), SDValue());
11051   if (Subtarget->is64Bit() &&
11052       DstTy == MVT::i64 &&
11053       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11054     return std::make_pair(SDValue(), SDValue());
11055
11056   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11057   // stack slot, or into the FTOL runtime function.
11058   MachineFunction &MF = DAG.getMachineFunction();
11059   unsigned MemSize = DstTy.getSizeInBits()/8;
11060   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11061   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11062
11063   unsigned Opc;
11064   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11065     Opc = X86ISD::WIN_FTOL;
11066   else
11067     switch (DstTy.getSimpleVT().SimpleTy) {
11068     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11069     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11070     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11071     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11072     }
11073
11074   SDValue Chain = DAG.getEntryNode();
11075   SDValue Value = Op.getOperand(0);
11076   EVT TheVT = Op.getOperand(0).getValueType();
11077   // FIXME This causes a redundant load/store if the SSE-class value is already
11078   // in memory, such as if it is on the callstack.
11079   if (isScalarFPTypeInSSEReg(TheVT)) {
11080     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11081     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11082                          MachinePointerInfo::getFixedStack(SSFI),
11083                          false, false, 0);
11084     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11085     SDValue Ops[] = {
11086       Chain, StackSlot, DAG.getValueType(TheVT)
11087     };
11088
11089     MachineMemOperand *MMO =
11090       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11091                               MachineMemOperand::MOLoad, MemSize, MemSize);
11092     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11093     Chain = Value.getValue(1);
11094     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11095     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11096   }
11097
11098   MachineMemOperand *MMO =
11099     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11100                             MachineMemOperand::MOStore, MemSize, MemSize);
11101
11102   if (Opc != X86ISD::WIN_FTOL) {
11103     // Build the FP_TO_INT*_IN_MEM
11104     SDValue Ops[] = { Chain, Value, StackSlot };
11105     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11106                                            Ops, DstTy, MMO);
11107     return std::make_pair(FIST, StackSlot);
11108   } else {
11109     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11110       DAG.getVTList(MVT::Other, MVT::Glue),
11111       Chain, Value);
11112     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11113       MVT::i32, ftol.getValue(1));
11114     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11115       MVT::i32, eax.getValue(2));
11116     SDValue Ops[] = { eax, edx };
11117     SDValue pair = IsReplace
11118       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11119       : DAG.getMergeValues(Ops, DL);
11120     return std::make_pair(pair, SDValue());
11121   }
11122 }
11123
11124 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11125                               const X86Subtarget *Subtarget) {
11126   MVT VT = Op->getSimpleValueType(0);
11127   SDValue In = Op->getOperand(0);
11128   MVT InVT = In.getSimpleValueType();
11129   SDLoc dl(Op);
11130
11131   // Optimize vectors in AVX mode:
11132   //
11133   //   v8i16 -> v8i32
11134   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11135   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11136   //   Concat upper and lower parts.
11137   //
11138   //   v4i32 -> v4i64
11139   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11140   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11141   //   Concat upper and lower parts.
11142   //
11143
11144   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11145       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11146       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11147     return SDValue();
11148
11149   if (Subtarget->hasInt256())
11150     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11151
11152   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11153   SDValue Undef = DAG.getUNDEF(InVT);
11154   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11155   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11156   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11157
11158   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11159                              VT.getVectorNumElements()/2);
11160
11161   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11162   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11163
11164   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11165 }
11166
11167 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11168                                         SelectionDAG &DAG) {
11169   MVT VT = Op->getSimpleValueType(0);
11170   SDValue In = Op->getOperand(0);
11171   MVT InVT = In.getSimpleValueType();
11172   SDLoc DL(Op);
11173   unsigned int NumElts = VT.getVectorNumElements();
11174   if (NumElts != 8 && NumElts != 16)
11175     return SDValue();
11176
11177   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11178     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11179
11180   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11182   // Now we have only mask extension
11183   assert(InVT.getVectorElementType() == MVT::i1);
11184   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11185   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11186   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11187   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11188   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11189                            MachinePointerInfo::getConstantPool(),
11190                            false, false, false, Alignment);
11191
11192   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11193   if (VT.is512BitVector())
11194     return Brcst;
11195   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11196 }
11197
11198 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11199                                SelectionDAG &DAG) {
11200   if (Subtarget->hasFp256()) {
11201     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11202     if (Res.getNode())
11203       return Res;
11204   }
11205
11206   return SDValue();
11207 }
11208
11209 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11210                                 SelectionDAG &DAG) {
11211   SDLoc DL(Op);
11212   MVT VT = Op.getSimpleValueType();
11213   SDValue In = Op.getOperand(0);
11214   MVT SVT = In.getSimpleValueType();
11215
11216   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11217     return LowerZERO_EXTEND_AVX512(Op, DAG);
11218
11219   if (Subtarget->hasFp256()) {
11220     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11221     if (Res.getNode())
11222       return Res;
11223   }
11224
11225   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11226          VT.getVectorNumElements() != SVT.getVectorNumElements());
11227   return SDValue();
11228 }
11229
11230 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11231   SDLoc DL(Op);
11232   MVT VT = Op.getSimpleValueType();
11233   SDValue In = Op.getOperand(0);
11234   MVT InVT = In.getSimpleValueType();
11235
11236   if (VT == MVT::i1) {
11237     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11238            "Invalid scalar TRUNCATE operation");
11239     if (InVT == MVT::i32)
11240       return SDValue();
11241     if (InVT.getSizeInBits() == 64)
11242       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11243     else if (InVT.getSizeInBits() < 32)
11244       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11245     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11246   }
11247   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11248          "Invalid TRUNCATE operation");
11249
11250   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11251     if (VT.getVectorElementType().getSizeInBits() >=8)
11252       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11253
11254     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11255     unsigned NumElts = InVT.getVectorNumElements();
11256     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11257     if (InVT.getSizeInBits() < 512) {
11258       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11259       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11260       InVT = ExtVT;
11261     }
11262     
11263     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11264     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11265     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11266     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11267     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11268                            MachinePointerInfo::getConstantPool(),
11269                            false, false, false, Alignment);
11270     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11271     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11272     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11273   }
11274
11275   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11276     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11277     if (Subtarget->hasInt256()) {
11278       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11279       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11280       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11281                                 ShufMask);
11282       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11283                          DAG.getIntPtrConstant(0));
11284     }
11285
11286     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11287                                DAG.getIntPtrConstant(0));
11288     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11289                                DAG.getIntPtrConstant(2));
11290     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11291     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11292     static const int ShufMask[] = {0, 2, 4, 6};
11293     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11294   }
11295
11296   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11297     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11298     if (Subtarget->hasInt256()) {
11299       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11300
11301       SmallVector<SDValue,32> pshufbMask;
11302       for (unsigned i = 0; i < 2; ++i) {
11303         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11304         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11305         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11306         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11307         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11308         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11309         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11310         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11311         for (unsigned j = 0; j < 8; ++j)
11312           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11313       }
11314       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11315       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11316       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11317
11318       static const int ShufMask[] = {0,  2,  -1,  -1};
11319       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11320                                 &ShufMask[0]);
11321       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11322                        DAG.getIntPtrConstant(0));
11323       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11324     }
11325
11326     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11327                                DAG.getIntPtrConstant(0));
11328
11329     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11330                                DAG.getIntPtrConstant(4));
11331
11332     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11333     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11334
11335     // The PSHUFB mask:
11336     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11337                                    -1, -1, -1, -1, -1, -1, -1, -1};
11338
11339     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11340     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11341     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11342
11343     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11344     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11345
11346     // The MOVLHPS Mask:
11347     static const int ShufMask2[] = {0, 1, 4, 5};
11348     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11349     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11350   }
11351
11352   // Handle truncation of V256 to V128 using shuffles.
11353   if (!VT.is128BitVector() || !InVT.is256BitVector())
11354     return SDValue();
11355
11356   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11357
11358   unsigned NumElems = VT.getVectorNumElements();
11359   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11360
11361   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11362   // Prepare truncation shuffle mask
11363   for (unsigned i = 0; i != NumElems; ++i)
11364     MaskVec[i] = i * 2;
11365   SDValue V = DAG.getVectorShuffle(NVT, DL,
11366                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11367                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11368   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11369                      DAG.getIntPtrConstant(0));
11370 }
11371
11372 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11373                                            SelectionDAG &DAG) const {
11374   assert(!Op.getSimpleValueType().isVector());
11375
11376   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11377     /*IsSigned=*/ true, /*IsReplace=*/ false);
11378   SDValue FIST = Vals.first, StackSlot = Vals.second;
11379   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11380   if (!FIST.getNode()) return Op;
11381
11382   if (StackSlot.getNode())
11383     // Load the result.
11384     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11385                        FIST, StackSlot, MachinePointerInfo(),
11386                        false, false, false, 0);
11387
11388   // The node is the result.
11389   return FIST;
11390 }
11391
11392 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11393                                            SelectionDAG &DAG) const {
11394   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11395     /*IsSigned=*/ false, /*IsReplace=*/ false);
11396   SDValue FIST = Vals.first, StackSlot = Vals.second;
11397   assert(FIST.getNode() && "Unexpected failure");
11398
11399   if (StackSlot.getNode())
11400     // Load the result.
11401     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11402                        FIST, StackSlot, MachinePointerInfo(),
11403                        false, false, false, 0);
11404
11405   // The node is the result.
11406   return FIST;
11407 }
11408
11409 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11410   SDLoc DL(Op);
11411   MVT VT = Op.getSimpleValueType();
11412   SDValue In = Op.getOperand(0);
11413   MVT SVT = In.getSimpleValueType();
11414
11415   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11416
11417   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11418                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11419                                  In, DAG.getUNDEF(SVT)));
11420 }
11421
11422 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11423   LLVMContext *Context = DAG.getContext();
11424   SDLoc dl(Op);
11425   MVT VT = Op.getSimpleValueType();
11426   MVT EltVT = VT;
11427   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11428   if (VT.isVector()) {
11429     EltVT = VT.getVectorElementType();
11430     NumElts = VT.getVectorNumElements();
11431   }
11432   Constant *C;
11433   if (EltVT == MVT::f64)
11434     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11435                                           APInt(64, ~(1ULL << 63))));
11436   else
11437     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11438                                           APInt(32, ~(1U << 31))));
11439   C = ConstantVector::getSplat(NumElts, C);
11440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11441   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11442   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11443   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11444                              MachinePointerInfo::getConstantPool(),
11445                              false, false, false, Alignment);
11446   if (VT.isVector()) {
11447     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11448     return DAG.getNode(ISD::BITCAST, dl, VT,
11449                        DAG.getNode(ISD::AND, dl, ANDVT,
11450                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11451                                                Op.getOperand(0)),
11452                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11453   }
11454   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11455 }
11456
11457 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11458   LLVMContext *Context = DAG.getContext();
11459   SDLoc dl(Op);
11460   MVT VT = Op.getSimpleValueType();
11461   MVT EltVT = VT;
11462   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11463   if (VT.isVector()) {
11464     EltVT = VT.getVectorElementType();
11465     NumElts = VT.getVectorNumElements();
11466   }
11467   Constant *C;
11468   if (EltVT == MVT::f64)
11469     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11470                                           APInt(64, 1ULL << 63)));
11471   else
11472     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11473                                           APInt(32, 1U << 31)));
11474   C = ConstantVector::getSplat(NumElts, C);
11475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11476   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11477   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11478   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11479                              MachinePointerInfo::getConstantPool(),
11480                              false, false, false, Alignment);
11481   if (VT.isVector()) {
11482     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11483     return DAG.getNode(ISD::BITCAST, dl, VT,
11484                        DAG.getNode(ISD::XOR, dl, XORVT,
11485                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11486                                                Op.getOperand(0)),
11487                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11488   }
11489
11490   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11491 }
11492
11493 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11495   LLVMContext *Context = DAG.getContext();
11496   SDValue Op0 = Op.getOperand(0);
11497   SDValue Op1 = Op.getOperand(1);
11498   SDLoc dl(Op);
11499   MVT VT = Op.getSimpleValueType();
11500   MVT SrcVT = Op1.getSimpleValueType();
11501
11502   // If second operand is smaller, extend it first.
11503   if (SrcVT.bitsLT(VT)) {
11504     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11505     SrcVT = VT;
11506   }
11507   // And if it is bigger, shrink it first.
11508   if (SrcVT.bitsGT(VT)) {
11509     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11510     SrcVT = VT;
11511   }
11512
11513   // At this point the operands and the result should have the same
11514   // type, and that won't be f80 since that is not custom lowered.
11515
11516   // First get the sign bit of second operand.
11517   SmallVector<Constant*,4> CV;
11518   if (SrcVT == MVT::f64) {
11519     const fltSemantics &Sem = APFloat::IEEEdouble;
11520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11521     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11522   } else {
11523     const fltSemantics &Sem = APFloat::IEEEsingle;
11524     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11525     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11526     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11527     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11528   }
11529   Constant *C = ConstantVector::get(CV);
11530   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11531   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11532                               MachinePointerInfo::getConstantPool(),
11533                               false, false, false, 16);
11534   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11535
11536   // Shift sign bit right or left if the two operands have different types.
11537   if (SrcVT.bitsGT(VT)) {
11538     // Op0 is MVT::f32, Op1 is MVT::f64.
11539     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11540     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11541                           DAG.getConstant(32, MVT::i32));
11542     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11543     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11544                           DAG.getIntPtrConstant(0));
11545   }
11546
11547   // Clear first operand sign bit.
11548   CV.clear();
11549   if (VT == MVT::f64) {
11550     const fltSemantics &Sem = APFloat::IEEEdouble;
11551     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11552                                                    APInt(64, ~(1ULL << 63)))));
11553     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11554   } else {
11555     const fltSemantics &Sem = APFloat::IEEEsingle;
11556     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11557                                                    APInt(32, ~(1U << 31)))));
11558     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11559     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11560     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11561   }
11562   C = ConstantVector::get(CV);
11563   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11564   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11565                               MachinePointerInfo::getConstantPool(),
11566                               false, false, false, 16);
11567   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11568
11569   // Or the value with the sign bit.
11570   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11571 }
11572
11573 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11574   SDValue N0 = Op.getOperand(0);
11575   SDLoc dl(Op);
11576   MVT VT = Op.getSimpleValueType();
11577
11578   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11579   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11580                                   DAG.getConstant(1, VT));
11581   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11582 }
11583
11584 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11585 //
11586 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11587                                       SelectionDAG &DAG) {
11588   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11589
11590   if (!Subtarget->hasSSE41())
11591     return SDValue();
11592
11593   if (!Op->hasOneUse())
11594     return SDValue();
11595
11596   SDNode *N = Op.getNode();
11597   SDLoc DL(N);
11598
11599   SmallVector<SDValue, 8> Opnds;
11600   DenseMap<SDValue, unsigned> VecInMap;
11601   SmallVector<SDValue, 8> VecIns;
11602   EVT VT = MVT::Other;
11603
11604   // Recognize a special case where a vector is casted into wide integer to
11605   // test all 0s.
11606   Opnds.push_back(N->getOperand(0));
11607   Opnds.push_back(N->getOperand(1));
11608
11609   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11610     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11611     // BFS traverse all OR'd operands.
11612     if (I->getOpcode() == ISD::OR) {
11613       Opnds.push_back(I->getOperand(0));
11614       Opnds.push_back(I->getOperand(1));
11615       // Re-evaluate the number of nodes to be traversed.
11616       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11617       continue;
11618     }
11619
11620     // Quit if a non-EXTRACT_VECTOR_ELT
11621     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11622       return SDValue();
11623
11624     // Quit if without a constant index.
11625     SDValue Idx = I->getOperand(1);
11626     if (!isa<ConstantSDNode>(Idx))
11627       return SDValue();
11628
11629     SDValue ExtractedFromVec = I->getOperand(0);
11630     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11631     if (M == VecInMap.end()) {
11632       VT = ExtractedFromVec.getValueType();
11633       // Quit if not 128/256-bit vector.
11634       if (!VT.is128BitVector() && !VT.is256BitVector())
11635         return SDValue();
11636       // Quit if not the same type.
11637       if (VecInMap.begin() != VecInMap.end() &&
11638           VT != VecInMap.begin()->first.getValueType())
11639         return SDValue();
11640       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11641       VecIns.push_back(ExtractedFromVec);
11642     }
11643     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11644   }
11645
11646   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11647          "Not extracted from 128-/256-bit vector.");
11648
11649   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11650
11651   for (DenseMap<SDValue, unsigned>::const_iterator
11652         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11653     // Quit if not all elements are used.
11654     if (I->second != FullMask)
11655       return SDValue();
11656   }
11657
11658   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11659
11660   // Cast all vectors into TestVT for PTEST.
11661   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11662     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11663
11664   // If more than one full vectors are evaluated, OR them first before PTEST.
11665   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11666     // Each iteration will OR 2 nodes and append the result until there is only
11667     // 1 node left, i.e. the final OR'd value of all vectors.
11668     SDValue LHS = VecIns[Slot];
11669     SDValue RHS = VecIns[Slot + 1];
11670     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11671   }
11672
11673   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11674                      VecIns.back(), VecIns.back());
11675 }
11676
11677 /// \brief return true if \c Op has a use that doesn't just read flags.
11678 static bool hasNonFlagsUse(SDValue Op) {
11679   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11680        ++UI) {
11681     SDNode *User = *UI;
11682     unsigned UOpNo = UI.getOperandNo();
11683     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11684       // Look pass truncate.
11685       UOpNo = User->use_begin().getOperandNo();
11686       User = *User->use_begin();
11687     }
11688
11689     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11690         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11691       return true;
11692   }
11693   return false;
11694 }
11695
11696 /// Emit nodes that will be selected as "test Op0,Op0", or something
11697 /// equivalent.
11698 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11699                                     SelectionDAG &DAG) const {
11700   if (Op.getValueType() == MVT::i1)
11701     // KORTEST instruction should be selected
11702     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11703                        DAG.getConstant(0, Op.getValueType()));
11704
11705   // CF and OF aren't always set the way we want. Determine which
11706   // of these we need.
11707   bool NeedCF = false;
11708   bool NeedOF = false;
11709   switch (X86CC) {
11710   default: break;
11711   case X86::COND_A: case X86::COND_AE:
11712   case X86::COND_B: case X86::COND_BE:
11713     NeedCF = true;
11714     break;
11715   case X86::COND_G: case X86::COND_GE:
11716   case X86::COND_L: case X86::COND_LE:
11717   case X86::COND_O: case X86::COND_NO: {
11718     // Check if we really need to set the
11719     // Overflow flag. If NoSignedWrap is present
11720     // that is not actually needed.
11721     switch (Op->getOpcode()) {
11722     case ISD::ADD:
11723     case ISD::SUB:
11724     case ISD::MUL:
11725     case ISD::SHL: {
11726       const BinaryWithFlagsSDNode *BinNode =
11727           cast<BinaryWithFlagsSDNode>(Op.getNode());
11728       if (BinNode->hasNoSignedWrap())
11729         break;
11730     }
11731     default:
11732       NeedOF = true;
11733       break;
11734     }
11735     break;
11736   }
11737   }
11738   // See if we can use the EFLAGS value from the operand instead of
11739   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11740   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11741   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11742     // Emit a CMP with 0, which is the TEST pattern.
11743     //if (Op.getValueType() == MVT::i1)
11744     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11745     //                     DAG.getConstant(0, MVT::i1));
11746     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11747                        DAG.getConstant(0, Op.getValueType()));
11748   }
11749   unsigned Opcode = 0;
11750   unsigned NumOperands = 0;
11751
11752   // Truncate operations may prevent the merge of the SETCC instruction
11753   // and the arithmetic instruction before it. Attempt to truncate the operands
11754   // of the arithmetic instruction and use a reduced bit-width instruction.
11755   bool NeedTruncation = false;
11756   SDValue ArithOp = Op;
11757   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11758     SDValue Arith = Op->getOperand(0);
11759     // Both the trunc and the arithmetic op need to have one user each.
11760     if (Arith->hasOneUse())
11761       switch (Arith.getOpcode()) {
11762         default: break;
11763         case ISD::ADD:
11764         case ISD::SUB:
11765         case ISD::AND:
11766         case ISD::OR:
11767         case ISD::XOR: {
11768           NeedTruncation = true;
11769           ArithOp = Arith;
11770         }
11771       }
11772   }
11773
11774   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11775   // which may be the result of a CAST.  We use the variable 'Op', which is the
11776   // non-casted variable when we check for possible users.
11777   switch (ArithOp.getOpcode()) {
11778   case ISD::ADD:
11779     // Due to an isel shortcoming, be conservative if this add is likely to be
11780     // selected as part of a load-modify-store instruction. When the root node
11781     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11782     // uses of other nodes in the match, such as the ADD in this case. This
11783     // leads to the ADD being left around and reselected, with the result being
11784     // two adds in the output.  Alas, even if none our users are stores, that
11785     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11786     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11787     // climbing the DAG back to the root, and it doesn't seem to be worth the
11788     // effort.
11789     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11790          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11791       if (UI->getOpcode() != ISD::CopyToReg &&
11792           UI->getOpcode() != ISD::SETCC &&
11793           UI->getOpcode() != ISD::STORE)
11794         goto default_case;
11795
11796     if (ConstantSDNode *C =
11797         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11798       // An add of one will be selected as an INC.
11799       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11800         Opcode = X86ISD::INC;
11801         NumOperands = 1;
11802         break;
11803       }
11804
11805       // An add of negative one (subtract of one) will be selected as a DEC.
11806       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11807         Opcode = X86ISD::DEC;
11808         NumOperands = 1;
11809         break;
11810       }
11811     }
11812
11813     // Otherwise use a regular EFLAGS-setting add.
11814     Opcode = X86ISD::ADD;
11815     NumOperands = 2;
11816     break;
11817   case ISD::SHL:
11818   case ISD::SRL:
11819     // If we have a constant logical shift that's only used in a comparison
11820     // against zero turn it into an equivalent AND. This allows turning it into
11821     // a TEST instruction later.
11822     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11823         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11824       EVT VT = Op.getValueType();
11825       unsigned BitWidth = VT.getSizeInBits();
11826       unsigned ShAmt = Op->getConstantOperandVal(1);
11827       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11828         break;
11829       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11830                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11831                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11832       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11833         break;
11834       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11835                                 DAG.getConstant(Mask, VT));
11836       DAG.ReplaceAllUsesWith(Op, New);
11837       Op = New;
11838     }
11839     break;
11840
11841   case ISD::AND:
11842     // If the primary and result isn't used, don't bother using X86ISD::AND,
11843     // because a TEST instruction will be better.
11844     if (!hasNonFlagsUse(Op))
11845       break;
11846     // FALL THROUGH
11847   case ISD::SUB:
11848   case ISD::OR:
11849   case ISD::XOR:
11850     // Due to the ISEL shortcoming noted above, be conservative if this op is
11851     // likely to be selected as part of a load-modify-store instruction.
11852     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11853            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11854       if (UI->getOpcode() == ISD::STORE)
11855         goto default_case;
11856
11857     // Otherwise use a regular EFLAGS-setting instruction.
11858     switch (ArithOp.getOpcode()) {
11859     default: llvm_unreachable("unexpected operator!");
11860     case ISD::SUB: Opcode = X86ISD::SUB; break;
11861     case ISD::XOR: Opcode = X86ISD::XOR; break;
11862     case ISD::AND: Opcode = X86ISD::AND; break;
11863     case ISD::OR: {
11864       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11865         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11866         if (EFLAGS.getNode())
11867           return EFLAGS;
11868       }
11869       Opcode = X86ISD::OR;
11870       break;
11871     }
11872     }
11873
11874     NumOperands = 2;
11875     break;
11876   case X86ISD::ADD:
11877   case X86ISD::SUB:
11878   case X86ISD::INC:
11879   case X86ISD::DEC:
11880   case X86ISD::OR:
11881   case X86ISD::XOR:
11882   case X86ISD::AND:
11883     return SDValue(Op.getNode(), 1);
11884   default:
11885   default_case:
11886     break;
11887   }
11888
11889   // If we found that truncation is beneficial, perform the truncation and
11890   // update 'Op'.
11891   if (NeedTruncation) {
11892     EVT VT = Op.getValueType();
11893     SDValue WideVal = Op->getOperand(0);
11894     EVT WideVT = WideVal.getValueType();
11895     unsigned ConvertedOp = 0;
11896     // Use a target machine opcode to prevent further DAGCombine
11897     // optimizations that may separate the arithmetic operations
11898     // from the setcc node.
11899     switch (WideVal.getOpcode()) {
11900       default: break;
11901       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11902       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11903       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11904       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11905       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11906     }
11907
11908     if (ConvertedOp) {
11909       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11910       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11911         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11912         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11913         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11914       }
11915     }
11916   }
11917
11918   if (Opcode == 0)
11919     // Emit a CMP with 0, which is the TEST pattern.
11920     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11921                        DAG.getConstant(0, Op.getValueType()));
11922
11923   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11924   SmallVector<SDValue, 4> Ops;
11925   for (unsigned i = 0; i != NumOperands; ++i)
11926     Ops.push_back(Op.getOperand(i));
11927
11928   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11929   DAG.ReplaceAllUsesWith(Op, New);
11930   return SDValue(New.getNode(), 1);
11931 }
11932
11933 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11934 /// equivalent.
11935 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11936                                    SDLoc dl, SelectionDAG &DAG) const {
11937   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11938     if (C->getAPIntValue() == 0)
11939       return EmitTest(Op0, X86CC, dl, DAG);
11940
11941      if (Op0.getValueType() == MVT::i1)
11942        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11943   }
11944  
11945   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11946        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11947     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11948     // This avoids subregister aliasing issues. Keep the smaller reference 
11949     // if we're optimizing for size, however, as that'll allow better folding 
11950     // of memory operations.
11951     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11952         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11953              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11954         !Subtarget->isAtom()) {
11955       unsigned ExtendOp =
11956           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11957       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11958       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11959     }
11960     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11961     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11962     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11963                               Op0, Op1);
11964     return SDValue(Sub.getNode(), 1);
11965   }
11966   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11967 }
11968
11969 /// Convert a comparison if required by the subtarget.
11970 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11971                                                  SelectionDAG &DAG) const {
11972   // If the subtarget does not support the FUCOMI instruction, floating-point
11973   // comparisons have to be converted.
11974   if (Subtarget->hasCMov() ||
11975       Cmp.getOpcode() != X86ISD::CMP ||
11976       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11977       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11978     return Cmp;
11979
11980   // The instruction selector will select an FUCOM instruction instead of
11981   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11982   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11983   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11984   SDLoc dl(Cmp);
11985   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11986   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11987   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11988                             DAG.getConstant(8, MVT::i8));
11989   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11990   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11991 }
11992
11993 static bool isAllOnes(SDValue V) {
11994   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11995   return C && C->isAllOnesValue();
11996 }
11997
11998 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11999 /// if it's possible.
12000 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12001                                      SDLoc dl, SelectionDAG &DAG) const {
12002   SDValue Op0 = And.getOperand(0);
12003   SDValue Op1 = And.getOperand(1);
12004   if (Op0.getOpcode() == ISD::TRUNCATE)
12005     Op0 = Op0.getOperand(0);
12006   if (Op1.getOpcode() == ISD::TRUNCATE)
12007     Op1 = Op1.getOperand(0);
12008
12009   SDValue LHS, RHS;
12010   if (Op1.getOpcode() == ISD::SHL)
12011     std::swap(Op0, Op1);
12012   if (Op0.getOpcode() == ISD::SHL) {
12013     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12014       if (And00C->getZExtValue() == 1) {
12015         // If we looked past a truncate, check that it's only truncating away
12016         // known zeros.
12017         unsigned BitWidth = Op0.getValueSizeInBits();
12018         unsigned AndBitWidth = And.getValueSizeInBits();
12019         if (BitWidth > AndBitWidth) {
12020           APInt Zeros, Ones;
12021           DAG.computeKnownBits(Op0, Zeros, Ones);
12022           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12023             return SDValue();
12024         }
12025         LHS = Op1;
12026         RHS = Op0.getOperand(1);
12027       }
12028   } else if (Op1.getOpcode() == ISD::Constant) {
12029     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12030     uint64_t AndRHSVal = AndRHS->getZExtValue();
12031     SDValue AndLHS = Op0;
12032
12033     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12034       LHS = AndLHS.getOperand(0);
12035       RHS = AndLHS.getOperand(1);
12036     }
12037
12038     // Use BT if the immediate can't be encoded in a TEST instruction.
12039     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12040       LHS = AndLHS;
12041       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12042     }
12043   }
12044
12045   if (LHS.getNode()) {
12046     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12047     // instruction.  Since the shift amount is in-range-or-undefined, we know
12048     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12049     // the encoding for the i16 version is larger than the i32 version.
12050     // Also promote i16 to i32 for performance / code size reason.
12051     if (LHS.getValueType() == MVT::i8 ||
12052         LHS.getValueType() == MVT::i16)
12053       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12054
12055     // If the operand types disagree, extend the shift amount to match.  Since
12056     // BT ignores high bits (like shifts) we can use anyextend.
12057     if (LHS.getValueType() != RHS.getValueType())
12058       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12059
12060     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12061     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12062     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12063                        DAG.getConstant(Cond, MVT::i8), BT);
12064   }
12065
12066   return SDValue();
12067 }
12068
12069 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12070 /// mask CMPs.
12071 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12072                               SDValue &Op1) {
12073   unsigned SSECC;
12074   bool Swap = false;
12075
12076   // SSE Condition code mapping:
12077   //  0 - EQ
12078   //  1 - LT
12079   //  2 - LE
12080   //  3 - UNORD
12081   //  4 - NEQ
12082   //  5 - NLT
12083   //  6 - NLE
12084   //  7 - ORD
12085   switch (SetCCOpcode) {
12086   default: llvm_unreachable("Unexpected SETCC condition");
12087   case ISD::SETOEQ:
12088   case ISD::SETEQ:  SSECC = 0; break;
12089   case ISD::SETOGT:
12090   case ISD::SETGT:  Swap = true; // Fallthrough
12091   case ISD::SETLT:
12092   case ISD::SETOLT: SSECC = 1; break;
12093   case ISD::SETOGE:
12094   case ISD::SETGE:  Swap = true; // Fallthrough
12095   case ISD::SETLE:
12096   case ISD::SETOLE: SSECC = 2; break;
12097   case ISD::SETUO:  SSECC = 3; break;
12098   case ISD::SETUNE:
12099   case ISD::SETNE:  SSECC = 4; break;
12100   case ISD::SETULE: Swap = true; // Fallthrough
12101   case ISD::SETUGE: SSECC = 5; break;
12102   case ISD::SETULT: Swap = true; // Fallthrough
12103   case ISD::SETUGT: SSECC = 6; break;
12104   case ISD::SETO:   SSECC = 7; break;
12105   case ISD::SETUEQ:
12106   case ISD::SETONE: SSECC = 8; break;
12107   }
12108   if (Swap)
12109     std::swap(Op0, Op1);
12110
12111   return SSECC;
12112 }
12113
12114 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12115 // ones, and then concatenate the result back.
12116 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12117   MVT VT = Op.getSimpleValueType();
12118
12119   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12120          "Unsupported value type for operation");
12121
12122   unsigned NumElems = VT.getVectorNumElements();
12123   SDLoc dl(Op);
12124   SDValue CC = Op.getOperand(2);
12125
12126   // Extract the LHS vectors
12127   SDValue LHS = Op.getOperand(0);
12128   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12129   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12130
12131   // Extract the RHS vectors
12132   SDValue RHS = Op.getOperand(1);
12133   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12134   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12135
12136   // Issue the operation on the smaller types and concatenate the result back
12137   MVT EltVT = VT.getVectorElementType();
12138   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12139   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12140                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12141                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12142 }
12143
12144 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12145                                      const X86Subtarget *Subtarget) {
12146   SDValue Op0 = Op.getOperand(0);
12147   SDValue Op1 = Op.getOperand(1);
12148   SDValue CC = Op.getOperand(2);
12149   MVT VT = Op.getSimpleValueType();
12150   SDLoc dl(Op);
12151
12152   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12153          Op.getValueType().getScalarType() == MVT::i1 &&
12154          "Cannot set masked compare for this operation");
12155
12156   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12157   unsigned  Opc = 0;
12158   bool Unsigned = false;
12159   bool Swap = false;
12160   unsigned SSECC;
12161   switch (SetCCOpcode) {
12162   default: llvm_unreachable("Unexpected SETCC condition");
12163   case ISD::SETNE:  SSECC = 4; break;
12164   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12165   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12166   case ISD::SETLT:  Swap = true; //fall-through
12167   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12168   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12169   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12170   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12171   case ISD::SETULE: Unsigned = true; //fall-through
12172   case ISD::SETLE:  SSECC = 2; break;
12173   }
12174
12175   if (Swap)
12176     std::swap(Op0, Op1);
12177   if (Opc)
12178     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12179   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12180   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12181                      DAG.getConstant(SSECC, MVT::i8));
12182 }
12183
12184 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12185 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12186 /// return an empty value.
12187 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12188 {
12189   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12190   if (!BV)
12191     return SDValue();
12192
12193   MVT VT = Op1.getSimpleValueType();
12194   MVT EVT = VT.getVectorElementType();
12195   unsigned n = VT.getVectorNumElements();
12196   SmallVector<SDValue, 8> ULTOp1;
12197
12198   for (unsigned i = 0; i < n; ++i) {
12199     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12200     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12201       return SDValue();
12202
12203     // Avoid underflow.
12204     APInt Val = Elt->getAPIntValue();
12205     if (Val == 0)
12206       return SDValue();
12207
12208     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12209   }
12210
12211   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12212 }
12213
12214 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12215                            SelectionDAG &DAG) {
12216   SDValue Op0 = Op.getOperand(0);
12217   SDValue Op1 = Op.getOperand(1);
12218   SDValue CC = Op.getOperand(2);
12219   MVT VT = Op.getSimpleValueType();
12220   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12221   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12222   SDLoc dl(Op);
12223
12224   if (isFP) {
12225 #ifndef NDEBUG
12226     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12227     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12228 #endif
12229
12230     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12231     unsigned Opc = X86ISD::CMPP;
12232     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12233       assert(VT.getVectorNumElements() <= 16);
12234       Opc = X86ISD::CMPM;
12235     }
12236     // In the two special cases we can't handle, emit two comparisons.
12237     if (SSECC == 8) {
12238       unsigned CC0, CC1;
12239       unsigned CombineOpc;
12240       if (SetCCOpcode == ISD::SETUEQ) {
12241         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12242       } else {
12243         assert(SetCCOpcode == ISD::SETONE);
12244         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12245       }
12246
12247       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12248                                  DAG.getConstant(CC0, MVT::i8));
12249       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12250                                  DAG.getConstant(CC1, MVT::i8));
12251       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12252     }
12253     // Handle all other FP comparisons here.
12254     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12255                        DAG.getConstant(SSECC, MVT::i8));
12256   }
12257
12258   // Break 256-bit integer vector compare into smaller ones.
12259   if (VT.is256BitVector() && !Subtarget->hasInt256())
12260     return Lower256IntVSETCC(Op, DAG);
12261
12262   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12263   EVT OpVT = Op1.getValueType();
12264   if (Subtarget->hasAVX512()) {
12265     if (Op1.getValueType().is512BitVector() ||
12266         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12267       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12268
12269     // In AVX-512 architecture setcc returns mask with i1 elements,
12270     // But there is no compare instruction for i8 and i16 elements.
12271     // We are not talking about 512-bit operands in this case, these
12272     // types are illegal.
12273     if (MaskResult &&
12274         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12275          OpVT.getVectorElementType().getSizeInBits() >= 8))
12276       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12277                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12278   }
12279
12280   // We are handling one of the integer comparisons here.  Since SSE only has
12281   // GT and EQ comparisons for integer, swapping operands and multiple
12282   // operations may be required for some comparisons.
12283   unsigned Opc;
12284   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12285   bool Subus = false;
12286
12287   switch (SetCCOpcode) {
12288   default: llvm_unreachable("Unexpected SETCC condition");
12289   case ISD::SETNE:  Invert = true;
12290   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12291   case ISD::SETLT:  Swap = true;
12292   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12293   case ISD::SETGE:  Swap = true;
12294   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12295                     Invert = true; break;
12296   case ISD::SETULT: Swap = true;
12297   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12298                     FlipSigns = true; break;
12299   case ISD::SETUGE: Swap = true;
12300   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12301                     FlipSigns = true; Invert = true; break;
12302   }
12303
12304   // Special case: Use min/max operations for SETULE/SETUGE
12305   MVT VET = VT.getVectorElementType();
12306   bool hasMinMax =
12307        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12308     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12309
12310   if (hasMinMax) {
12311     switch (SetCCOpcode) {
12312     default: break;
12313     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12314     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12315     }
12316
12317     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12318   }
12319
12320   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12321   if (!MinMax && hasSubus) {
12322     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12323     // Op0 u<= Op1:
12324     //   t = psubus Op0, Op1
12325     //   pcmpeq t, <0..0>
12326     switch (SetCCOpcode) {
12327     default: break;
12328     case ISD::SETULT: {
12329       // If the comparison is against a constant we can turn this into a
12330       // setule.  With psubus, setule does not require a swap.  This is
12331       // beneficial because the constant in the register is no longer
12332       // destructed as the destination so it can be hoisted out of a loop.
12333       // Only do this pre-AVX since vpcmp* is no longer destructive.
12334       if (Subtarget->hasAVX())
12335         break;
12336       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12337       if (ULEOp1.getNode()) {
12338         Op1 = ULEOp1;
12339         Subus = true; Invert = false; Swap = false;
12340       }
12341       break;
12342     }
12343     // Psubus is better than flip-sign because it requires no inversion.
12344     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12345     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12346     }
12347
12348     if (Subus) {
12349       Opc = X86ISD::SUBUS;
12350       FlipSigns = false;
12351     }
12352   }
12353
12354   if (Swap)
12355     std::swap(Op0, Op1);
12356
12357   // Check that the operation in question is available (most are plain SSE2,
12358   // but PCMPGTQ and PCMPEQQ have different requirements).
12359   if (VT == MVT::v2i64) {
12360     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12361       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12362
12363       // First cast everything to the right type.
12364       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12365       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12366
12367       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12368       // bits of the inputs before performing those operations. The lower
12369       // compare is always unsigned.
12370       SDValue SB;
12371       if (FlipSigns) {
12372         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12373       } else {
12374         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12375         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12376         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12377                          Sign, Zero, Sign, Zero);
12378       }
12379       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12380       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12381
12382       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12383       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12384       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12385
12386       // Create masks for only the low parts/high parts of the 64 bit integers.
12387       static const int MaskHi[] = { 1, 1, 3, 3 };
12388       static const int MaskLo[] = { 0, 0, 2, 2 };
12389       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12390       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12391       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12392
12393       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12394       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12395
12396       if (Invert)
12397         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12398
12399       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12400     }
12401
12402     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12403       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12404       // pcmpeqd + pshufd + pand.
12405       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12406
12407       // First cast everything to the right type.
12408       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12409       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12410
12411       // Do the compare.
12412       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12413
12414       // Make sure the lower and upper halves are both all-ones.
12415       static const int Mask[] = { 1, 0, 3, 2 };
12416       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12417       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12418
12419       if (Invert)
12420         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12421
12422       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12423     }
12424   }
12425
12426   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12427   // bits of the inputs before performing those operations.
12428   if (FlipSigns) {
12429     EVT EltVT = VT.getVectorElementType();
12430     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12431     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12432     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12433   }
12434
12435   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12436
12437   // If the logical-not of the result is required, perform that now.
12438   if (Invert)
12439     Result = DAG.getNOT(dl, Result, VT);
12440
12441   if (MinMax)
12442     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12443
12444   if (Subus)
12445     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12446                          getZeroVector(VT, Subtarget, DAG, dl));
12447
12448   return Result;
12449 }
12450
12451 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12452
12453   MVT VT = Op.getSimpleValueType();
12454
12455   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12456
12457   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12458          && "SetCC type must be 8-bit or 1-bit integer");
12459   SDValue Op0 = Op.getOperand(0);
12460   SDValue Op1 = Op.getOperand(1);
12461   SDLoc dl(Op);
12462   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12463
12464   // Optimize to BT if possible.
12465   // Lower (X & (1 << N)) == 0 to BT(X, N).
12466   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12467   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12468   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12469       Op1.getOpcode() == ISD::Constant &&
12470       cast<ConstantSDNode>(Op1)->isNullValue() &&
12471       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12472     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12473     if (NewSetCC.getNode())
12474       return NewSetCC;
12475   }
12476
12477   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12478   // these.
12479   if (Op1.getOpcode() == ISD::Constant &&
12480       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12481        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12482       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12483
12484     // If the input is a setcc, then reuse the input setcc or use a new one with
12485     // the inverted condition.
12486     if (Op0.getOpcode() == X86ISD::SETCC) {
12487       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12488       bool Invert = (CC == ISD::SETNE) ^
12489         cast<ConstantSDNode>(Op1)->isNullValue();
12490       if (!Invert)
12491         return Op0;
12492
12493       CCode = X86::GetOppositeBranchCondition(CCode);
12494       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12495                                   DAG.getConstant(CCode, MVT::i8),
12496                                   Op0.getOperand(1));
12497       if (VT == MVT::i1)
12498         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12499       return SetCC;
12500     }
12501   }
12502   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12503       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12504       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12505
12506     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12507     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12508   }
12509
12510   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12511   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12512   if (X86CC == X86::COND_INVALID)
12513     return SDValue();
12514
12515   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12516   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12517   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12518                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12519   if (VT == MVT::i1)
12520     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12521   return SetCC;
12522 }
12523
12524 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12525 static bool isX86LogicalCmp(SDValue Op) {
12526   unsigned Opc = Op.getNode()->getOpcode();
12527   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12528       Opc == X86ISD::SAHF)
12529     return true;
12530   if (Op.getResNo() == 1 &&
12531       (Opc == X86ISD::ADD ||
12532        Opc == X86ISD::SUB ||
12533        Opc == X86ISD::ADC ||
12534        Opc == X86ISD::SBB ||
12535        Opc == X86ISD::SMUL ||
12536        Opc == X86ISD::UMUL ||
12537        Opc == X86ISD::INC ||
12538        Opc == X86ISD::DEC ||
12539        Opc == X86ISD::OR ||
12540        Opc == X86ISD::XOR ||
12541        Opc == X86ISD::AND))
12542     return true;
12543
12544   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12545     return true;
12546
12547   return false;
12548 }
12549
12550 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12551   if (V.getOpcode() != ISD::TRUNCATE)
12552     return false;
12553
12554   SDValue VOp0 = V.getOperand(0);
12555   unsigned InBits = VOp0.getValueSizeInBits();
12556   unsigned Bits = V.getValueSizeInBits();
12557   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12558 }
12559
12560 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12561   bool addTest = true;
12562   SDValue Cond  = Op.getOperand(0);
12563   SDValue Op1 = Op.getOperand(1);
12564   SDValue Op2 = Op.getOperand(2);
12565   SDLoc DL(Op);
12566   EVT VT = Op1.getValueType();
12567   SDValue CC;
12568
12569   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12570   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12571   // sequence later on.
12572   if (Cond.getOpcode() == ISD::SETCC &&
12573       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12574        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12575       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12576     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12577     int SSECC = translateX86FSETCC(
12578         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12579
12580     if (SSECC != 8) {
12581       if (Subtarget->hasAVX512()) {
12582         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12583                                   DAG.getConstant(SSECC, MVT::i8));
12584         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12585       }
12586       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12587                                 DAG.getConstant(SSECC, MVT::i8));
12588       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12589       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12590       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12591     }
12592   }
12593
12594   if (Cond.getOpcode() == ISD::SETCC) {
12595     SDValue NewCond = LowerSETCC(Cond, DAG);
12596     if (NewCond.getNode())
12597       Cond = NewCond;
12598   }
12599
12600   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12601   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12602   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12603   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12604   if (Cond.getOpcode() == X86ISD::SETCC &&
12605       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12606       isZero(Cond.getOperand(1).getOperand(1))) {
12607     SDValue Cmp = Cond.getOperand(1);
12608
12609     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12610
12611     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12612         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12613       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12614
12615       SDValue CmpOp0 = Cmp.getOperand(0);
12616       // Apply further optimizations for special cases
12617       // (select (x != 0), -1, 0) -> neg & sbb
12618       // (select (x == 0), 0, -1) -> neg & sbb
12619       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12620         if (YC->isNullValue() &&
12621             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12622           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12623           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12624                                     DAG.getConstant(0, CmpOp0.getValueType()),
12625                                     CmpOp0);
12626           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12627                                     DAG.getConstant(X86::COND_B, MVT::i8),
12628                                     SDValue(Neg.getNode(), 1));
12629           return Res;
12630         }
12631
12632       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12633                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12634       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12635
12636       SDValue Res =   // Res = 0 or -1.
12637         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12638                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12639
12640       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12641         Res = DAG.getNOT(DL, Res, Res.getValueType());
12642
12643       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12644       if (!N2C || !N2C->isNullValue())
12645         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12646       return Res;
12647     }
12648   }
12649
12650   // Look past (and (setcc_carry (cmp ...)), 1).
12651   if (Cond.getOpcode() == ISD::AND &&
12652       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12653     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12654     if (C && C->getAPIntValue() == 1)
12655       Cond = Cond.getOperand(0);
12656   }
12657
12658   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12659   // setting operand in place of the X86ISD::SETCC.
12660   unsigned CondOpcode = Cond.getOpcode();
12661   if (CondOpcode == X86ISD::SETCC ||
12662       CondOpcode == X86ISD::SETCC_CARRY) {
12663     CC = Cond.getOperand(0);
12664
12665     SDValue Cmp = Cond.getOperand(1);
12666     unsigned Opc = Cmp.getOpcode();
12667     MVT VT = Op.getSimpleValueType();
12668
12669     bool IllegalFPCMov = false;
12670     if (VT.isFloatingPoint() && !VT.isVector() &&
12671         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12672       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12673
12674     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12675         Opc == X86ISD::BT) { // FIXME
12676       Cond = Cmp;
12677       addTest = false;
12678     }
12679   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12680              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12681              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12682               Cond.getOperand(0).getValueType() != MVT::i8)) {
12683     SDValue LHS = Cond.getOperand(0);
12684     SDValue RHS = Cond.getOperand(1);
12685     unsigned X86Opcode;
12686     unsigned X86Cond;
12687     SDVTList VTs;
12688     switch (CondOpcode) {
12689     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12690     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12691     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12692     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12693     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12694     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12695     default: llvm_unreachable("unexpected overflowing operator");
12696     }
12697     if (CondOpcode == ISD::UMULO)
12698       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12699                           MVT::i32);
12700     else
12701       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12702
12703     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12704
12705     if (CondOpcode == ISD::UMULO)
12706       Cond = X86Op.getValue(2);
12707     else
12708       Cond = X86Op.getValue(1);
12709
12710     CC = DAG.getConstant(X86Cond, MVT::i8);
12711     addTest = false;
12712   }
12713
12714   if (addTest) {
12715     // Look pass the truncate if the high bits are known zero.
12716     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12717         Cond = Cond.getOperand(0);
12718
12719     // We know the result of AND is compared against zero. Try to match
12720     // it to BT.
12721     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12722       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12723       if (NewSetCC.getNode()) {
12724         CC = NewSetCC.getOperand(0);
12725         Cond = NewSetCC.getOperand(1);
12726         addTest = false;
12727       }
12728     }
12729   }
12730
12731   if (addTest) {
12732     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12733     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12734   }
12735
12736   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12737   // a <  b ?  0 : -1 -> RES = setcc_carry
12738   // a >= b ? -1 :  0 -> RES = setcc_carry
12739   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12740   if (Cond.getOpcode() == X86ISD::SUB) {
12741     Cond = ConvertCmpIfNecessary(Cond, DAG);
12742     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12743
12744     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12745         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12746       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12747                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12748       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12749         return DAG.getNOT(DL, Res, Res.getValueType());
12750       return Res;
12751     }
12752   }
12753
12754   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12755   // widen the cmov and push the truncate through. This avoids introducing a new
12756   // branch during isel and doesn't add any extensions.
12757   if (Op.getValueType() == MVT::i8 &&
12758       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12759     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12760     if (T1.getValueType() == T2.getValueType() &&
12761         // Blacklist CopyFromReg to avoid partial register stalls.
12762         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12763       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12764       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12765       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12766     }
12767   }
12768
12769   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12770   // condition is true.
12771   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12772   SDValue Ops[] = { Op2, Op1, CC, Cond };
12773   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12774 }
12775
12776 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12777   MVT VT = Op->getSimpleValueType(0);
12778   SDValue In = Op->getOperand(0);
12779   MVT InVT = In.getSimpleValueType();
12780   SDLoc dl(Op);
12781
12782   unsigned int NumElts = VT.getVectorNumElements();
12783   if (NumElts != 8 && NumElts != 16)
12784     return SDValue();
12785
12786   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12787     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12788
12789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12790   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12791
12792   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12793   Constant *C = ConstantInt::get(*DAG.getContext(),
12794     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12795
12796   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12797   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12798   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12799                           MachinePointerInfo::getConstantPool(),
12800                           false, false, false, Alignment);
12801   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12802   if (VT.is512BitVector())
12803     return Brcst;
12804   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12805 }
12806
12807 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12808                                 SelectionDAG &DAG) {
12809   MVT VT = Op->getSimpleValueType(0);
12810   SDValue In = Op->getOperand(0);
12811   MVT InVT = In.getSimpleValueType();
12812   SDLoc dl(Op);
12813
12814   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12815     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12816
12817   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12818       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12819       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12820     return SDValue();
12821
12822   if (Subtarget->hasInt256())
12823     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12824
12825   // Optimize vectors in AVX mode
12826   // Sign extend  v8i16 to v8i32 and
12827   //              v4i32 to v4i64
12828   //
12829   // Divide input vector into two parts
12830   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12831   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12832   // concat the vectors to original VT
12833
12834   unsigned NumElems = InVT.getVectorNumElements();
12835   SDValue Undef = DAG.getUNDEF(InVT);
12836
12837   SmallVector<int,8> ShufMask1(NumElems, -1);
12838   for (unsigned i = 0; i != NumElems/2; ++i)
12839     ShufMask1[i] = i;
12840
12841   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12842
12843   SmallVector<int,8> ShufMask2(NumElems, -1);
12844   for (unsigned i = 0; i != NumElems/2; ++i)
12845     ShufMask2[i] = i + NumElems/2;
12846
12847   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12848
12849   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12850                                 VT.getVectorNumElements()/2);
12851
12852   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12853   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12854
12855   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12856 }
12857
12858 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12859 // may emit an illegal shuffle but the expansion is still better than scalar
12860 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12861 // we'll emit a shuffle and a arithmetic shift.
12862 // TODO: It is possible to support ZExt by zeroing the undef values during
12863 // the shuffle phase or after the shuffle.
12864 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12865                                  SelectionDAG &DAG) {
12866   MVT RegVT = Op.getSimpleValueType();
12867   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12868   assert(RegVT.isInteger() &&
12869          "We only custom lower integer vector sext loads.");
12870
12871   // Nothing useful we can do without SSE2 shuffles.
12872   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12873
12874   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12875   SDLoc dl(Ld);
12876   EVT MemVT = Ld->getMemoryVT();
12877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12878   unsigned RegSz = RegVT.getSizeInBits();
12879
12880   ISD::LoadExtType Ext = Ld->getExtensionType();
12881
12882   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12883          && "Only anyext and sext are currently implemented.");
12884   assert(MemVT != RegVT && "Cannot extend to the same type");
12885   assert(MemVT.isVector() && "Must load a vector from memory");
12886
12887   unsigned NumElems = RegVT.getVectorNumElements();
12888   unsigned MemSz = MemVT.getSizeInBits();
12889   assert(RegSz > MemSz && "Register size must be greater than the mem size");
12890
12891   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12892     // The only way in which we have a legal 256-bit vector result but not the
12893     // integer 256-bit operations needed to directly lower a sextload is if we
12894     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12895     // a 128-bit vector and a normal sign_extend to 256-bits that should get
12896     // correctly legalized. We do this late to allow the canonical form of
12897     // sextload to persist throughout the rest of the DAG combiner -- it wants
12898     // to fold together any extensions it can, and so will fuse a sign_extend
12899     // of an sextload into an sextload targeting a wider value.
12900     SDValue Load;
12901     if (MemSz == 128) {
12902       // Just switch this to a normal load.
12903       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
12904                                        "it must be a legal 128-bit vector "
12905                                        "type!");
12906       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
12907                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
12908                   Ld->isInvariant(), Ld->getAlignment());
12909     } else {
12910       assert(MemSz < 128 &&
12911              "Can't extend a type wider than 128 bits to a 256 bit vector!");
12912       // Do an sext load to a 128-bit vector type. We want to use the same
12913       // number of elements, but elements half as wide. This will end up being
12914       // recursively lowered by this routine, but will succeed as we definitely
12915       // have all the necessary features if we're using AVX1.
12916       EVT HalfEltVT =
12917           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
12918       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
12919       Load =
12920           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
12921                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
12922                          Ld->isNonTemporal(), Ld->getAlignment());
12923     }
12924
12925     // Replace chain users with the new chain.
12926     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
12927     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
12928
12929     // Finally, do a normal sign-extend to the desired register.
12930     return DAG.getSExtOrTrunc(Load, dl, RegVT);
12931   }
12932
12933   // All sizes must be a power of two.
12934   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
12935          "Non-power-of-two elements are not custom lowered!");
12936
12937   // Attempt to load the original value using scalar loads.
12938   // Find the largest scalar type that divides the total loaded size.
12939   MVT SclrLoadTy = MVT::i8;
12940   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
12941        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
12942     MVT Tp = (MVT::SimpleValueType)tp;
12943     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
12944       SclrLoadTy = Tp;
12945     }
12946   }
12947
12948   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
12949   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
12950       (64 <= MemSz))
12951     SclrLoadTy = MVT::f64;
12952
12953   // Calculate the number of scalar loads that we need to perform
12954   // in order to load our vector from memory.
12955   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
12956
12957   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
12958          "Can only lower sext loads with a single scalar load!");
12959
12960   unsigned loadRegZize = RegSz;
12961   if (Ext == ISD::SEXTLOAD && RegSz == 256)
12962     loadRegZize /= 2;
12963
12964   // Represent our vector as a sequence of elements which are the
12965   // largest scalar that we can load.
12966   EVT LoadUnitVecVT = EVT::getVectorVT(
12967       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
12968
12969   // Represent the data using the same element type that is stored in
12970   // memory. In practice, we ''widen'' MemVT.
12971   EVT WideVecVT =
12972       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
12973                        loadRegZize / MemVT.getScalarType().getSizeInBits());
12974
12975   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
12976          "Invalid vector type");
12977
12978   // We can't shuffle using an illegal type.
12979   assert(TLI.isTypeLegal(WideVecVT) &&
12980          "We only lower types that form legal widened vector types");
12981
12982   SmallVector<SDValue, 8> Chains;
12983   SDValue Ptr = Ld->getBasePtr();
12984   SDValue Increment =
12985       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
12986   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
12987
12988   for (unsigned i = 0; i < NumLoads; ++i) {
12989     // Perform a single load.
12990     SDValue ScalarLoad =
12991         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
12992                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
12993                     Ld->getAlignment());
12994     Chains.push_back(ScalarLoad.getValue(1));
12995     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
12996     // another round of DAGCombining.
12997     if (i == 0)
12998       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
12999     else
13000       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13001                         ScalarLoad, DAG.getIntPtrConstant(i));
13002
13003     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13004   }
13005
13006   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13007
13008   // Bitcast the loaded value to a vector of the original element type, in
13009   // the size of the target vector type.
13010   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13011   unsigned SizeRatio = RegSz / MemSz;
13012
13013   if (Ext == ISD::SEXTLOAD) {
13014     // If we have SSE4.1 we can directly emit a VSEXT node.
13015     if (Subtarget->hasSSE41()) {
13016       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13017       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13018       return Sext;
13019     }
13020
13021     // Otherwise we'll shuffle the small elements in the high bits of the
13022     // larger type and perform an arithmetic shift. If the shift is not legal
13023     // it's better to scalarize.
13024     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13025            "We can't implement an sext load without a arithmetic right shift!");
13026
13027     // Redistribute the loaded elements into the different locations.
13028     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13029     for (unsigned i = 0; i != NumElems; ++i)
13030       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13031
13032     SDValue Shuff = DAG.getVectorShuffle(
13033         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13034
13035     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13036
13037     // Build the arithmetic shift.
13038     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13039                    MemVT.getVectorElementType().getSizeInBits();
13040     Shuff =
13041         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13042
13043     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13044     return Shuff;
13045   }
13046
13047   // Redistribute the loaded elements into the different locations.
13048   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13049   for (unsigned i = 0; i != NumElems; ++i)
13050     ShuffleVec[i * SizeRatio] = i;
13051
13052   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13053                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13054
13055   // Bitcast to the requested type.
13056   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13057   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13058   return Shuff;
13059 }
13060
13061 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13062 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13063 // from the AND / OR.
13064 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13065   Opc = Op.getOpcode();
13066   if (Opc != ISD::OR && Opc != ISD::AND)
13067     return false;
13068   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13069           Op.getOperand(0).hasOneUse() &&
13070           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13071           Op.getOperand(1).hasOneUse());
13072 }
13073
13074 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13075 // 1 and that the SETCC node has a single use.
13076 static bool isXor1OfSetCC(SDValue Op) {
13077   if (Op.getOpcode() != ISD::XOR)
13078     return false;
13079   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13080   if (N1C && N1C->getAPIntValue() == 1) {
13081     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13082       Op.getOperand(0).hasOneUse();
13083   }
13084   return false;
13085 }
13086
13087 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13088   bool addTest = true;
13089   SDValue Chain = Op.getOperand(0);
13090   SDValue Cond  = Op.getOperand(1);
13091   SDValue Dest  = Op.getOperand(2);
13092   SDLoc dl(Op);
13093   SDValue CC;
13094   bool Inverted = false;
13095
13096   if (Cond.getOpcode() == ISD::SETCC) {
13097     // Check for setcc([su]{add,sub,mul}o == 0).
13098     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13099         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13100         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13101         Cond.getOperand(0).getResNo() == 1 &&
13102         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13103          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13104          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13105          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13106          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13107          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13108       Inverted = true;
13109       Cond = Cond.getOperand(0);
13110     } else {
13111       SDValue NewCond = LowerSETCC(Cond, DAG);
13112       if (NewCond.getNode())
13113         Cond = NewCond;
13114     }
13115   }
13116 #if 0
13117   // FIXME: LowerXALUO doesn't handle these!!
13118   else if (Cond.getOpcode() == X86ISD::ADD  ||
13119            Cond.getOpcode() == X86ISD::SUB  ||
13120            Cond.getOpcode() == X86ISD::SMUL ||
13121            Cond.getOpcode() == X86ISD::UMUL)
13122     Cond = LowerXALUO(Cond, DAG);
13123 #endif
13124
13125   // Look pass (and (setcc_carry (cmp ...)), 1).
13126   if (Cond.getOpcode() == ISD::AND &&
13127       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13128     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13129     if (C && C->getAPIntValue() == 1)
13130       Cond = Cond.getOperand(0);
13131   }
13132
13133   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13134   // setting operand in place of the X86ISD::SETCC.
13135   unsigned CondOpcode = Cond.getOpcode();
13136   if (CondOpcode == X86ISD::SETCC ||
13137       CondOpcode == X86ISD::SETCC_CARRY) {
13138     CC = Cond.getOperand(0);
13139
13140     SDValue Cmp = Cond.getOperand(1);
13141     unsigned Opc = Cmp.getOpcode();
13142     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13143     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13144       Cond = Cmp;
13145       addTest = false;
13146     } else {
13147       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13148       default: break;
13149       case X86::COND_O:
13150       case X86::COND_B:
13151         // These can only come from an arithmetic instruction with overflow,
13152         // e.g. SADDO, UADDO.
13153         Cond = Cond.getNode()->getOperand(1);
13154         addTest = false;
13155         break;
13156       }
13157     }
13158   }
13159   CondOpcode = Cond.getOpcode();
13160   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13161       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13162       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13163        Cond.getOperand(0).getValueType() != MVT::i8)) {
13164     SDValue LHS = Cond.getOperand(0);
13165     SDValue RHS = Cond.getOperand(1);
13166     unsigned X86Opcode;
13167     unsigned X86Cond;
13168     SDVTList VTs;
13169     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13170     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13171     // X86ISD::INC).
13172     switch (CondOpcode) {
13173     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13174     case ISD::SADDO:
13175       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13176         if (C->isOne()) {
13177           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13178           break;
13179         }
13180       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13181     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13182     case ISD::SSUBO:
13183       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13184         if (C->isOne()) {
13185           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13186           break;
13187         }
13188       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13189     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13190     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13191     default: llvm_unreachable("unexpected overflowing operator");
13192     }
13193     if (Inverted)
13194       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13195     if (CondOpcode == ISD::UMULO)
13196       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13197                           MVT::i32);
13198     else
13199       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13200
13201     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13202
13203     if (CondOpcode == ISD::UMULO)
13204       Cond = X86Op.getValue(2);
13205     else
13206       Cond = X86Op.getValue(1);
13207
13208     CC = DAG.getConstant(X86Cond, MVT::i8);
13209     addTest = false;
13210   } else {
13211     unsigned CondOpc;
13212     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13213       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13214       if (CondOpc == ISD::OR) {
13215         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13216         // two branches instead of an explicit OR instruction with a
13217         // separate test.
13218         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13219             isX86LogicalCmp(Cmp)) {
13220           CC = Cond.getOperand(0).getOperand(0);
13221           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13222                               Chain, Dest, CC, Cmp);
13223           CC = Cond.getOperand(1).getOperand(0);
13224           Cond = Cmp;
13225           addTest = false;
13226         }
13227       } else { // ISD::AND
13228         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13229         // two branches instead of an explicit AND instruction with a
13230         // separate test. However, we only do this if this block doesn't
13231         // have a fall-through edge, because this requires an explicit
13232         // jmp when the condition is false.
13233         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13234             isX86LogicalCmp(Cmp) &&
13235             Op.getNode()->hasOneUse()) {
13236           X86::CondCode CCode =
13237             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13238           CCode = X86::GetOppositeBranchCondition(CCode);
13239           CC = DAG.getConstant(CCode, MVT::i8);
13240           SDNode *User = *Op.getNode()->use_begin();
13241           // Look for an unconditional branch following this conditional branch.
13242           // We need this because we need to reverse the successors in order
13243           // to implement FCMP_OEQ.
13244           if (User->getOpcode() == ISD::BR) {
13245             SDValue FalseBB = User->getOperand(1);
13246             SDNode *NewBR =
13247               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13248             assert(NewBR == User);
13249             (void)NewBR;
13250             Dest = FalseBB;
13251
13252             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13253                                 Chain, Dest, CC, Cmp);
13254             X86::CondCode CCode =
13255               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13256             CCode = X86::GetOppositeBranchCondition(CCode);
13257             CC = DAG.getConstant(CCode, MVT::i8);
13258             Cond = Cmp;
13259             addTest = false;
13260           }
13261         }
13262       }
13263     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13264       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13265       // It should be transformed during dag combiner except when the condition
13266       // is set by a arithmetics with overflow node.
13267       X86::CondCode CCode =
13268         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13269       CCode = X86::GetOppositeBranchCondition(CCode);
13270       CC = DAG.getConstant(CCode, MVT::i8);
13271       Cond = Cond.getOperand(0).getOperand(1);
13272       addTest = false;
13273     } else if (Cond.getOpcode() == ISD::SETCC &&
13274                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13275       // For FCMP_OEQ, we can emit
13276       // two branches instead of an explicit AND instruction with a
13277       // separate test. However, we only do this if this block doesn't
13278       // have a fall-through edge, because this requires an explicit
13279       // jmp when the condition is false.
13280       if (Op.getNode()->hasOneUse()) {
13281         SDNode *User = *Op.getNode()->use_begin();
13282         // Look for an unconditional branch following this conditional branch.
13283         // We need this because we need to reverse the successors in order
13284         // to implement FCMP_OEQ.
13285         if (User->getOpcode() == ISD::BR) {
13286           SDValue FalseBB = User->getOperand(1);
13287           SDNode *NewBR =
13288             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13289           assert(NewBR == User);
13290           (void)NewBR;
13291           Dest = FalseBB;
13292
13293           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13294                                     Cond.getOperand(0), Cond.getOperand(1));
13295           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13296           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13297           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13298                               Chain, Dest, CC, Cmp);
13299           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13300           Cond = Cmp;
13301           addTest = false;
13302         }
13303       }
13304     } else if (Cond.getOpcode() == ISD::SETCC &&
13305                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13306       // For FCMP_UNE, we can emit
13307       // two branches instead of an explicit AND instruction with a
13308       // separate test. However, we only do this if this block doesn't
13309       // have a fall-through edge, because this requires an explicit
13310       // jmp when the condition is false.
13311       if (Op.getNode()->hasOneUse()) {
13312         SDNode *User = *Op.getNode()->use_begin();
13313         // Look for an unconditional branch following this conditional branch.
13314         // We need this because we need to reverse the successors in order
13315         // to implement FCMP_UNE.
13316         if (User->getOpcode() == ISD::BR) {
13317           SDValue FalseBB = User->getOperand(1);
13318           SDNode *NewBR =
13319             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13320           assert(NewBR == User);
13321           (void)NewBR;
13322
13323           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13324                                     Cond.getOperand(0), Cond.getOperand(1));
13325           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13326           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13327           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13328                               Chain, Dest, CC, Cmp);
13329           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13330           Cond = Cmp;
13331           addTest = false;
13332           Dest = FalseBB;
13333         }
13334       }
13335     }
13336   }
13337
13338   if (addTest) {
13339     // Look pass the truncate if the high bits are known zero.
13340     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13341         Cond = Cond.getOperand(0);
13342
13343     // We know the result of AND is compared against zero. Try to match
13344     // it to BT.
13345     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13346       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13347       if (NewSetCC.getNode()) {
13348         CC = NewSetCC.getOperand(0);
13349         Cond = NewSetCC.getOperand(1);
13350         addTest = false;
13351       }
13352     }
13353   }
13354
13355   if (addTest) {
13356     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13357     CC = DAG.getConstant(X86Cond, MVT::i8);
13358     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13359   }
13360   Cond = ConvertCmpIfNecessary(Cond, DAG);
13361   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13362                      Chain, Dest, CC, Cond);
13363 }
13364
13365 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13366 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13367 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13368 // that the guard pages used by the OS virtual memory manager are allocated in
13369 // correct sequence.
13370 SDValue
13371 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13372                                            SelectionDAG &DAG) const {
13373   MachineFunction &MF = DAG.getMachineFunction();
13374   bool SplitStack = MF.shouldSplitStack();
13375   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13376                SplitStack;
13377   SDLoc dl(Op);
13378
13379   if (!Lower) {
13380     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13381     SDNode* Node = Op.getNode();
13382
13383     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13384     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13385         " not tell us which reg is the stack pointer!");
13386     EVT VT = Node->getValueType(0);
13387     SDValue Tmp1 = SDValue(Node, 0);
13388     SDValue Tmp2 = SDValue(Node, 1);
13389     SDValue Tmp3 = Node->getOperand(2);
13390     SDValue Chain = Tmp1.getOperand(0);
13391
13392     // Chain the dynamic stack allocation so that it doesn't modify the stack
13393     // pointer when other instructions are using the stack.
13394     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13395         SDLoc(Node));
13396
13397     SDValue Size = Tmp2.getOperand(1);
13398     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13399     Chain = SP.getValue(1);
13400     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13401     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13402     unsigned StackAlign = TFI.getStackAlignment();
13403     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13404     if (Align > StackAlign)
13405       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13406           DAG.getConstant(-(uint64_t)Align, VT));
13407     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13408
13409     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13410         DAG.getIntPtrConstant(0, true), SDValue(),
13411         SDLoc(Node));
13412
13413     SDValue Ops[2] = { Tmp1, Tmp2 };
13414     return DAG.getMergeValues(Ops, dl);
13415   }
13416
13417   // Get the inputs.
13418   SDValue Chain = Op.getOperand(0);
13419   SDValue Size  = Op.getOperand(1);
13420   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13421   EVT VT = Op.getNode()->getValueType(0);
13422
13423   bool Is64Bit = Subtarget->is64Bit();
13424   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13425
13426   if (SplitStack) {
13427     MachineRegisterInfo &MRI = MF.getRegInfo();
13428
13429     if (Is64Bit) {
13430       // The 64 bit implementation of segmented stacks needs to clobber both r10
13431       // r11. This makes it impossible to use it along with nested parameters.
13432       const Function *F = MF.getFunction();
13433
13434       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13435            I != E; ++I)
13436         if (I->hasNestAttr())
13437           report_fatal_error("Cannot use segmented stacks with functions that "
13438                              "have nested arguments.");
13439     }
13440
13441     const TargetRegisterClass *AddrRegClass =
13442       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13443     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13444     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13445     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13446                                 DAG.getRegister(Vreg, SPTy));
13447     SDValue Ops1[2] = { Value, Chain };
13448     return DAG.getMergeValues(Ops1, dl);
13449   } else {
13450     SDValue Flag;
13451     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13452
13453     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13454     Flag = Chain.getValue(1);
13455     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13456
13457     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13458
13459     const X86RegisterInfo *RegInfo =
13460       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13461     unsigned SPReg = RegInfo->getStackRegister();
13462     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13463     Chain = SP.getValue(1);
13464
13465     if (Align) {
13466       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13467                        DAG.getConstant(-(uint64_t)Align, VT));
13468       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13469     }
13470
13471     SDValue Ops1[2] = { SP, Chain };
13472     return DAG.getMergeValues(Ops1, dl);
13473   }
13474 }
13475
13476 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13477   MachineFunction &MF = DAG.getMachineFunction();
13478   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13479
13480   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13481   SDLoc DL(Op);
13482
13483   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13484     // vastart just stores the address of the VarArgsFrameIndex slot into the
13485     // memory location argument.
13486     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13487                                    getPointerTy());
13488     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13489                         MachinePointerInfo(SV), false, false, 0);
13490   }
13491
13492   // __va_list_tag:
13493   //   gp_offset         (0 - 6 * 8)
13494   //   fp_offset         (48 - 48 + 8 * 16)
13495   //   overflow_arg_area (point to parameters coming in memory).
13496   //   reg_save_area
13497   SmallVector<SDValue, 8> MemOps;
13498   SDValue FIN = Op.getOperand(1);
13499   // Store gp_offset
13500   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13501                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13502                                                MVT::i32),
13503                                FIN, MachinePointerInfo(SV), false, false, 0);
13504   MemOps.push_back(Store);
13505
13506   // Store fp_offset
13507   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13508                     FIN, DAG.getIntPtrConstant(4));
13509   Store = DAG.getStore(Op.getOperand(0), DL,
13510                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13511                                        MVT::i32),
13512                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13513   MemOps.push_back(Store);
13514
13515   // Store ptr to overflow_arg_area
13516   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13517                     FIN, DAG.getIntPtrConstant(4));
13518   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13519                                     getPointerTy());
13520   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13521                        MachinePointerInfo(SV, 8),
13522                        false, false, 0);
13523   MemOps.push_back(Store);
13524
13525   // Store ptr to reg_save_area.
13526   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13527                     FIN, DAG.getIntPtrConstant(8));
13528   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13529                                     getPointerTy());
13530   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13531                        MachinePointerInfo(SV, 16), false, false, 0);
13532   MemOps.push_back(Store);
13533   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13534 }
13535
13536 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13537   assert(Subtarget->is64Bit() &&
13538          "LowerVAARG only handles 64-bit va_arg!");
13539   assert((Subtarget->isTargetLinux() ||
13540           Subtarget->isTargetDarwin()) &&
13541           "Unhandled target in LowerVAARG");
13542   assert(Op.getNode()->getNumOperands() == 4);
13543   SDValue Chain = Op.getOperand(0);
13544   SDValue SrcPtr = Op.getOperand(1);
13545   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13546   unsigned Align = Op.getConstantOperandVal(3);
13547   SDLoc dl(Op);
13548
13549   EVT ArgVT = Op.getNode()->getValueType(0);
13550   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13551   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13552   uint8_t ArgMode;
13553
13554   // Decide which area this value should be read from.
13555   // TODO: Implement the AMD64 ABI in its entirety. This simple
13556   // selection mechanism works only for the basic types.
13557   if (ArgVT == MVT::f80) {
13558     llvm_unreachable("va_arg for f80 not yet implemented");
13559   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13560     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13561   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13562     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13563   } else {
13564     llvm_unreachable("Unhandled argument type in LowerVAARG");
13565   }
13566
13567   if (ArgMode == 2) {
13568     // Sanity Check: Make sure using fp_offset makes sense.
13569     assert(!DAG.getTarget().Options.UseSoftFloat &&
13570            !(DAG.getMachineFunction()
13571                 .getFunction()->getAttributes()
13572                 .hasAttribute(AttributeSet::FunctionIndex,
13573                               Attribute::NoImplicitFloat)) &&
13574            Subtarget->hasSSE1());
13575   }
13576
13577   // Insert VAARG_64 node into the DAG
13578   // VAARG_64 returns two values: Variable Argument Address, Chain
13579   SmallVector<SDValue, 11> InstOps;
13580   InstOps.push_back(Chain);
13581   InstOps.push_back(SrcPtr);
13582   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13583   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13584   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13585   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13586   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13587                                           VTs, InstOps, MVT::i64,
13588                                           MachinePointerInfo(SV),
13589                                           /*Align=*/0,
13590                                           /*Volatile=*/false,
13591                                           /*ReadMem=*/true,
13592                                           /*WriteMem=*/true);
13593   Chain = VAARG.getValue(1);
13594
13595   // Load the next argument and return it
13596   return DAG.getLoad(ArgVT, dl,
13597                      Chain,
13598                      VAARG,
13599                      MachinePointerInfo(),
13600                      false, false, false, 0);
13601 }
13602
13603 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13604                            SelectionDAG &DAG) {
13605   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13606   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13607   SDValue Chain = Op.getOperand(0);
13608   SDValue DstPtr = Op.getOperand(1);
13609   SDValue SrcPtr = Op.getOperand(2);
13610   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13611   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13612   SDLoc DL(Op);
13613
13614   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13615                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13616                        false,
13617                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13618 }
13619
13620 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13621 // amount is a constant. Takes immediate version of shift as input.
13622 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13623                                           SDValue SrcOp, uint64_t ShiftAmt,
13624                                           SelectionDAG &DAG) {
13625   MVT ElementType = VT.getVectorElementType();
13626
13627   // Fold this packed shift into its first operand if ShiftAmt is 0.
13628   if (ShiftAmt == 0)
13629     return SrcOp;
13630
13631   // Check for ShiftAmt >= element width
13632   if (ShiftAmt >= ElementType.getSizeInBits()) {
13633     if (Opc == X86ISD::VSRAI)
13634       ShiftAmt = ElementType.getSizeInBits() - 1;
13635     else
13636       return DAG.getConstant(0, VT);
13637   }
13638
13639   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13640          && "Unknown target vector shift-by-constant node");
13641
13642   // Fold this packed vector shift into a build vector if SrcOp is a
13643   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13644   if (VT == SrcOp.getSimpleValueType() &&
13645       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13646     SmallVector<SDValue, 8> Elts;
13647     unsigned NumElts = SrcOp->getNumOperands();
13648     ConstantSDNode *ND;
13649
13650     switch(Opc) {
13651     default: llvm_unreachable(nullptr);
13652     case X86ISD::VSHLI:
13653       for (unsigned i=0; i!=NumElts; ++i) {
13654         SDValue CurrentOp = SrcOp->getOperand(i);
13655         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13656           Elts.push_back(CurrentOp);
13657           continue;
13658         }
13659         ND = cast<ConstantSDNode>(CurrentOp);
13660         const APInt &C = ND->getAPIntValue();
13661         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13662       }
13663       break;
13664     case X86ISD::VSRLI:
13665       for (unsigned i=0; i!=NumElts; ++i) {
13666         SDValue CurrentOp = SrcOp->getOperand(i);
13667         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13668           Elts.push_back(CurrentOp);
13669           continue;
13670         }
13671         ND = cast<ConstantSDNode>(CurrentOp);
13672         const APInt &C = ND->getAPIntValue();
13673         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13674       }
13675       break;
13676     case X86ISD::VSRAI:
13677       for (unsigned i=0; i!=NumElts; ++i) {
13678         SDValue CurrentOp = SrcOp->getOperand(i);
13679         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13680           Elts.push_back(CurrentOp);
13681           continue;
13682         }
13683         ND = cast<ConstantSDNode>(CurrentOp);
13684         const APInt &C = ND->getAPIntValue();
13685         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13686       }
13687       break;
13688     }
13689
13690     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13691   }
13692
13693   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13694 }
13695
13696 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13697 // may or may not be a constant. Takes immediate version of shift as input.
13698 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13699                                    SDValue SrcOp, SDValue ShAmt,
13700                                    SelectionDAG &DAG) {
13701   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13702
13703   // Catch shift-by-constant.
13704   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13705     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13706                                       CShAmt->getZExtValue(), DAG);
13707
13708   // Change opcode to non-immediate version
13709   switch (Opc) {
13710     default: llvm_unreachable("Unknown target vector shift node");
13711     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13712     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13713     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13714   }
13715
13716   // Need to build a vector containing shift amount
13717   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13718   SDValue ShOps[4];
13719   ShOps[0] = ShAmt;
13720   ShOps[1] = DAG.getConstant(0, MVT::i32);
13721   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13722   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13723
13724   // The return type has to be a 128-bit type with the same element
13725   // type as the input type.
13726   MVT EltVT = VT.getVectorElementType();
13727   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13728
13729   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13730   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13731 }
13732
13733 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13734   SDLoc dl(Op);
13735   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13736   switch (IntNo) {
13737   default: return SDValue();    // Don't custom lower most intrinsics.
13738   // Comparison intrinsics.
13739   case Intrinsic::x86_sse_comieq_ss:
13740   case Intrinsic::x86_sse_comilt_ss:
13741   case Intrinsic::x86_sse_comile_ss:
13742   case Intrinsic::x86_sse_comigt_ss:
13743   case Intrinsic::x86_sse_comige_ss:
13744   case Intrinsic::x86_sse_comineq_ss:
13745   case Intrinsic::x86_sse_ucomieq_ss:
13746   case Intrinsic::x86_sse_ucomilt_ss:
13747   case Intrinsic::x86_sse_ucomile_ss:
13748   case Intrinsic::x86_sse_ucomigt_ss:
13749   case Intrinsic::x86_sse_ucomige_ss:
13750   case Intrinsic::x86_sse_ucomineq_ss:
13751   case Intrinsic::x86_sse2_comieq_sd:
13752   case Intrinsic::x86_sse2_comilt_sd:
13753   case Intrinsic::x86_sse2_comile_sd:
13754   case Intrinsic::x86_sse2_comigt_sd:
13755   case Intrinsic::x86_sse2_comige_sd:
13756   case Intrinsic::x86_sse2_comineq_sd:
13757   case Intrinsic::x86_sse2_ucomieq_sd:
13758   case Intrinsic::x86_sse2_ucomilt_sd:
13759   case Intrinsic::x86_sse2_ucomile_sd:
13760   case Intrinsic::x86_sse2_ucomigt_sd:
13761   case Intrinsic::x86_sse2_ucomige_sd:
13762   case Intrinsic::x86_sse2_ucomineq_sd: {
13763     unsigned Opc;
13764     ISD::CondCode CC;
13765     switch (IntNo) {
13766     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13767     case Intrinsic::x86_sse_comieq_ss:
13768     case Intrinsic::x86_sse2_comieq_sd:
13769       Opc = X86ISD::COMI;
13770       CC = ISD::SETEQ;
13771       break;
13772     case Intrinsic::x86_sse_comilt_ss:
13773     case Intrinsic::x86_sse2_comilt_sd:
13774       Opc = X86ISD::COMI;
13775       CC = ISD::SETLT;
13776       break;
13777     case Intrinsic::x86_sse_comile_ss:
13778     case Intrinsic::x86_sse2_comile_sd:
13779       Opc = X86ISD::COMI;
13780       CC = ISD::SETLE;
13781       break;
13782     case Intrinsic::x86_sse_comigt_ss:
13783     case Intrinsic::x86_sse2_comigt_sd:
13784       Opc = X86ISD::COMI;
13785       CC = ISD::SETGT;
13786       break;
13787     case Intrinsic::x86_sse_comige_ss:
13788     case Intrinsic::x86_sse2_comige_sd:
13789       Opc = X86ISD::COMI;
13790       CC = ISD::SETGE;
13791       break;
13792     case Intrinsic::x86_sse_comineq_ss:
13793     case Intrinsic::x86_sse2_comineq_sd:
13794       Opc = X86ISD::COMI;
13795       CC = ISD::SETNE;
13796       break;
13797     case Intrinsic::x86_sse_ucomieq_ss:
13798     case Intrinsic::x86_sse2_ucomieq_sd:
13799       Opc = X86ISD::UCOMI;
13800       CC = ISD::SETEQ;
13801       break;
13802     case Intrinsic::x86_sse_ucomilt_ss:
13803     case Intrinsic::x86_sse2_ucomilt_sd:
13804       Opc = X86ISD::UCOMI;
13805       CC = ISD::SETLT;
13806       break;
13807     case Intrinsic::x86_sse_ucomile_ss:
13808     case Intrinsic::x86_sse2_ucomile_sd:
13809       Opc = X86ISD::UCOMI;
13810       CC = ISD::SETLE;
13811       break;
13812     case Intrinsic::x86_sse_ucomigt_ss:
13813     case Intrinsic::x86_sse2_ucomigt_sd:
13814       Opc = X86ISD::UCOMI;
13815       CC = ISD::SETGT;
13816       break;
13817     case Intrinsic::x86_sse_ucomige_ss:
13818     case Intrinsic::x86_sse2_ucomige_sd:
13819       Opc = X86ISD::UCOMI;
13820       CC = ISD::SETGE;
13821       break;
13822     case Intrinsic::x86_sse_ucomineq_ss:
13823     case Intrinsic::x86_sse2_ucomineq_sd:
13824       Opc = X86ISD::UCOMI;
13825       CC = ISD::SETNE;
13826       break;
13827     }
13828
13829     SDValue LHS = Op.getOperand(1);
13830     SDValue RHS = Op.getOperand(2);
13831     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13832     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13833     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13834     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13835                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13836     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13837   }
13838
13839   // Arithmetic intrinsics.
13840   case Intrinsic::x86_sse2_pmulu_dq:
13841   case Intrinsic::x86_avx2_pmulu_dq:
13842     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13843                        Op.getOperand(1), Op.getOperand(2));
13844
13845   case Intrinsic::x86_sse41_pmuldq:
13846   case Intrinsic::x86_avx2_pmul_dq:
13847     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13848                        Op.getOperand(1), Op.getOperand(2));
13849
13850   case Intrinsic::x86_sse2_pmulhu_w:
13851   case Intrinsic::x86_avx2_pmulhu_w:
13852     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13853                        Op.getOperand(1), Op.getOperand(2));
13854
13855   case Intrinsic::x86_sse2_pmulh_w:
13856   case Intrinsic::x86_avx2_pmulh_w:
13857     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13858                        Op.getOperand(1), Op.getOperand(2));
13859
13860   // SSE2/AVX2 sub with unsigned saturation intrinsics
13861   case Intrinsic::x86_sse2_psubus_b:
13862   case Intrinsic::x86_sse2_psubus_w:
13863   case Intrinsic::x86_avx2_psubus_b:
13864   case Intrinsic::x86_avx2_psubus_w:
13865     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13866                        Op.getOperand(1), Op.getOperand(2));
13867
13868   // SSE3/AVX horizontal add/sub intrinsics
13869   case Intrinsic::x86_sse3_hadd_ps:
13870   case Intrinsic::x86_sse3_hadd_pd:
13871   case Intrinsic::x86_avx_hadd_ps_256:
13872   case Intrinsic::x86_avx_hadd_pd_256:
13873   case Intrinsic::x86_sse3_hsub_ps:
13874   case Intrinsic::x86_sse3_hsub_pd:
13875   case Intrinsic::x86_avx_hsub_ps_256:
13876   case Intrinsic::x86_avx_hsub_pd_256:
13877   case Intrinsic::x86_ssse3_phadd_w_128:
13878   case Intrinsic::x86_ssse3_phadd_d_128:
13879   case Intrinsic::x86_avx2_phadd_w:
13880   case Intrinsic::x86_avx2_phadd_d:
13881   case Intrinsic::x86_ssse3_phsub_w_128:
13882   case Intrinsic::x86_ssse3_phsub_d_128:
13883   case Intrinsic::x86_avx2_phsub_w:
13884   case Intrinsic::x86_avx2_phsub_d: {
13885     unsigned Opcode;
13886     switch (IntNo) {
13887     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13888     case Intrinsic::x86_sse3_hadd_ps:
13889     case Intrinsic::x86_sse3_hadd_pd:
13890     case Intrinsic::x86_avx_hadd_ps_256:
13891     case Intrinsic::x86_avx_hadd_pd_256:
13892       Opcode = X86ISD::FHADD;
13893       break;
13894     case Intrinsic::x86_sse3_hsub_ps:
13895     case Intrinsic::x86_sse3_hsub_pd:
13896     case Intrinsic::x86_avx_hsub_ps_256:
13897     case Intrinsic::x86_avx_hsub_pd_256:
13898       Opcode = X86ISD::FHSUB;
13899       break;
13900     case Intrinsic::x86_ssse3_phadd_w_128:
13901     case Intrinsic::x86_ssse3_phadd_d_128:
13902     case Intrinsic::x86_avx2_phadd_w:
13903     case Intrinsic::x86_avx2_phadd_d:
13904       Opcode = X86ISD::HADD;
13905       break;
13906     case Intrinsic::x86_ssse3_phsub_w_128:
13907     case Intrinsic::x86_ssse3_phsub_d_128:
13908     case Intrinsic::x86_avx2_phsub_w:
13909     case Intrinsic::x86_avx2_phsub_d:
13910       Opcode = X86ISD::HSUB;
13911       break;
13912     }
13913     return DAG.getNode(Opcode, dl, Op.getValueType(),
13914                        Op.getOperand(1), Op.getOperand(2));
13915   }
13916
13917   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13918   case Intrinsic::x86_sse2_pmaxu_b:
13919   case Intrinsic::x86_sse41_pmaxuw:
13920   case Intrinsic::x86_sse41_pmaxud:
13921   case Intrinsic::x86_avx2_pmaxu_b:
13922   case Intrinsic::x86_avx2_pmaxu_w:
13923   case Intrinsic::x86_avx2_pmaxu_d:
13924   case Intrinsic::x86_sse2_pminu_b:
13925   case Intrinsic::x86_sse41_pminuw:
13926   case Intrinsic::x86_sse41_pminud:
13927   case Intrinsic::x86_avx2_pminu_b:
13928   case Intrinsic::x86_avx2_pminu_w:
13929   case Intrinsic::x86_avx2_pminu_d:
13930   case Intrinsic::x86_sse41_pmaxsb:
13931   case Intrinsic::x86_sse2_pmaxs_w:
13932   case Intrinsic::x86_sse41_pmaxsd:
13933   case Intrinsic::x86_avx2_pmaxs_b:
13934   case Intrinsic::x86_avx2_pmaxs_w:
13935   case Intrinsic::x86_avx2_pmaxs_d:
13936   case Intrinsic::x86_sse41_pminsb:
13937   case Intrinsic::x86_sse2_pmins_w:
13938   case Intrinsic::x86_sse41_pminsd:
13939   case Intrinsic::x86_avx2_pmins_b:
13940   case Intrinsic::x86_avx2_pmins_w:
13941   case Intrinsic::x86_avx2_pmins_d: {
13942     unsigned Opcode;
13943     switch (IntNo) {
13944     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13945     case Intrinsic::x86_sse2_pmaxu_b:
13946     case Intrinsic::x86_sse41_pmaxuw:
13947     case Intrinsic::x86_sse41_pmaxud:
13948     case Intrinsic::x86_avx2_pmaxu_b:
13949     case Intrinsic::x86_avx2_pmaxu_w:
13950     case Intrinsic::x86_avx2_pmaxu_d:
13951       Opcode = X86ISD::UMAX;
13952       break;
13953     case Intrinsic::x86_sse2_pminu_b:
13954     case Intrinsic::x86_sse41_pminuw:
13955     case Intrinsic::x86_sse41_pminud:
13956     case Intrinsic::x86_avx2_pminu_b:
13957     case Intrinsic::x86_avx2_pminu_w:
13958     case Intrinsic::x86_avx2_pminu_d:
13959       Opcode = X86ISD::UMIN;
13960       break;
13961     case Intrinsic::x86_sse41_pmaxsb:
13962     case Intrinsic::x86_sse2_pmaxs_w:
13963     case Intrinsic::x86_sse41_pmaxsd:
13964     case Intrinsic::x86_avx2_pmaxs_b:
13965     case Intrinsic::x86_avx2_pmaxs_w:
13966     case Intrinsic::x86_avx2_pmaxs_d:
13967       Opcode = X86ISD::SMAX;
13968       break;
13969     case Intrinsic::x86_sse41_pminsb:
13970     case Intrinsic::x86_sse2_pmins_w:
13971     case Intrinsic::x86_sse41_pminsd:
13972     case Intrinsic::x86_avx2_pmins_b:
13973     case Intrinsic::x86_avx2_pmins_w:
13974     case Intrinsic::x86_avx2_pmins_d:
13975       Opcode = X86ISD::SMIN;
13976       break;
13977     }
13978     return DAG.getNode(Opcode, dl, Op.getValueType(),
13979                        Op.getOperand(1), Op.getOperand(2));
13980   }
13981
13982   // SSE/SSE2/AVX floating point max/min intrinsics.
13983   case Intrinsic::x86_sse_max_ps:
13984   case Intrinsic::x86_sse2_max_pd:
13985   case Intrinsic::x86_avx_max_ps_256:
13986   case Intrinsic::x86_avx_max_pd_256:
13987   case Intrinsic::x86_sse_min_ps:
13988   case Intrinsic::x86_sse2_min_pd:
13989   case Intrinsic::x86_avx_min_ps_256:
13990   case Intrinsic::x86_avx_min_pd_256: {
13991     unsigned Opcode;
13992     switch (IntNo) {
13993     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13994     case Intrinsic::x86_sse_max_ps:
13995     case Intrinsic::x86_sse2_max_pd:
13996     case Intrinsic::x86_avx_max_ps_256:
13997     case Intrinsic::x86_avx_max_pd_256:
13998       Opcode = X86ISD::FMAX;
13999       break;
14000     case Intrinsic::x86_sse_min_ps:
14001     case Intrinsic::x86_sse2_min_pd:
14002     case Intrinsic::x86_avx_min_ps_256:
14003     case Intrinsic::x86_avx_min_pd_256:
14004       Opcode = X86ISD::FMIN;
14005       break;
14006     }
14007     return DAG.getNode(Opcode, dl, Op.getValueType(),
14008                        Op.getOperand(1), Op.getOperand(2));
14009   }
14010
14011   // AVX2 variable shift intrinsics
14012   case Intrinsic::x86_avx2_psllv_d:
14013   case Intrinsic::x86_avx2_psllv_q:
14014   case Intrinsic::x86_avx2_psllv_d_256:
14015   case Intrinsic::x86_avx2_psllv_q_256:
14016   case Intrinsic::x86_avx2_psrlv_d:
14017   case Intrinsic::x86_avx2_psrlv_q:
14018   case Intrinsic::x86_avx2_psrlv_d_256:
14019   case Intrinsic::x86_avx2_psrlv_q_256:
14020   case Intrinsic::x86_avx2_psrav_d:
14021   case Intrinsic::x86_avx2_psrav_d_256: {
14022     unsigned Opcode;
14023     switch (IntNo) {
14024     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14025     case Intrinsic::x86_avx2_psllv_d:
14026     case Intrinsic::x86_avx2_psllv_q:
14027     case Intrinsic::x86_avx2_psllv_d_256:
14028     case Intrinsic::x86_avx2_psllv_q_256:
14029       Opcode = ISD::SHL;
14030       break;
14031     case Intrinsic::x86_avx2_psrlv_d:
14032     case Intrinsic::x86_avx2_psrlv_q:
14033     case Intrinsic::x86_avx2_psrlv_d_256:
14034     case Intrinsic::x86_avx2_psrlv_q_256:
14035       Opcode = ISD::SRL;
14036       break;
14037     case Intrinsic::x86_avx2_psrav_d:
14038     case Intrinsic::x86_avx2_psrav_d_256:
14039       Opcode = ISD::SRA;
14040       break;
14041     }
14042     return DAG.getNode(Opcode, dl, Op.getValueType(),
14043                        Op.getOperand(1), Op.getOperand(2));
14044   }
14045
14046   case Intrinsic::x86_sse2_packssdw_128:
14047   case Intrinsic::x86_sse2_packsswb_128:
14048   case Intrinsic::x86_avx2_packssdw:
14049   case Intrinsic::x86_avx2_packsswb:
14050     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14051                        Op.getOperand(1), Op.getOperand(2));
14052
14053   case Intrinsic::x86_sse2_packuswb_128:
14054   case Intrinsic::x86_sse41_packusdw:
14055   case Intrinsic::x86_avx2_packuswb:
14056   case Intrinsic::x86_avx2_packusdw:
14057     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14058                        Op.getOperand(1), Op.getOperand(2));
14059
14060   case Intrinsic::x86_ssse3_pshuf_b_128:
14061   case Intrinsic::x86_avx2_pshuf_b:
14062     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14063                        Op.getOperand(1), Op.getOperand(2));
14064
14065   case Intrinsic::x86_sse2_pshuf_d:
14066     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14067                        Op.getOperand(1), Op.getOperand(2));
14068
14069   case Intrinsic::x86_sse2_pshufl_w:
14070     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14071                        Op.getOperand(1), Op.getOperand(2));
14072
14073   case Intrinsic::x86_sse2_pshufh_w:
14074     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14075                        Op.getOperand(1), Op.getOperand(2));
14076
14077   case Intrinsic::x86_ssse3_psign_b_128:
14078   case Intrinsic::x86_ssse3_psign_w_128:
14079   case Intrinsic::x86_ssse3_psign_d_128:
14080   case Intrinsic::x86_avx2_psign_b:
14081   case Intrinsic::x86_avx2_psign_w:
14082   case Intrinsic::x86_avx2_psign_d:
14083     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14084                        Op.getOperand(1), Op.getOperand(2));
14085
14086   case Intrinsic::x86_sse41_insertps:
14087     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14088                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14089
14090   case Intrinsic::x86_avx_vperm2f128_ps_256:
14091   case Intrinsic::x86_avx_vperm2f128_pd_256:
14092   case Intrinsic::x86_avx_vperm2f128_si_256:
14093   case Intrinsic::x86_avx2_vperm2i128:
14094     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14095                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14096
14097   case Intrinsic::x86_avx2_permd:
14098   case Intrinsic::x86_avx2_permps:
14099     // Operands intentionally swapped. Mask is last operand to intrinsic,
14100     // but second operand for node/instruction.
14101     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14102                        Op.getOperand(2), Op.getOperand(1));
14103
14104   case Intrinsic::x86_sse_sqrt_ps:
14105   case Intrinsic::x86_sse2_sqrt_pd:
14106   case Intrinsic::x86_avx_sqrt_ps_256:
14107   case Intrinsic::x86_avx_sqrt_pd_256:
14108     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14109
14110   // ptest and testp intrinsics. The intrinsic these come from are designed to
14111   // return an integer value, not just an instruction so lower it to the ptest
14112   // or testp pattern and a setcc for the result.
14113   case Intrinsic::x86_sse41_ptestz:
14114   case Intrinsic::x86_sse41_ptestc:
14115   case Intrinsic::x86_sse41_ptestnzc:
14116   case Intrinsic::x86_avx_ptestz_256:
14117   case Intrinsic::x86_avx_ptestc_256:
14118   case Intrinsic::x86_avx_ptestnzc_256:
14119   case Intrinsic::x86_avx_vtestz_ps:
14120   case Intrinsic::x86_avx_vtestc_ps:
14121   case Intrinsic::x86_avx_vtestnzc_ps:
14122   case Intrinsic::x86_avx_vtestz_pd:
14123   case Intrinsic::x86_avx_vtestc_pd:
14124   case Intrinsic::x86_avx_vtestnzc_pd:
14125   case Intrinsic::x86_avx_vtestz_ps_256:
14126   case Intrinsic::x86_avx_vtestc_ps_256:
14127   case Intrinsic::x86_avx_vtestnzc_ps_256:
14128   case Intrinsic::x86_avx_vtestz_pd_256:
14129   case Intrinsic::x86_avx_vtestc_pd_256:
14130   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14131     bool IsTestPacked = false;
14132     unsigned X86CC;
14133     switch (IntNo) {
14134     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14135     case Intrinsic::x86_avx_vtestz_ps:
14136     case Intrinsic::x86_avx_vtestz_pd:
14137     case Intrinsic::x86_avx_vtestz_ps_256:
14138     case Intrinsic::x86_avx_vtestz_pd_256:
14139       IsTestPacked = true; // Fallthrough
14140     case Intrinsic::x86_sse41_ptestz:
14141     case Intrinsic::x86_avx_ptestz_256:
14142       // ZF = 1
14143       X86CC = X86::COND_E;
14144       break;
14145     case Intrinsic::x86_avx_vtestc_ps:
14146     case Intrinsic::x86_avx_vtestc_pd:
14147     case Intrinsic::x86_avx_vtestc_ps_256:
14148     case Intrinsic::x86_avx_vtestc_pd_256:
14149       IsTestPacked = true; // Fallthrough
14150     case Intrinsic::x86_sse41_ptestc:
14151     case Intrinsic::x86_avx_ptestc_256:
14152       // CF = 1
14153       X86CC = X86::COND_B;
14154       break;
14155     case Intrinsic::x86_avx_vtestnzc_ps:
14156     case Intrinsic::x86_avx_vtestnzc_pd:
14157     case Intrinsic::x86_avx_vtestnzc_ps_256:
14158     case Intrinsic::x86_avx_vtestnzc_pd_256:
14159       IsTestPacked = true; // Fallthrough
14160     case Intrinsic::x86_sse41_ptestnzc:
14161     case Intrinsic::x86_avx_ptestnzc_256:
14162       // ZF and CF = 0
14163       X86CC = X86::COND_A;
14164       break;
14165     }
14166
14167     SDValue LHS = Op.getOperand(1);
14168     SDValue RHS = Op.getOperand(2);
14169     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14170     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14171     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14172     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14173     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14174   }
14175   case Intrinsic::x86_avx512_kortestz_w:
14176   case Intrinsic::x86_avx512_kortestc_w: {
14177     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14178     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14179     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14180     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14181     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14182     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14183     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14184   }
14185
14186   // SSE/AVX shift intrinsics
14187   case Intrinsic::x86_sse2_psll_w:
14188   case Intrinsic::x86_sse2_psll_d:
14189   case Intrinsic::x86_sse2_psll_q:
14190   case Intrinsic::x86_avx2_psll_w:
14191   case Intrinsic::x86_avx2_psll_d:
14192   case Intrinsic::x86_avx2_psll_q:
14193   case Intrinsic::x86_sse2_psrl_w:
14194   case Intrinsic::x86_sse2_psrl_d:
14195   case Intrinsic::x86_sse2_psrl_q:
14196   case Intrinsic::x86_avx2_psrl_w:
14197   case Intrinsic::x86_avx2_psrl_d:
14198   case Intrinsic::x86_avx2_psrl_q:
14199   case Intrinsic::x86_sse2_psra_w:
14200   case Intrinsic::x86_sse2_psra_d:
14201   case Intrinsic::x86_avx2_psra_w:
14202   case Intrinsic::x86_avx2_psra_d: {
14203     unsigned Opcode;
14204     switch (IntNo) {
14205     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14206     case Intrinsic::x86_sse2_psll_w:
14207     case Intrinsic::x86_sse2_psll_d:
14208     case Intrinsic::x86_sse2_psll_q:
14209     case Intrinsic::x86_avx2_psll_w:
14210     case Intrinsic::x86_avx2_psll_d:
14211     case Intrinsic::x86_avx2_psll_q:
14212       Opcode = X86ISD::VSHL;
14213       break;
14214     case Intrinsic::x86_sse2_psrl_w:
14215     case Intrinsic::x86_sse2_psrl_d:
14216     case Intrinsic::x86_sse2_psrl_q:
14217     case Intrinsic::x86_avx2_psrl_w:
14218     case Intrinsic::x86_avx2_psrl_d:
14219     case Intrinsic::x86_avx2_psrl_q:
14220       Opcode = X86ISD::VSRL;
14221       break;
14222     case Intrinsic::x86_sse2_psra_w:
14223     case Intrinsic::x86_sse2_psra_d:
14224     case Intrinsic::x86_avx2_psra_w:
14225     case Intrinsic::x86_avx2_psra_d:
14226       Opcode = X86ISD::VSRA;
14227       break;
14228     }
14229     return DAG.getNode(Opcode, dl, Op.getValueType(),
14230                        Op.getOperand(1), Op.getOperand(2));
14231   }
14232
14233   // SSE/AVX immediate shift intrinsics
14234   case Intrinsic::x86_sse2_pslli_w:
14235   case Intrinsic::x86_sse2_pslli_d:
14236   case Intrinsic::x86_sse2_pslli_q:
14237   case Intrinsic::x86_avx2_pslli_w:
14238   case Intrinsic::x86_avx2_pslli_d:
14239   case Intrinsic::x86_avx2_pslli_q:
14240   case Intrinsic::x86_sse2_psrli_w:
14241   case Intrinsic::x86_sse2_psrli_d:
14242   case Intrinsic::x86_sse2_psrli_q:
14243   case Intrinsic::x86_avx2_psrli_w:
14244   case Intrinsic::x86_avx2_psrli_d:
14245   case Intrinsic::x86_avx2_psrli_q:
14246   case Intrinsic::x86_sse2_psrai_w:
14247   case Intrinsic::x86_sse2_psrai_d:
14248   case Intrinsic::x86_avx2_psrai_w:
14249   case Intrinsic::x86_avx2_psrai_d: {
14250     unsigned Opcode;
14251     switch (IntNo) {
14252     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14253     case Intrinsic::x86_sse2_pslli_w:
14254     case Intrinsic::x86_sse2_pslli_d:
14255     case Intrinsic::x86_sse2_pslli_q:
14256     case Intrinsic::x86_avx2_pslli_w:
14257     case Intrinsic::x86_avx2_pslli_d:
14258     case Intrinsic::x86_avx2_pslli_q:
14259       Opcode = X86ISD::VSHLI;
14260       break;
14261     case Intrinsic::x86_sse2_psrli_w:
14262     case Intrinsic::x86_sse2_psrli_d:
14263     case Intrinsic::x86_sse2_psrli_q:
14264     case Intrinsic::x86_avx2_psrli_w:
14265     case Intrinsic::x86_avx2_psrli_d:
14266     case Intrinsic::x86_avx2_psrli_q:
14267       Opcode = X86ISD::VSRLI;
14268       break;
14269     case Intrinsic::x86_sse2_psrai_w:
14270     case Intrinsic::x86_sse2_psrai_d:
14271     case Intrinsic::x86_avx2_psrai_w:
14272     case Intrinsic::x86_avx2_psrai_d:
14273       Opcode = X86ISD::VSRAI;
14274       break;
14275     }
14276     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14277                                Op.getOperand(1), Op.getOperand(2), DAG);
14278   }
14279
14280   case Intrinsic::x86_sse42_pcmpistria128:
14281   case Intrinsic::x86_sse42_pcmpestria128:
14282   case Intrinsic::x86_sse42_pcmpistric128:
14283   case Intrinsic::x86_sse42_pcmpestric128:
14284   case Intrinsic::x86_sse42_pcmpistrio128:
14285   case Intrinsic::x86_sse42_pcmpestrio128:
14286   case Intrinsic::x86_sse42_pcmpistris128:
14287   case Intrinsic::x86_sse42_pcmpestris128:
14288   case Intrinsic::x86_sse42_pcmpistriz128:
14289   case Intrinsic::x86_sse42_pcmpestriz128: {
14290     unsigned Opcode;
14291     unsigned X86CC;
14292     switch (IntNo) {
14293     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14294     case Intrinsic::x86_sse42_pcmpistria128:
14295       Opcode = X86ISD::PCMPISTRI;
14296       X86CC = X86::COND_A;
14297       break;
14298     case Intrinsic::x86_sse42_pcmpestria128:
14299       Opcode = X86ISD::PCMPESTRI;
14300       X86CC = X86::COND_A;
14301       break;
14302     case Intrinsic::x86_sse42_pcmpistric128:
14303       Opcode = X86ISD::PCMPISTRI;
14304       X86CC = X86::COND_B;
14305       break;
14306     case Intrinsic::x86_sse42_pcmpestric128:
14307       Opcode = X86ISD::PCMPESTRI;
14308       X86CC = X86::COND_B;
14309       break;
14310     case Intrinsic::x86_sse42_pcmpistrio128:
14311       Opcode = X86ISD::PCMPISTRI;
14312       X86CC = X86::COND_O;
14313       break;
14314     case Intrinsic::x86_sse42_pcmpestrio128:
14315       Opcode = X86ISD::PCMPESTRI;
14316       X86CC = X86::COND_O;
14317       break;
14318     case Intrinsic::x86_sse42_pcmpistris128:
14319       Opcode = X86ISD::PCMPISTRI;
14320       X86CC = X86::COND_S;
14321       break;
14322     case Intrinsic::x86_sse42_pcmpestris128:
14323       Opcode = X86ISD::PCMPESTRI;
14324       X86CC = X86::COND_S;
14325       break;
14326     case Intrinsic::x86_sse42_pcmpistriz128:
14327       Opcode = X86ISD::PCMPISTRI;
14328       X86CC = X86::COND_E;
14329       break;
14330     case Intrinsic::x86_sse42_pcmpestriz128:
14331       Opcode = X86ISD::PCMPESTRI;
14332       X86CC = X86::COND_E;
14333       break;
14334     }
14335     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14336     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14337     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14338     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14339                                 DAG.getConstant(X86CC, MVT::i8),
14340                                 SDValue(PCMP.getNode(), 1));
14341     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14342   }
14343
14344   case Intrinsic::x86_sse42_pcmpistri128:
14345   case Intrinsic::x86_sse42_pcmpestri128: {
14346     unsigned Opcode;
14347     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14348       Opcode = X86ISD::PCMPISTRI;
14349     else
14350       Opcode = X86ISD::PCMPESTRI;
14351
14352     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14353     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14354     return DAG.getNode(Opcode, dl, VTs, NewOps);
14355   }
14356   case Intrinsic::x86_fma_vfmadd_ps:
14357   case Intrinsic::x86_fma_vfmadd_pd:
14358   case Intrinsic::x86_fma_vfmsub_ps:
14359   case Intrinsic::x86_fma_vfmsub_pd:
14360   case Intrinsic::x86_fma_vfnmadd_ps:
14361   case Intrinsic::x86_fma_vfnmadd_pd:
14362   case Intrinsic::x86_fma_vfnmsub_ps:
14363   case Intrinsic::x86_fma_vfnmsub_pd:
14364   case Intrinsic::x86_fma_vfmaddsub_ps:
14365   case Intrinsic::x86_fma_vfmaddsub_pd:
14366   case Intrinsic::x86_fma_vfmsubadd_ps:
14367   case Intrinsic::x86_fma_vfmsubadd_pd:
14368   case Intrinsic::x86_fma_vfmadd_ps_256:
14369   case Intrinsic::x86_fma_vfmadd_pd_256:
14370   case Intrinsic::x86_fma_vfmsub_ps_256:
14371   case Intrinsic::x86_fma_vfmsub_pd_256:
14372   case Intrinsic::x86_fma_vfnmadd_ps_256:
14373   case Intrinsic::x86_fma_vfnmadd_pd_256:
14374   case Intrinsic::x86_fma_vfnmsub_ps_256:
14375   case Intrinsic::x86_fma_vfnmsub_pd_256:
14376   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14377   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14378   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14379   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14380   case Intrinsic::x86_fma_vfmadd_ps_512:
14381   case Intrinsic::x86_fma_vfmadd_pd_512:
14382   case Intrinsic::x86_fma_vfmsub_ps_512:
14383   case Intrinsic::x86_fma_vfmsub_pd_512:
14384   case Intrinsic::x86_fma_vfnmadd_ps_512:
14385   case Intrinsic::x86_fma_vfnmadd_pd_512:
14386   case Intrinsic::x86_fma_vfnmsub_ps_512:
14387   case Intrinsic::x86_fma_vfnmsub_pd_512:
14388   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14389   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14390   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14391   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14392     unsigned Opc;
14393     switch (IntNo) {
14394     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14395     case Intrinsic::x86_fma_vfmadd_ps:
14396     case Intrinsic::x86_fma_vfmadd_pd:
14397     case Intrinsic::x86_fma_vfmadd_ps_256:
14398     case Intrinsic::x86_fma_vfmadd_pd_256:
14399     case Intrinsic::x86_fma_vfmadd_ps_512:
14400     case Intrinsic::x86_fma_vfmadd_pd_512:
14401       Opc = X86ISD::FMADD;
14402       break;
14403     case Intrinsic::x86_fma_vfmsub_ps:
14404     case Intrinsic::x86_fma_vfmsub_pd:
14405     case Intrinsic::x86_fma_vfmsub_ps_256:
14406     case Intrinsic::x86_fma_vfmsub_pd_256:
14407     case Intrinsic::x86_fma_vfmsub_ps_512:
14408     case Intrinsic::x86_fma_vfmsub_pd_512:
14409       Opc = X86ISD::FMSUB;
14410       break;
14411     case Intrinsic::x86_fma_vfnmadd_ps:
14412     case Intrinsic::x86_fma_vfnmadd_pd:
14413     case Intrinsic::x86_fma_vfnmadd_ps_256:
14414     case Intrinsic::x86_fma_vfnmadd_pd_256:
14415     case Intrinsic::x86_fma_vfnmadd_ps_512:
14416     case Intrinsic::x86_fma_vfnmadd_pd_512:
14417       Opc = X86ISD::FNMADD;
14418       break;
14419     case Intrinsic::x86_fma_vfnmsub_ps:
14420     case Intrinsic::x86_fma_vfnmsub_pd:
14421     case Intrinsic::x86_fma_vfnmsub_ps_256:
14422     case Intrinsic::x86_fma_vfnmsub_pd_256:
14423     case Intrinsic::x86_fma_vfnmsub_ps_512:
14424     case Intrinsic::x86_fma_vfnmsub_pd_512:
14425       Opc = X86ISD::FNMSUB;
14426       break;
14427     case Intrinsic::x86_fma_vfmaddsub_ps:
14428     case Intrinsic::x86_fma_vfmaddsub_pd:
14429     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14430     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14431     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14432     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14433       Opc = X86ISD::FMADDSUB;
14434       break;
14435     case Intrinsic::x86_fma_vfmsubadd_ps:
14436     case Intrinsic::x86_fma_vfmsubadd_pd:
14437     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14438     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14439     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14440     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14441       Opc = X86ISD::FMSUBADD;
14442       break;
14443     }
14444
14445     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14446                        Op.getOperand(2), Op.getOperand(3));
14447   }
14448   }
14449 }
14450
14451 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14452                               SDValue Src, SDValue Mask, SDValue Base,
14453                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14454                               const X86Subtarget * Subtarget) {
14455   SDLoc dl(Op);
14456   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14457   assert(C && "Invalid scale type");
14458   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14459   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14460                              Index.getSimpleValueType().getVectorNumElements());
14461   SDValue MaskInReg;
14462   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14463   if (MaskC)
14464     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14465   else
14466     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14467   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14468   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14469   SDValue Segment = DAG.getRegister(0, MVT::i32);
14470   if (Src.getOpcode() == ISD::UNDEF)
14471     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14472   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14473   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14474   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14475   return DAG.getMergeValues(RetOps, dl);
14476 }
14477
14478 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14479                                SDValue Src, SDValue Mask, SDValue Base,
14480                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14481   SDLoc dl(Op);
14482   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14483   assert(C && "Invalid scale type");
14484   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14485   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14486   SDValue Segment = DAG.getRegister(0, MVT::i32);
14487   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14488                              Index.getSimpleValueType().getVectorNumElements());
14489   SDValue MaskInReg;
14490   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14491   if (MaskC)
14492     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14493   else
14494     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14495   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14496   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14497   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14498   return SDValue(Res, 1);
14499 }
14500
14501 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14502                                SDValue Mask, SDValue Base, SDValue Index,
14503                                SDValue ScaleOp, SDValue Chain) {
14504   SDLoc dl(Op);
14505   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14506   assert(C && "Invalid scale type");
14507   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14508   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14509   SDValue Segment = DAG.getRegister(0, MVT::i32);
14510   EVT MaskVT =
14511     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14512   SDValue MaskInReg;
14513   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14514   if (MaskC)
14515     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14516   else
14517     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14518   //SDVTList VTs = DAG.getVTList(MVT::Other);
14519   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14520   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14521   return SDValue(Res, 0);
14522 }
14523
14524 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14525 // read performance monitor counters (x86_rdpmc).
14526 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14527                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14528                               SmallVectorImpl<SDValue> &Results) {
14529   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14530   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14531   SDValue LO, HI;
14532
14533   // The ECX register is used to select the index of the performance counter
14534   // to read.
14535   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14536                                    N->getOperand(2));
14537   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14538
14539   // Reads the content of a 64-bit performance counter and returns it in the
14540   // registers EDX:EAX.
14541   if (Subtarget->is64Bit()) {
14542     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14543     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14544                             LO.getValue(2));
14545   } else {
14546     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14547     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14548                             LO.getValue(2));
14549   }
14550   Chain = HI.getValue(1);
14551
14552   if (Subtarget->is64Bit()) {
14553     // The EAX register is loaded with the low-order 32 bits. The EDX register
14554     // is loaded with the supported high-order bits of the counter.
14555     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14556                               DAG.getConstant(32, MVT::i8));
14557     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14558     Results.push_back(Chain);
14559     return;
14560   }
14561
14562   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14563   SDValue Ops[] = { LO, HI };
14564   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14565   Results.push_back(Pair);
14566   Results.push_back(Chain);
14567 }
14568
14569 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14570 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14571 // also used to custom lower READCYCLECOUNTER nodes.
14572 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14573                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14574                               SmallVectorImpl<SDValue> &Results) {
14575   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14576   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14577   SDValue LO, HI;
14578
14579   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14580   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14581   // and the EAX register is loaded with the low-order 32 bits.
14582   if (Subtarget->is64Bit()) {
14583     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14584     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14585                             LO.getValue(2));
14586   } else {
14587     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14588     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14589                             LO.getValue(2));
14590   }
14591   SDValue Chain = HI.getValue(1);
14592
14593   if (Opcode == X86ISD::RDTSCP_DAG) {
14594     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14595
14596     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14597     // the ECX register. Add 'ecx' explicitly to the chain.
14598     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14599                                      HI.getValue(2));
14600     // Explicitly store the content of ECX at the location passed in input
14601     // to the 'rdtscp' intrinsic.
14602     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14603                          MachinePointerInfo(), false, false, 0);
14604   }
14605
14606   if (Subtarget->is64Bit()) {
14607     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14608     // the EAX register is loaded with the low-order 32 bits.
14609     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14610                               DAG.getConstant(32, MVT::i8));
14611     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14612     Results.push_back(Chain);
14613     return;
14614   }
14615
14616   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14617   SDValue Ops[] = { LO, HI };
14618   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14619   Results.push_back(Pair);
14620   Results.push_back(Chain);
14621 }
14622
14623 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14624                                      SelectionDAG &DAG) {
14625   SmallVector<SDValue, 2> Results;
14626   SDLoc DL(Op);
14627   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14628                           Results);
14629   return DAG.getMergeValues(Results, DL);
14630 }
14631
14632 enum IntrinsicType {
14633   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14634 };
14635
14636 struct IntrinsicData {
14637   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14638     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14639   IntrinsicType Type;
14640   unsigned      Opc0;
14641   unsigned      Opc1;
14642 };
14643
14644 std::map < unsigned, IntrinsicData> IntrMap;
14645 static void InitIntinsicsMap() {
14646   static bool Initialized = false;
14647   if (Initialized) 
14648     return;
14649   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14650                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14651   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14652                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14653   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14654                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14655   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14656                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14657   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14658                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14659   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14660                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14661   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14662                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14663   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14664                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14665   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14666                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14667
14668   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14669                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14670   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14671                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14672   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14673                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14674   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14675                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14676   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14677                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14678   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14679                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14680   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14681                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14682   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14683                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14684    
14685   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14686                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14687                                                         X86::VGATHERPF1QPSm)));
14688   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14689                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14690                                                         X86::VGATHERPF1QPDm)));
14691   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14692                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14693                                                         X86::VGATHERPF1DPDm)));
14694   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14695                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14696                                                         X86::VGATHERPF1DPSm)));
14697   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14698                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14699                                                         X86::VSCATTERPF1QPSm)));
14700   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14701                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14702                                                         X86::VSCATTERPF1QPDm)));
14703   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14704                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14705                                                         X86::VSCATTERPF1DPDm)));
14706   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14707                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14708                                                         X86::VSCATTERPF1DPSm)));
14709   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14710                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14711   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14712                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14713   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14714                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14715   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14716                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14717   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14718                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14719   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14720                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14721   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14722                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14723   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14724                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14725   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14726                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14727   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14728                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14729   Initialized = true;
14730 }
14731
14732 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14733                                       SelectionDAG &DAG) {
14734   InitIntinsicsMap();
14735   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14736   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14737   if (itr == IntrMap.end())
14738     return SDValue();
14739
14740   SDLoc dl(Op);
14741   IntrinsicData Intr = itr->second;
14742   switch(Intr.Type) {
14743   case RDSEED:
14744   case RDRAND: {
14745     // Emit the node with the right value type.
14746     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14747     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14748
14749     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14750     // Otherwise return the value from Rand, which is always 0, casted to i32.
14751     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14752                       DAG.getConstant(1, Op->getValueType(1)),
14753                       DAG.getConstant(X86::COND_B, MVT::i32),
14754                       SDValue(Result.getNode(), 1) };
14755     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14756                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14757                                   Ops);
14758
14759     // Return { result, isValid, chain }.
14760     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14761                        SDValue(Result.getNode(), 2));
14762   }
14763   case GATHER: {
14764   //gather(v1, mask, index, base, scale);
14765     SDValue Chain = Op.getOperand(0);
14766     SDValue Src   = Op.getOperand(2);
14767     SDValue Base  = Op.getOperand(3);
14768     SDValue Index = Op.getOperand(4);
14769     SDValue Mask  = Op.getOperand(5);
14770     SDValue Scale = Op.getOperand(6);
14771     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14772                           Subtarget);
14773   }
14774   case SCATTER: {
14775   //scatter(base, mask, index, v1, scale);
14776     SDValue Chain = Op.getOperand(0);
14777     SDValue Base  = Op.getOperand(2);
14778     SDValue Mask  = Op.getOperand(3);
14779     SDValue Index = Op.getOperand(4);
14780     SDValue Src   = Op.getOperand(5);
14781     SDValue Scale = Op.getOperand(6);
14782     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14783   }
14784   case PREFETCH: {
14785     SDValue Hint = Op.getOperand(6);
14786     unsigned HintVal;
14787     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14788         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14789       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14790     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14791     SDValue Chain = Op.getOperand(0);
14792     SDValue Mask  = Op.getOperand(2);
14793     SDValue Index = Op.getOperand(3);
14794     SDValue Base  = Op.getOperand(4);
14795     SDValue Scale = Op.getOperand(5);
14796     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14797   }
14798   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14799   case RDTSC: {
14800     SmallVector<SDValue, 2> Results;
14801     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14802     return DAG.getMergeValues(Results, dl);
14803   }
14804   // Read Performance Monitoring Counters.
14805   case RDPMC: {
14806     SmallVector<SDValue, 2> Results;
14807     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14808     return DAG.getMergeValues(Results, dl);
14809   }
14810   // XTEST intrinsics.
14811   case XTEST: {
14812     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14813     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14814     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14815                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14816                                 InTrans);
14817     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14818     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14819                        Ret, SDValue(InTrans.getNode(), 1));
14820   }
14821   }
14822   llvm_unreachable("Unknown Intrinsic Type");
14823 }
14824
14825 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14826                                            SelectionDAG &DAG) const {
14827   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14828   MFI->setReturnAddressIsTaken(true);
14829
14830   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14831     return SDValue();
14832
14833   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14834   SDLoc dl(Op);
14835   EVT PtrVT = getPointerTy();
14836
14837   if (Depth > 0) {
14838     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14839     const X86RegisterInfo *RegInfo =
14840       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14841     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14842     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14843                        DAG.getNode(ISD::ADD, dl, PtrVT,
14844                                    FrameAddr, Offset),
14845                        MachinePointerInfo(), false, false, false, 0);
14846   }
14847
14848   // Just load the return address.
14849   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14850   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14851                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14852 }
14853
14854 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14855   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14856   MFI->setFrameAddressIsTaken(true);
14857
14858   EVT VT = Op.getValueType();
14859   SDLoc dl(Op);  // FIXME probably not meaningful
14860   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14861   const X86RegisterInfo *RegInfo =
14862     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14863   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14864   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14865           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14866          "Invalid Frame Register!");
14867   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14868   while (Depth--)
14869     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14870                             MachinePointerInfo(),
14871                             false, false, false, 0);
14872   return FrameAddr;
14873 }
14874
14875 // FIXME? Maybe this could be a TableGen attribute on some registers and
14876 // this table could be generated automatically from RegInfo.
14877 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14878                                               EVT VT) const {
14879   unsigned Reg = StringSwitch<unsigned>(RegName)
14880                        .Case("esp", X86::ESP)
14881                        .Case("rsp", X86::RSP)
14882                        .Default(0);
14883   if (Reg)
14884     return Reg;
14885   report_fatal_error("Invalid register name global variable");
14886 }
14887
14888 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14889                                                      SelectionDAG &DAG) const {
14890   const X86RegisterInfo *RegInfo =
14891     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14892   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14893 }
14894
14895 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14896   SDValue Chain     = Op.getOperand(0);
14897   SDValue Offset    = Op.getOperand(1);
14898   SDValue Handler   = Op.getOperand(2);
14899   SDLoc dl      (Op);
14900
14901   EVT PtrVT = getPointerTy();
14902   const X86RegisterInfo *RegInfo =
14903     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14904   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14905   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14906           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14907          "Invalid Frame Register!");
14908   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14909   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14910
14911   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14912                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14913   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14914   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14915                        false, false, 0);
14916   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14917
14918   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14919                      DAG.getRegister(StoreAddrReg, PtrVT));
14920 }
14921
14922 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14923                                                SelectionDAG &DAG) const {
14924   SDLoc DL(Op);
14925   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14926                      DAG.getVTList(MVT::i32, MVT::Other),
14927                      Op.getOperand(0), Op.getOperand(1));
14928 }
14929
14930 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14931                                                 SelectionDAG &DAG) const {
14932   SDLoc DL(Op);
14933   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14934                      Op.getOperand(0), Op.getOperand(1));
14935 }
14936
14937 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14938   return Op.getOperand(0);
14939 }
14940
14941 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14942                                                 SelectionDAG &DAG) const {
14943   SDValue Root = Op.getOperand(0);
14944   SDValue Trmp = Op.getOperand(1); // trampoline
14945   SDValue FPtr = Op.getOperand(2); // nested function
14946   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14947   SDLoc dl (Op);
14948
14949   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14950   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14951
14952   if (Subtarget->is64Bit()) {
14953     SDValue OutChains[6];
14954
14955     // Large code-model.
14956     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14957     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14958
14959     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14960     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14961
14962     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14963
14964     // Load the pointer to the nested function into R11.
14965     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14966     SDValue Addr = Trmp;
14967     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14968                                 Addr, MachinePointerInfo(TrmpAddr),
14969                                 false, false, 0);
14970
14971     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14972                        DAG.getConstant(2, MVT::i64));
14973     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14974                                 MachinePointerInfo(TrmpAddr, 2),
14975                                 false, false, 2);
14976
14977     // Load the 'nest' parameter value into R10.
14978     // R10 is specified in X86CallingConv.td
14979     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14980     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14981                        DAG.getConstant(10, MVT::i64));
14982     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14983                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14984                                 false, false, 0);
14985
14986     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14987                        DAG.getConstant(12, MVT::i64));
14988     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14989                                 MachinePointerInfo(TrmpAddr, 12),
14990                                 false, false, 2);
14991
14992     // Jump to the nested function.
14993     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14994     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14995                        DAG.getConstant(20, MVT::i64));
14996     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14997                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14998                                 false, false, 0);
14999
15000     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15001     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15002                        DAG.getConstant(22, MVT::i64));
15003     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15004                                 MachinePointerInfo(TrmpAddr, 22),
15005                                 false, false, 0);
15006
15007     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15008   } else {
15009     const Function *Func =
15010       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15011     CallingConv::ID CC = Func->getCallingConv();
15012     unsigned NestReg;
15013
15014     switch (CC) {
15015     default:
15016       llvm_unreachable("Unsupported calling convention");
15017     case CallingConv::C:
15018     case CallingConv::X86_StdCall: {
15019       // Pass 'nest' parameter in ECX.
15020       // Must be kept in sync with X86CallingConv.td
15021       NestReg = X86::ECX;
15022
15023       // Check that ECX wasn't needed by an 'inreg' parameter.
15024       FunctionType *FTy = Func->getFunctionType();
15025       const AttributeSet &Attrs = Func->getAttributes();
15026
15027       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15028         unsigned InRegCount = 0;
15029         unsigned Idx = 1;
15030
15031         for (FunctionType::param_iterator I = FTy->param_begin(),
15032              E = FTy->param_end(); I != E; ++I, ++Idx)
15033           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15034             // FIXME: should only count parameters that are lowered to integers.
15035             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15036
15037         if (InRegCount > 2) {
15038           report_fatal_error("Nest register in use - reduce number of inreg"
15039                              " parameters!");
15040         }
15041       }
15042       break;
15043     }
15044     case CallingConv::X86_FastCall:
15045     case CallingConv::X86_ThisCall:
15046     case CallingConv::Fast:
15047       // Pass 'nest' parameter in EAX.
15048       // Must be kept in sync with X86CallingConv.td
15049       NestReg = X86::EAX;
15050       break;
15051     }
15052
15053     SDValue OutChains[4];
15054     SDValue Addr, Disp;
15055
15056     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15057                        DAG.getConstant(10, MVT::i32));
15058     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15059
15060     // This is storing the opcode for MOV32ri.
15061     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15062     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15063     OutChains[0] = DAG.getStore(Root, dl,
15064                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15065                                 Trmp, MachinePointerInfo(TrmpAddr),
15066                                 false, false, 0);
15067
15068     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15069                        DAG.getConstant(1, MVT::i32));
15070     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15071                                 MachinePointerInfo(TrmpAddr, 1),
15072                                 false, false, 1);
15073
15074     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15075     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15076                        DAG.getConstant(5, MVT::i32));
15077     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15078                                 MachinePointerInfo(TrmpAddr, 5),
15079                                 false, false, 1);
15080
15081     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15082                        DAG.getConstant(6, MVT::i32));
15083     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15084                                 MachinePointerInfo(TrmpAddr, 6),
15085                                 false, false, 1);
15086
15087     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15088   }
15089 }
15090
15091 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15092                                             SelectionDAG &DAG) const {
15093   /*
15094    The rounding mode is in bits 11:10 of FPSR, and has the following
15095    settings:
15096      00 Round to nearest
15097      01 Round to -inf
15098      10 Round to +inf
15099      11 Round to 0
15100
15101   FLT_ROUNDS, on the other hand, expects the following:
15102     -1 Undefined
15103      0 Round to 0
15104      1 Round to nearest
15105      2 Round to +inf
15106      3 Round to -inf
15107
15108   To perform the conversion, we do:
15109     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15110   */
15111
15112   MachineFunction &MF = DAG.getMachineFunction();
15113   const TargetMachine &TM = MF.getTarget();
15114   const TargetFrameLowering &TFI = *TM.getFrameLowering();
15115   unsigned StackAlignment = TFI.getStackAlignment();
15116   MVT VT = Op.getSimpleValueType();
15117   SDLoc DL(Op);
15118
15119   // Save FP Control Word to stack slot
15120   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15121   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15122
15123   MachineMemOperand *MMO =
15124    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15125                            MachineMemOperand::MOStore, 2, 2);
15126
15127   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15128   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15129                                           DAG.getVTList(MVT::Other),
15130                                           Ops, MVT::i16, MMO);
15131
15132   // Load FP Control Word from stack slot
15133   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15134                             MachinePointerInfo(), false, false, false, 0);
15135
15136   // Transform as necessary
15137   SDValue CWD1 =
15138     DAG.getNode(ISD::SRL, DL, MVT::i16,
15139                 DAG.getNode(ISD::AND, DL, MVT::i16,
15140                             CWD, DAG.getConstant(0x800, MVT::i16)),
15141                 DAG.getConstant(11, MVT::i8));
15142   SDValue CWD2 =
15143     DAG.getNode(ISD::SRL, DL, MVT::i16,
15144                 DAG.getNode(ISD::AND, DL, MVT::i16,
15145                             CWD, DAG.getConstant(0x400, MVT::i16)),
15146                 DAG.getConstant(9, MVT::i8));
15147
15148   SDValue RetVal =
15149     DAG.getNode(ISD::AND, DL, MVT::i16,
15150                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15151                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15152                             DAG.getConstant(1, MVT::i16)),
15153                 DAG.getConstant(3, MVT::i16));
15154
15155   return DAG.getNode((VT.getSizeInBits() < 16 ?
15156                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15157 }
15158
15159 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15160   MVT VT = Op.getSimpleValueType();
15161   EVT OpVT = VT;
15162   unsigned NumBits = VT.getSizeInBits();
15163   SDLoc dl(Op);
15164
15165   Op = Op.getOperand(0);
15166   if (VT == MVT::i8) {
15167     // Zero extend to i32 since there is not an i8 bsr.
15168     OpVT = MVT::i32;
15169     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15170   }
15171
15172   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15173   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15174   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15175
15176   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15177   SDValue Ops[] = {
15178     Op,
15179     DAG.getConstant(NumBits+NumBits-1, OpVT),
15180     DAG.getConstant(X86::COND_E, MVT::i8),
15181     Op.getValue(1)
15182   };
15183   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15184
15185   // Finally xor with NumBits-1.
15186   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15187
15188   if (VT == MVT::i8)
15189     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15190   return Op;
15191 }
15192
15193 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15194   MVT VT = Op.getSimpleValueType();
15195   EVT OpVT = VT;
15196   unsigned NumBits = VT.getSizeInBits();
15197   SDLoc dl(Op);
15198
15199   Op = Op.getOperand(0);
15200   if (VT == MVT::i8) {
15201     // Zero extend to i32 since there is not an i8 bsr.
15202     OpVT = MVT::i32;
15203     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15204   }
15205
15206   // Issue a bsr (scan bits in reverse).
15207   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15208   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15209
15210   // And xor with NumBits-1.
15211   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15212
15213   if (VT == MVT::i8)
15214     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15215   return Op;
15216 }
15217
15218 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15219   MVT VT = Op.getSimpleValueType();
15220   unsigned NumBits = VT.getSizeInBits();
15221   SDLoc dl(Op);
15222   Op = Op.getOperand(0);
15223
15224   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15225   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15226   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15227
15228   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15229   SDValue Ops[] = {
15230     Op,
15231     DAG.getConstant(NumBits, VT),
15232     DAG.getConstant(X86::COND_E, MVT::i8),
15233     Op.getValue(1)
15234   };
15235   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15236 }
15237
15238 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15239 // ones, and then concatenate the result back.
15240 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15241   MVT VT = Op.getSimpleValueType();
15242
15243   assert(VT.is256BitVector() && VT.isInteger() &&
15244          "Unsupported value type for operation");
15245
15246   unsigned NumElems = VT.getVectorNumElements();
15247   SDLoc dl(Op);
15248
15249   // Extract the LHS vectors
15250   SDValue LHS = Op.getOperand(0);
15251   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15252   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15253
15254   // Extract the RHS vectors
15255   SDValue RHS = Op.getOperand(1);
15256   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15257   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15258
15259   MVT EltVT = VT.getVectorElementType();
15260   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15261
15262   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15263                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15264                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15265 }
15266
15267 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15268   assert(Op.getSimpleValueType().is256BitVector() &&
15269          Op.getSimpleValueType().isInteger() &&
15270          "Only handle AVX 256-bit vector integer operation");
15271   return Lower256IntArith(Op, DAG);
15272 }
15273
15274 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15275   assert(Op.getSimpleValueType().is256BitVector() &&
15276          Op.getSimpleValueType().isInteger() &&
15277          "Only handle AVX 256-bit vector integer operation");
15278   return Lower256IntArith(Op, DAG);
15279 }
15280
15281 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15282                         SelectionDAG &DAG) {
15283   SDLoc dl(Op);
15284   MVT VT = Op.getSimpleValueType();
15285
15286   // Decompose 256-bit ops into smaller 128-bit ops.
15287   if (VT.is256BitVector() && !Subtarget->hasInt256())
15288     return Lower256IntArith(Op, DAG);
15289
15290   SDValue A = Op.getOperand(0);
15291   SDValue B = Op.getOperand(1);
15292
15293   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15294   if (VT == MVT::v4i32) {
15295     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15296            "Should not custom lower when pmuldq is available!");
15297
15298     // Extract the odd parts.
15299     static const int UnpackMask[] = { 1, -1, 3, -1 };
15300     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15301     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15302
15303     // Multiply the even parts.
15304     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15305     // Now multiply odd parts.
15306     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15307
15308     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15309     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15310
15311     // Merge the two vectors back together with a shuffle. This expands into 2
15312     // shuffles.
15313     static const int ShufMask[] = { 0, 4, 2, 6 };
15314     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15315   }
15316
15317   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15318          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15319
15320   //  Ahi = psrlqi(a, 32);
15321   //  Bhi = psrlqi(b, 32);
15322   //
15323   //  AloBlo = pmuludq(a, b);
15324   //  AloBhi = pmuludq(a, Bhi);
15325   //  AhiBlo = pmuludq(Ahi, b);
15326
15327   //  AloBhi = psllqi(AloBhi, 32);
15328   //  AhiBlo = psllqi(AhiBlo, 32);
15329   //  return AloBlo + AloBhi + AhiBlo;
15330
15331   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15332   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15333
15334   // Bit cast to 32-bit vectors for MULUDQ
15335   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15336                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15337   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15338   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15339   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15340   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15341
15342   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15343   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15344   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15345
15346   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15347   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15348
15349   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15350   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15351 }
15352
15353 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15354   assert(Subtarget->isTargetWin64() && "Unexpected target");
15355   EVT VT = Op.getValueType();
15356   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15357          "Unexpected return type for lowering");
15358
15359   RTLIB::Libcall LC;
15360   bool isSigned;
15361   switch (Op->getOpcode()) {
15362   default: llvm_unreachable("Unexpected request for libcall!");
15363   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15364   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15365   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15366   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15367   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15368   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15369   }
15370
15371   SDLoc dl(Op);
15372   SDValue InChain = DAG.getEntryNode();
15373
15374   TargetLowering::ArgListTy Args;
15375   TargetLowering::ArgListEntry Entry;
15376   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15377     EVT ArgVT = Op->getOperand(i).getValueType();
15378     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15379            "Unexpected argument type for lowering");
15380     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15381     Entry.Node = StackPtr;
15382     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15383                            false, false, 16);
15384     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15385     Entry.Ty = PointerType::get(ArgTy,0);
15386     Entry.isSExt = false;
15387     Entry.isZExt = false;
15388     Args.push_back(Entry);
15389   }
15390
15391   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15392                                          getPointerTy());
15393
15394   TargetLowering::CallLoweringInfo CLI(DAG);
15395   CLI.setDebugLoc(dl).setChain(InChain)
15396     .setCallee(getLibcallCallingConv(LC),
15397                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15398                Callee, std::move(Args), 0)
15399     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15400
15401   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15402   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15403 }
15404
15405 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15406                              SelectionDAG &DAG) {
15407   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15408   EVT VT = Op0.getValueType();
15409   SDLoc dl(Op);
15410
15411   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15412          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15413
15414   // PMULxD operations multiply each even value (starting at 0) of LHS with
15415   // the related value of RHS and produce a widen result.
15416   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15417   // => <2 x i64> <ae|cg>
15418   //
15419   // In other word, to have all the results, we need to perform two PMULxD:
15420   // 1. one with the even values.
15421   // 2. one with the odd values.
15422   // To achieve #2, with need to place the odd values at an even position.
15423   //
15424   // Place the odd value at an even position (basically, shift all values 1
15425   // step to the left):
15426   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15427   // <a|b|c|d> => <b|undef|d|undef>
15428   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15429   // <e|f|g|h> => <f|undef|h|undef>
15430   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15431
15432   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15433   // ints.
15434   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15435   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15436   assert((!IsSigned || Subtarget->hasSSE41()) &&
15437          "We need PMULDQ for signed multiplies!");
15438   unsigned Opcode = IsSigned ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
15439   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15440   // => <2 x i64> <ae|cg>
15441   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15442                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15443   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15444   // => <2 x i64> <bf|dh>
15445   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15446                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15447
15448   // Shuffle it back into the right order.
15449   // The internal representation is big endian.
15450   // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15451   // and its low part at index 1.
15452   // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15453   // Vector index                0 1   ;          2 3
15454   // We want      <ae|bf|cg|dh>
15455   // Vector index   0  2  1  3
15456   // Since each element is seen as 2 x i32, we get:
15457   // high_mask[i] = 2 x vector_index[i]
15458   // low_mask[i] = 2 x vector_index[i] + 1
15459   // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15460   //                       Size/2 - 1, Size/2 + Size/2 - 1}
15461   // where Size is the number of element of the final vector.
15462   SDValue Highs, Lows;
15463   if (VT == MVT::v8i32) {
15464     const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15465     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15466     const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15467     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15468   } else {
15469     const int HighMask[] = {0, 4, 2, 6};
15470     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15471     const int LowMask[] = {1, 5, 3, 7};
15472     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15473   }
15474
15475   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15476   // unsigned multiply.
15477   if (IsSigned && !Subtarget->hasSSE41()) {
15478     SDValue ShAmt =
15479         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15480     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15481                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15482     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15483                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15484
15485     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15486     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15487   }
15488
15489   // THe first result of MUL_LOHI is actually the high value, followed by the
15490   // low value.
15491   SDValue Ops[] = {Highs, Lows};
15492   return DAG.getMergeValues(Ops, dl);
15493 }
15494
15495 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15496                                          const X86Subtarget *Subtarget) {
15497   MVT VT = Op.getSimpleValueType();
15498   SDLoc dl(Op);
15499   SDValue R = Op.getOperand(0);
15500   SDValue Amt = Op.getOperand(1);
15501
15502   // Optimize shl/srl/sra with constant shift amount.
15503   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15504     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15505       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15506
15507       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15508           (Subtarget->hasInt256() &&
15509            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15510           (Subtarget->hasAVX512() &&
15511            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15512         if (Op.getOpcode() == ISD::SHL)
15513           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15514                                             DAG);
15515         if (Op.getOpcode() == ISD::SRL)
15516           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15517                                             DAG);
15518         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15519           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15520                                             DAG);
15521       }
15522
15523       if (VT == MVT::v16i8) {
15524         if (Op.getOpcode() == ISD::SHL) {
15525           // Make a large shift.
15526           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15527                                                    MVT::v8i16, R, ShiftAmt,
15528                                                    DAG);
15529           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15530           // Zero out the rightmost bits.
15531           SmallVector<SDValue, 16> V(16,
15532                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15533                                                      MVT::i8));
15534           return DAG.getNode(ISD::AND, dl, VT, SHL,
15535                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15536         }
15537         if (Op.getOpcode() == ISD::SRL) {
15538           // Make a large shift.
15539           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15540                                                    MVT::v8i16, R, ShiftAmt,
15541                                                    DAG);
15542           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15543           // Zero out the leftmost bits.
15544           SmallVector<SDValue, 16> V(16,
15545                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15546                                                      MVT::i8));
15547           return DAG.getNode(ISD::AND, dl, VT, SRL,
15548                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15549         }
15550         if (Op.getOpcode() == ISD::SRA) {
15551           if (ShiftAmt == 7) {
15552             // R s>> 7  ===  R s< 0
15553             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15554             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15555           }
15556
15557           // R s>> a === ((R u>> a) ^ m) - m
15558           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15559           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15560                                                          MVT::i8));
15561           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15562           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15563           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15564           return Res;
15565         }
15566         llvm_unreachable("Unknown shift opcode.");
15567       }
15568
15569       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15570         if (Op.getOpcode() == ISD::SHL) {
15571           // Make a large shift.
15572           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15573                                                    MVT::v16i16, R, ShiftAmt,
15574                                                    DAG);
15575           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15576           // Zero out the rightmost bits.
15577           SmallVector<SDValue, 32> V(32,
15578                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15579                                                      MVT::i8));
15580           return DAG.getNode(ISD::AND, dl, VT, SHL,
15581                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15582         }
15583         if (Op.getOpcode() == ISD::SRL) {
15584           // Make a large shift.
15585           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15586                                                    MVT::v16i16, R, ShiftAmt,
15587                                                    DAG);
15588           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15589           // Zero out the leftmost bits.
15590           SmallVector<SDValue, 32> V(32,
15591                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15592                                                      MVT::i8));
15593           return DAG.getNode(ISD::AND, dl, VT, SRL,
15594                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15595         }
15596         if (Op.getOpcode() == ISD::SRA) {
15597           if (ShiftAmt == 7) {
15598             // R s>> 7  ===  R s< 0
15599             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15600             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15601           }
15602
15603           // R s>> a === ((R u>> a) ^ m) - m
15604           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15605           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15606                                                          MVT::i8));
15607           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15608           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15609           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15610           return Res;
15611         }
15612         llvm_unreachable("Unknown shift opcode.");
15613       }
15614     }
15615   }
15616
15617   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15618   if (!Subtarget->is64Bit() &&
15619       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15620       Amt.getOpcode() == ISD::BITCAST &&
15621       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15622     Amt = Amt.getOperand(0);
15623     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15624                      VT.getVectorNumElements();
15625     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15626     uint64_t ShiftAmt = 0;
15627     for (unsigned i = 0; i != Ratio; ++i) {
15628       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15629       if (!C)
15630         return SDValue();
15631       // 6 == Log2(64)
15632       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15633     }
15634     // Check remaining shift amounts.
15635     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15636       uint64_t ShAmt = 0;
15637       for (unsigned j = 0; j != Ratio; ++j) {
15638         ConstantSDNode *C =
15639           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15640         if (!C)
15641           return SDValue();
15642         // 6 == Log2(64)
15643         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15644       }
15645       if (ShAmt != ShiftAmt)
15646         return SDValue();
15647     }
15648     switch (Op.getOpcode()) {
15649     default:
15650       llvm_unreachable("Unknown shift opcode!");
15651     case ISD::SHL:
15652       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15653                                         DAG);
15654     case ISD::SRL:
15655       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15656                                         DAG);
15657     case ISD::SRA:
15658       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15659                                         DAG);
15660     }
15661   }
15662
15663   return SDValue();
15664 }
15665
15666 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15667                                         const X86Subtarget* Subtarget) {
15668   MVT VT = Op.getSimpleValueType();
15669   SDLoc dl(Op);
15670   SDValue R = Op.getOperand(0);
15671   SDValue Amt = Op.getOperand(1);
15672
15673   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15674       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15675       (Subtarget->hasInt256() &&
15676        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15677         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15678        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15679     SDValue BaseShAmt;
15680     EVT EltVT = VT.getVectorElementType();
15681
15682     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15683       unsigned NumElts = VT.getVectorNumElements();
15684       unsigned i, j;
15685       for (i = 0; i != NumElts; ++i) {
15686         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15687           continue;
15688         break;
15689       }
15690       for (j = i; j != NumElts; ++j) {
15691         SDValue Arg = Amt.getOperand(j);
15692         if (Arg.getOpcode() == ISD::UNDEF) continue;
15693         if (Arg != Amt.getOperand(i))
15694           break;
15695       }
15696       if (i != NumElts && j == NumElts)
15697         BaseShAmt = Amt.getOperand(i);
15698     } else {
15699       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15700         Amt = Amt.getOperand(0);
15701       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15702                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15703         SDValue InVec = Amt.getOperand(0);
15704         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15705           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15706           unsigned i = 0;
15707           for (; i != NumElts; ++i) {
15708             SDValue Arg = InVec.getOperand(i);
15709             if (Arg.getOpcode() == ISD::UNDEF) continue;
15710             BaseShAmt = Arg;
15711             break;
15712           }
15713         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15714            if (ConstantSDNode *C =
15715                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15716              unsigned SplatIdx =
15717                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15718              if (C->getZExtValue() == SplatIdx)
15719                BaseShAmt = InVec.getOperand(1);
15720            }
15721         }
15722         if (!BaseShAmt.getNode())
15723           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15724                                   DAG.getIntPtrConstant(0));
15725       }
15726     }
15727
15728     if (BaseShAmt.getNode()) {
15729       if (EltVT.bitsGT(MVT::i32))
15730         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15731       else if (EltVT.bitsLT(MVT::i32))
15732         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15733
15734       switch (Op.getOpcode()) {
15735       default:
15736         llvm_unreachable("Unknown shift opcode!");
15737       case ISD::SHL:
15738         switch (VT.SimpleTy) {
15739         default: return SDValue();
15740         case MVT::v2i64:
15741         case MVT::v4i32:
15742         case MVT::v8i16:
15743         case MVT::v4i64:
15744         case MVT::v8i32:
15745         case MVT::v16i16:
15746         case MVT::v16i32:
15747         case MVT::v8i64:
15748           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15749         }
15750       case ISD::SRA:
15751         switch (VT.SimpleTy) {
15752         default: return SDValue();
15753         case MVT::v4i32:
15754         case MVT::v8i16:
15755         case MVT::v8i32:
15756         case MVT::v16i16:
15757         case MVT::v16i32:
15758         case MVT::v8i64:
15759           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15760         }
15761       case ISD::SRL:
15762         switch (VT.SimpleTy) {
15763         default: return SDValue();
15764         case MVT::v2i64:
15765         case MVT::v4i32:
15766         case MVT::v8i16:
15767         case MVT::v4i64:
15768         case MVT::v8i32:
15769         case MVT::v16i16:
15770         case MVT::v16i32:
15771         case MVT::v8i64:
15772           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15773         }
15774       }
15775     }
15776   }
15777
15778   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15779   if (!Subtarget->is64Bit() &&
15780       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15781       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15782       Amt.getOpcode() == ISD::BITCAST &&
15783       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15784     Amt = Amt.getOperand(0);
15785     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15786                      VT.getVectorNumElements();
15787     std::vector<SDValue> Vals(Ratio);
15788     for (unsigned i = 0; i != Ratio; ++i)
15789       Vals[i] = Amt.getOperand(i);
15790     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15791       for (unsigned j = 0; j != Ratio; ++j)
15792         if (Vals[j] != Amt.getOperand(i + j))
15793           return SDValue();
15794     }
15795     switch (Op.getOpcode()) {
15796     default:
15797       llvm_unreachable("Unknown shift opcode!");
15798     case ISD::SHL:
15799       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15800     case ISD::SRL:
15801       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15802     case ISD::SRA:
15803       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15804     }
15805   }
15806
15807   return SDValue();
15808 }
15809
15810 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15811                           SelectionDAG &DAG) {
15812   MVT VT = Op.getSimpleValueType();
15813   SDLoc dl(Op);
15814   SDValue R = Op.getOperand(0);
15815   SDValue Amt = Op.getOperand(1);
15816   SDValue V;
15817
15818   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15819   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15820
15821   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15822   if (V.getNode())
15823     return V;
15824
15825   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15826   if (V.getNode())
15827       return V;
15828
15829   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15830     return Op;
15831   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15832   if (Subtarget->hasInt256()) {
15833     if (Op.getOpcode() == ISD::SRL &&
15834         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15835          VT == MVT::v4i64 || VT == MVT::v8i32))
15836       return Op;
15837     if (Op.getOpcode() == ISD::SHL &&
15838         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15839          VT == MVT::v4i64 || VT == MVT::v8i32))
15840       return Op;
15841     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15842       return Op;
15843   }
15844
15845   // If possible, lower this packed shift into a vector multiply instead of
15846   // expanding it into a sequence of scalar shifts.
15847   // Do this only if the vector shift count is a constant build_vector.
15848   if (Op.getOpcode() == ISD::SHL && 
15849       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15850        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15851       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15852     SmallVector<SDValue, 8> Elts;
15853     EVT SVT = VT.getScalarType();
15854     unsigned SVTBits = SVT.getSizeInBits();
15855     const APInt &One = APInt(SVTBits, 1);
15856     unsigned NumElems = VT.getVectorNumElements();
15857
15858     for (unsigned i=0; i !=NumElems; ++i) {
15859       SDValue Op = Amt->getOperand(i);
15860       if (Op->getOpcode() == ISD::UNDEF) {
15861         Elts.push_back(Op);
15862         continue;
15863       }
15864
15865       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15866       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15867       uint64_t ShAmt = C.getZExtValue();
15868       if (ShAmt >= SVTBits) {
15869         Elts.push_back(DAG.getUNDEF(SVT));
15870         continue;
15871       }
15872       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15873     }
15874     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15875     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15876   }
15877
15878   // Lower SHL with variable shift amount.
15879   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15880     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15881
15882     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15883     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15884     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15885     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15886   }
15887
15888   // If possible, lower this shift as a sequence of two shifts by
15889   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15890   // Example:
15891   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15892   //
15893   // Could be rewritten as:
15894   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15895   //
15896   // The advantage is that the two shifts from the example would be
15897   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15898   // the vector shift into four scalar shifts plus four pairs of vector
15899   // insert/extract.
15900   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15901       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15902     unsigned TargetOpcode = X86ISD::MOVSS;
15903     bool CanBeSimplified;
15904     // The splat value for the first packed shift (the 'X' from the example).
15905     SDValue Amt1 = Amt->getOperand(0);
15906     // The splat value for the second packed shift (the 'Y' from the example).
15907     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15908                                         Amt->getOperand(2);
15909
15910     // See if it is possible to replace this node with a sequence of
15911     // two shifts followed by a MOVSS/MOVSD
15912     if (VT == MVT::v4i32) {
15913       // Check if it is legal to use a MOVSS.
15914       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15915                         Amt2 == Amt->getOperand(3);
15916       if (!CanBeSimplified) {
15917         // Otherwise, check if we can still simplify this node using a MOVSD.
15918         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15919                           Amt->getOperand(2) == Amt->getOperand(3);
15920         TargetOpcode = X86ISD::MOVSD;
15921         Amt2 = Amt->getOperand(2);
15922       }
15923     } else {
15924       // Do similar checks for the case where the machine value type
15925       // is MVT::v8i16.
15926       CanBeSimplified = Amt1 == Amt->getOperand(1);
15927       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15928         CanBeSimplified = Amt2 == Amt->getOperand(i);
15929
15930       if (!CanBeSimplified) {
15931         TargetOpcode = X86ISD::MOVSD;
15932         CanBeSimplified = true;
15933         Amt2 = Amt->getOperand(4);
15934         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15935           CanBeSimplified = Amt1 == Amt->getOperand(i);
15936         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15937           CanBeSimplified = Amt2 == Amt->getOperand(j);
15938       }
15939     }
15940     
15941     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15942         isa<ConstantSDNode>(Amt2)) {
15943       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15944       EVT CastVT = MVT::v4i32;
15945       SDValue Splat1 = 
15946         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15947       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15948       SDValue Splat2 = 
15949         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15950       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15951       if (TargetOpcode == X86ISD::MOVSD)
15952         CastVT = MVT::v2i64;
15953       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15954       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15955       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15956                                             BitCast1, DAG);
15957       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15958     }
15959   }
15960
15961   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15962     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15963
15964     // a = a << 5;
15965     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15966     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15967
15968     // Turn 'a' into a mask suitable for VSELECT
15969     SDValue VSelM = DAG.getConstant(0x80, VT);
15970     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15971     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15972
15973     SDValue CM1 = DAG.getConstant(0x0f, VT);
15974     SDValue CM2 = DAG.getConstant(0x3f, VT);
15975
15976     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15977     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15978     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15979     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15980     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15981
15982     // a += a
15983     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15984     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15985     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15986
15987     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15988     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15989     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15990     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15991     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15992
15993     // a += a
15994     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15995     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15996     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15997
15998     // return VSELECT(r, r+r, a);
15999     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16000                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16001     return R;
16002   }
16003
16004   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16005   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16006   // solution better.
16007   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16008     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16009     unsigned ExtOpc =
16010         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16011     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16012     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16013     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16014                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16015     }
16016
16017   // Decompose 256-bit shifts into smaller 128-bit shifts.
16018   if (VT.is256BitVector()) {
16019     unsigned NumElems = VT.getVectorNumElements();
16020     MVT EltVT = VT.getVectorElementType();
16021     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16022
16023     // Extract the two vectors
16024     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16025     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16026
16027     // Recreate the shift amount vectors
16028     SDValue Amt1, Amt2;
16029     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16030       // Constant shift amount
16031       SmallVector<SDValue, 4> Amt1Csts;
16032       SmallVector<SDValue, 4> Amt2Csts;
16033       for (unsigned i = 0; i != NumElems/2; ++i)
16034         Amt1Csts.push_back(Amt->getOperand(i));
16035       for (unsigned i = NumElems/2; i != NumElems; ++i)
16036         Amt2Csts.push_back(Amt->getOperand(i));
16037
16038       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16039       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16040     } else {
16041       // Variable shift amount
16042       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16043       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16044     }
16045
16046     // Issue new vector shifts for the smaller types
16047     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16048     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16049
16050     // Concatenate the result back
16051     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16052   }
16053
16054   return SDValue();
16055 }
16056
16057 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16058   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16059   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16060   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16061   // has only one use.
16062   SDNode *N = Op.getNode();
16063   SDValue LHS = N->getOperand(0);
16064   SDValue RHS = N->getOperand(1);
16065   unsigned BaseOp = 0;
16066   unsigned Cond = 0;
16067   SDLoc DL(Op);
16068   switch (Op.getOpcode()) {
16069   default: llvm_unreachable("Unknown ovf instruction!");
16070   case ISD::SADDO:
16071     // A subtract of one will be selected as a INC. Note that INC doesn't
16072     // set CF, so we can't do this for UADDO.
16073     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16074       if (C->isOne()) {
16075         BaseOp = X86ISD::INC;
16076         Cond = X86::COND_O;
16077         break;
16078       }
16079     BaseOp = X86ISD::ADD;
16080     Cond = X86::COND_O;
16081     break;
16082   case ISD::UADDO:
16083     BaseOp = X86ISD::ADD;
16084     Cond = X86::COND_B;
16085     break;
16086   case ISD::SSUBO:
16087     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16088     // set CF, so we can't do this for USUBO.
16089     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16090       if (C->isOne()) {
16091         BaseOp = X86ISD::DEC;
16092         Cond = X86::COND_O;
16093         break;
16094       }
16095     BaseOp = X86ISD::SUB;
16096     Cond = X86::COND_O;
16097     break;
16098   case ISD::USUBO:
16099     BaseOp = X86ISD::SUB;
16100     Cond = X86::COND_B;
16101     break;
16102   case ISD::SMULO:
16103     BaseOp = X86ISD::SMUL;
16104     Cond = X86::COND_O;
16105     break;
16106   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16107     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16108                                  MVT::i32);
16109     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16110
16111     SDValue SetCC =
16112       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16113                   DAG.getConstant(X86::COND_O, MVT::i32),
16114                   SDValue(Sum.getNode(), 2));
16115
16116     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16117   }
16118   }
16119
16120   // Also sets EFLAGS.
16121   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16122   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16123
16124   SDValue SetCC =
16125     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16126                 DAG.getConstant(Cond, MVT::i32),
16127                 SDValue(Sum.getNode(), 1));
16128
16129   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16130 }
16131
16132 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16133                                                   SelectionDAG &DAG) const {
16134   SDLoc dl(Op);
16135   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16136   MVT VT = Op.getSimpleValueType();
16137
16138   if (!Subtarget->hasSSE2() || !VT.isVector())
16139     return SDValue();
16140
16141   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16142                       ExtraVT.getScalarType().getSizeInBits();
16143
16144   switch (VT.SimpleTy) {
16145     default: return SDValue();
16146     case MVT::v8i32:
16147     case MVT::v16i16:
16148       if (!Subtarget->hasFp256())
16149         return SDValue();
16150       if (!Subtarget->hasInt256()) {
16151         // needs to be split
16152         unsigned NumElems = VT.getVectorNumElements();
16153
16154         // Extract the LHS vectors
16155         SDValue LHS = Op.getOperand(0);
16156         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16157         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16158
16159         MVT EltVT = VT.getVectorElementType();
16160         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16161
16162         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16163         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16164         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16165                                    ExtraNumElems/2);
16166         SDValue Extra = DAG.getValueType(ExtraVT);
16167
16168         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16169         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16170
16171         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16172       }
16173       // fall through
16174     case MVT::v4i32:
16175     case MVT::v8i16: {
16176       SDValue Op0 = Op.getOperand(0);
16177       SDValue Op00 = Op0.getOperand(0);
16178       SDValue Tmp1;
16179       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16180       if (Op0.getOpcode() == ISD::BITCAST &&
16181           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16182         // (sext (vzext x)) -> (vsext x)
16183         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16184         if (Tmp1.getNode()) {
16185           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16186           // This folding is only valid when the in-reg type is a vector of i8,
16187           // i16, or i32.
16188           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16189               ExtraEltVT == MVT::i32) {
16190             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16191             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16192                    "This optimization is invalid without a VZEXT.");
16193             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16194           }
16195           Op0 = Tmp1;
16196         }
16197       }
16198
16199       // If the above didn't work, then just use Shift-Left + Shift-Right.
16200       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16201                                         DAG);
16202       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16203                                         DAG);
16204     }
16205   }
16206 }
16207
16208 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16209                                  SelectionDAG &DAG) {
16210   SDLoc dl(Op);
16211   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16212     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16213   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16214     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16215
16216   // The only fence that needs an instruction is a sequentially-consistent
16217   // cross-thread fence.
16218   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16219     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16220     // no-sse2). There isn't any reason to disable it if the target processor
16221     // supports it.
16222     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16223       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16224
16225     SDValue Chain = Op.getOperand(0);
16226     SDValue Zero = DAG.getConstant(0, MVT::i32);
16227     SDValue Ops[] = {
16228       DAG.getRegister(X86::ESP, MVT::i32), // Base
16229       DAG.getTargetConstant(1, MVT::i8),   // Scale
16230       DAG.getRegister(0, MVT::i32),        // Index
16231       DAG.getTargetConstant(0, MVT::i32),  // Disp
16232       DAG.getRegister(0, MVT::i32),        // Segment.
16233       Zero,
16234       Chain
16235     };
16236     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16237     return SDValue(Res, 0);
16238   }
16239
16240   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16241   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16242 }
16243
16244 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16245                              SelectionDAG &DAG) {
16246   MVT T = Op.getSimpleValueType();
16247   SDLoc DL(Op);
16248   unsigned Reg = 0;
16249   unsigned size = 0;
16250   switch(T.SimpleTy) {
16251   default: llvm_unreachable("Invalid value type!");
16252   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16253   case MVT::i16: Reg = X86::AX;  size = 2; break;
16254   case MVT::i32: Reg = X86::EAX; size = 4; break;
16255   case MVT::i64:
16256     assert(Subtarget->is64Bit() && "Node not type legal!");
16257     Reg = X86::RAX; size = 8;
16258     break;
16259   }
16260   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16261                                   Op.getOperand(2), SDValue());
16262   SDValue Ops[] = { cpIn.getValue(0),
16263                     Op.getOperand(1),
16264                     Op.getOperand(3),
16265                     DAG.getTargetConstant(size, MVT::i8),
16266                     cpIn.getValue(1) };
16267   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16268   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16269   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16270                                            Ops, T, MMO);
16271
16272   SDValue cpOut =
16273     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16274   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16275                                       MVT::i32, cpOut.getValue(2));
16276   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16277                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16278
16279   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16280   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16281   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16282   return SDValue();
16283 }
16284
16285 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16286                             SelectionDAG &DAG) {
16287   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16288   MVT DstVT = Op.getSimpleValueType();
16289
16290   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16291     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16292     if (DstVT != MVT::f64)
16293       // This conversion needs to be expanded.
16294       return SDValue();
16295
16296     SDValue InVec = Op->getOperand(0);
16297     SDLoc dl(Op);
16298     unsigned NumElts = SrcVT.getVectorNumElements();
16299     EVT SVT = SrcVT.getVectorElementType();
16300
16301     // Widen the vector in input in the case of MVT::v2i32.
16302     // Example: from MVT::v2i32 to MVT::v4i32.
16303     SmallVector<SDValue, 16> Elts;
16304     for (unsigned i = 0, e = NumElts; i != e; ++i)
16305       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16306                                  DAG.getIntPtrConstant(i)));
16307
16308     // Explicitly mark the extra elements as Undef.
16309     SDValue Undef = DAG.getUNDEF(SVT);
16310     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16311       Elts.push_back(Undef);
16312
16313     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16314     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16315     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16316     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16317                        DAG.getIntPtrConstant(0));
16318   }
16319
16320   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16321          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16322   assert((DstVT == MVT::i64 ||
16323           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16324          "Unexpected custom BITCAST");
16325   // i64 <=> MMX conversions are Legal.
16326   if (SrcVT==MVT::i64 && DstVT.isVector())
16327     return Op;
16328   if (DstVT==MVT::i64 && SrcVT.isVector())
16329     return Op;
16330   // MMX <=> MMX conversions are Legal.
16331   if (SrcVT.isVector() && DstVT.isVector())
16332     return Op;
16333   // All other conversions need to be expanded.
16334   return SDValue();
16335 }
16336
16337 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16338   SDNode *Node = Op.getNode();
16339   SDLoc dl(Node);
16340   EVT T = Node->getValueType(0);
16341   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16342                               DAG.getConstant(0, T), Node->getOperand(2));
16343   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16344                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16345                        Node->getOperand(0),
16346                        Node->getOperand(1), negOp,
16347                        cast<AtomicSDNode>(Node)->getMemOperand(),
16348                        cast<AtomicSDNode>(Node)->getOrdering(),
16349                        cast<AtomicSDNode>(Node)->getSynchScope());
16350 }
16351
16352 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16353   SDNode *Node = Op.getNode();
16354   SDLoc dl(Node);
16355   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16356
16357   // Convert seq_cst store -> xchg
16358   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16359   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16360   //        (The only way to get a 16-byte store is cmpxchg16b)
16361   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16362   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16363       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16364     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16365                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16366                                  Node->getOperand(0),
16367                                  Node->getOperand(1), Node->getOperand(2),
16368                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16369                                  cast<AtomicSDNode>(Node)->getOrdering(),
16370                                  cast<AtomicSDNode>(Node)->getSynchScope());
16371     return Swap.getValue(1);
16372   }
16373   // Other atomic stores have a simple pattern.
16374   return Op;
16375 }
16376
16377 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16378   EVT VT = Op.getNode()->getSimpleValueType(0);
16379
16380   // Let legalize expand this if it isn't a legal type yet.
16381   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16382     return SDValue();
16383
16384   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16385
16386   unsigned Opc;
16387   bool ExtraOp = false;
16388   switch (Op.getOpcode()) {
16389   default: llvm_unreachable("Invalid code");
16390   case ISD::ADDC: Opc = X86ISD::ADD; break;
16391   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16392   case ISD::SUBC: Opc = X86ISD::SUB; break;
16393   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16394   }
16395
16396   if (!ExtraOp)
16397     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16398                        Op.getOperand(1));
16399   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16400                      Op.getOperand(1), Op.getOperand(2));
16401 }
16402
16403 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16404                             SelectionDAG &DAG) {
16405   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16406
16407   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16408   // which returns the values as { float, float } (in XMM0) or
16409   // { double, double } (which is returned in XMM0, XMM1).
16410   SDLoc dl(Op);
16411   SDValue Arg = Op.getOperand(0);
16412   EVT ArgVT = Arg.getValueType();
16413   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16414
16415   TargetLowering::ArgListTy Args;
16416   TargetLowering::ArgListEntry Entry;
16417
16418   Entry.Node = Arg;
16419   Entry.Ty = ArgTy;
16420   Entry.isSExt = false;
16421   Entry.isZExt = false;
16422   Args.push_back(Entry);
16423
16424   bool isF64 = ArgVT == MVT::f64;
16425   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16426   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16427   // the results are returned via SRet in memory.
16428   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16430   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16431
16432   Type *RetTy = isF64
16433     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16434     : (Type*)VectorType::get(ArgTy, 4);
16435
16436   TargetLowering::CallLoweringInfo CLI(DAG);
16437   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16438     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16439
16440   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16441
16442   if (isF64)
16443     // Returned in xmm0 and xmm1.
16444     return CallResult.first;
16445
16446   // Returned in bits 0:31 and 32:64 xmm0.
16447   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16448                                CallResult.first, DAG.getIntPtrConstant(0));
16449   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16450                                CallResult.first, DAG.getIntPtrConstant(1));
16451   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16452   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16453 }
16454
16455 /// LowerOperation - Provide custom lowering hooks for some operations.
16456 ///
16457 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16458   switch (Op.getOpcode()) {
16459   default: llvm_unreachable("Should not custom lower this!");
16460   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16461   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16462   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16463     return LowerCMP_SWAP(Op, Subtarget, DAG);
16464   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16465   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16466   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16467   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16468   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16469   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16470   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16471   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16472   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16473   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16474   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16475   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16476   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16477   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16478   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16479   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16480   case ISD::SHL_PARTS:
16481   case ISD::SRA_PARTS:
16482   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16483   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16484   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16485   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16486   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16487   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16488   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16489   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16490   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16491   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16492   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16493   case ISD::FABS:               return LowerFABS(Op, DAG);
16494   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16495   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16496   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16497   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16498   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16499   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16500   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16501   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16502   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16503   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16504   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16505   case ISD::INTRINSIC_VOID:
16506   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16507   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16508   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16509   case ISD::FRAME_TO_ARGS_OFFSET:
16510                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16511   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16512   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16513   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16514   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16515   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16516   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16517   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16518   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16519   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16520   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16521   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16522   case ISD::UMUL_LOHI:
16523   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16524   case ISD::SRA:
16525   case ISD::SRL:
16526   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16527   case ISD::SADDO:
16528   case ISD::UADDO:
16529   case ISD::SSUBO:
16530   case ISD::USUBO:
16531   case ISD::SMULO:
16532   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16533   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16534   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16535   case ISD::ADDC:
16536   case ISD::ADDE:
16537   case ISD::SUBC:
16538   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16539   case ISD::ADD:                return LowerADD(Op, DAG);
16540   case ISD::SUB:                return LowerSUB(Op, DAG);
16541   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16542   }
16543 }
16544
16545 static void ReplaceATOMIC_LOAD(SDNode *Node,
16546                                SmallVectorImpl<SDValue> &Results,
16547                                SelectionDAG &DAG) {
16548   SDLoc dl(Node);
16549   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16550
16551   // Convert wide load -> cmpxchg8b/cmpxchg16b
16552   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16553   //        (The only way to get a 16-byte load is cmpxchg16b)
16554   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16555   SDValue Zero = DAG.getConstant(0, VT);
16556   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16557   SDValue Swap =
16558       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16559                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16560                            cast<AtomicSDNode>(Node)->getMemOperand(),
16561                            cast<AtomicSDNode>(Node)->getOrdering(),
16562                            cast<AtomicSDNode>(Node)->getOrdering(),
16563                            cast<AtomicSDNode>(Node)->getSynchScope());
16564   Results.push_back(Swap.getValue(0));
16565   Results.push_back(Swap.getValue(2));
16566 }
16567
16568 /// ReplaceNodeResults - Replace a node with an illegal result type
16569 /// with a new node built out of custom code.
16570 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16571                                            SmallVectorImpl<SDValue>&Results,
16572                                            SelectionDAG &DAG) const {
16573   SDLoc dl(N);
16574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16575   switch (N->getOpcode()) {
16576   default:
16577     llvm_unreachable("Do not know how to custom type legalize this operation!");
16578   case ISD::SIGN_EXTEND_INREG:
16579   case ISD::ADDC:
16580   case ISD::ADDE:
16581   case ISD::SUBC:
16582   case ISD::SUBE:
16583     // We don't want to expand or promote these.
16584     return;
16585   case ISD::SDIV:
16586   case ISD::UDIV:
16587   case ISD::SREM:
16588   case ISD::UREM:
16589   case ISD::SDIVREM:
16590   case ISD::UDIVREM: {
16591     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16592     Results.push_back(V);
16593     return;
16594   }
16595   case ISD::FP_TO_SINT:
16596   case ISD::FP_TO_UINT: {
16597     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16598
16599     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16600       return;
16601
16602     std::pair<SDValue,SDValue> Vals =
16603         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16604     SDValue FIST = Vals.first, StackSlot = Vals.second;
16605     if (FIST.getNode()) {
16606       EVT VT = N->getValueType(0);
16607       // Return a load from the stack slot.
16608       if (StackSlot.getNode())
16609         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16610                                       MachinePointerInfo(),
16611                                       false, false, false, 0));
16612       else
16613         Results.push_back(FIST);
16614     }
16615     return;
16616   }
16617   case ISD::UINT_TO_FP: {
16618     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16619     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16620         N->getValueType(0) != MVT::v2f32)
16621       return;
16622     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16623                                  N->getOperand(0));
16624     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16625                                      MVT::f64);
16626     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16627     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16628                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16629     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16630     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16631     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16632     return;
16633   }
16634   case ISD::FP_ROUND: {
16635     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16636         return;
16637     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16638     Results.push_back(V);
16639     return;
16640   }
16641   case ISD::INTRINSIC_W_CHAIN: {
16642     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16643     switch (IntNo) {
16644     default : llvm_unreachable("Do not know how to custom type "
16645                                "legalize this intrinsic operation!");
16646     case Intrinsic::x86_rdtsc:
16647       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16648                                      Results);
16649     case Intrinsic::x86_rdtscp:
16650       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16651                                      Results);
16652     case Intrinsic::x86_rdpmc:
16653       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16654     }
16655   }
16656   case ISD::READCYCLECOUNTER: {
16657     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16658                                    Results);
16659   }
16660   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16661     EVT T = N->getValueType(0);
16662     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16663     bool Regs64bit = T == MVT::i128;
16664     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16665     SDValue cpInL, cpInH;
16666     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16667                         DAG.getConstant(0, HalfT));
16668     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16669                         DAG.getConstant(1, HalfT));
16670     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16671                              Regs64bit ? X86::RAX : X86::EAX,
16672                              cpInL, SDValue());
16673     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16674                              Regs64bit ? X86::RDX : X86::EDX,
16675                              cpInH, cpInL.getValue(1));
16676     SDValue swapInL, swapInH;
16677     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16678                           DAG.getConstant(0, HalfT));
16679     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16680                           DAG.getConstant(1, HalfT));
16681     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16682                                Regs64bit ? X86::RBX : X86::EBX,
16683                                swapInL, cpInH.getValue(1));
16684     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16685                                Regs64bit ? X86::RCX : X86::ECX,
16686                                swapInH, swapInL.getValue(1));
16687     SDValue Ops[] = { swapInH.getValue(0),
16688                       N->getOperand(1),
16689                       swapInH.getValue(1) };
16690     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16691     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16692     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16693                                   X86ISD::LCMPXCHG8_DAG;
16694     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16695     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16696                                         Regs64bit ? X86::RAX : X86::EAX,
16697                                         HalfT, Result.getValue(1));
16698     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16699                                         Regs64bit ? X86::RDX : X86::EDX,
16700                                         HalfT, cpOutL.getValue(2));
16701     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16702
16703     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16704                                         MVT::i32, cpOutH.getValue(2));
16705     SDValue Success =
16706         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16707                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16708     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16709
16710     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16711     Results.push_back(Success);
16712     Results.push_back(EFLAGS.getValue(1));
16713     return;
16714   }
16715   case ISD::ATOMIC_SWAP:
16716   case ISD::ATOMIC_LOAD_ADD:
16717   case ISD::ATOMIC_LOAD_SUB:
16718   case ISD::ATOMIC_LOAD_AND:
16719   case ISD::ATOMIC_LOAD_OR:
16720   case ISD::ATOMIC_LOAD_XOR:
16721   case ISD::ATOMIC_LOAD_NAND:
16722   case ISD::ATOMIC_LOAD_MIN:
16723   case ISD::ATOMIC_LOAD_MAX:
16724   case ISD::ATOMIC_LOAD_UMIN:
16725   case ISD::ATOMIC_LOAD_UMAX:
16726     // Delegate to generic TypeLegalization. Situations we can really handle
16727     // should have already been dealt with by X86AtomicExpand.cpp.
16728     break;
16729   case ISD::ATOMIC_LOAD: {
16730     ReplaceATOMIC_LOAD(N, Results, DAG);
16731     return;
16732   }
16733   case ISD::BITCAST: {
16734     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16735     EVT DstVT = N->getValueType(0);
16736     EVT SrcVT = N->getOperand(0)->getValueType(0);
16737
16738     if (SrcVT != MVT::f64 ||
16739         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16740       return;
16741
16742     unsigned NumElts = DstVT.getVectorNumElements();
16743     EVT SVT = DstVT.getVectorElementType();
16744     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16745     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16746                                    MVT::v2f64, N->getOperand(0));
16747     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16748
16749     if (ExperimentalVectorWideningLegalization) {
16750       // If we are legalizing vectors by widening, we already have the desired
16751       // legal vector type, just return it.
16752       Results.push_back(ToVecInt);
16753       return;
16754     }
16755
16756     SmallVector<SDValue, 8> Elts;
16757     for (unsigned i = 0, e = NumElts; i != e; ++i)
16758       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16759                                    ToVecInt, DAG.getIntPtrConstant(i)));
16760
16761     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16762   }
16763   }
16764 }
16765
16766 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16767   switch (Opcode) {
16768   default: return nullptr;
16769   case X86ISD::BSF:                return "X86ISD::BSF";
16770   case X86ISD::BSR:                return "X86ISD::BSR";
16771   case X86ISD::SHLD:               return "X86ISD::SHLD";
16772   case X86ISD::SHRD:               return "X86ISD::SHRD";
16773   case X86ISD::FAND:               return "X86ISD::FAND";
16774   case X86ISD::FANDN:              return "X86ISD::FANDN";
16775   case X86ISD::FOR:                return "X86ISD::FOR";
16776   case X86ISD::FXOR:               return "X86ISD::FXOR";
16777   case X86ISD::FSRL:               return "X86ISD::FSRL";
16778   case X86ISD::FILD:               return "X86ISD::FILD";
16779   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16780   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16781   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16782   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16783   case X86ISD::FLD:                return "X86ISD::FLD";
16784   case X86ISD::FST:                return "X86ISD::FST";
16785   case X86ISD::CALL:               return "X86ISD::CALL";
16786   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16787   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16788   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16789   case X86ISD::BT:                 return "X86ISD::BT";
16790   case X86ISD::CMP:                return "X86ISD::CMP";
16791   case X86ISD::COMI:               return "X86ISD::COMI";
16792   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16793   case X86ISD::CMPM:               return "X86ISD::CMPM";
16794   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16795   case X86ISD::SETCC:              return "X86ISD::SETCC";
16796   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16797   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16798   case X86ISD::CMOV:               return "X86ISD::CMOV";
16799   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16800   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16801   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16802   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16803   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16804   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16805   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16806   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16807   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16808   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16809   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16810   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16811   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16812   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16813   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16814   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16815   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16816   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16817   case X86ISD::HADD:               return "X86ISD::HADD";
16818   case X86ISD::HSUB:               return "X86ISD::HSUB";
16819   case X86ISD::FHADD:              return "X86ISD::FHADD";
16820   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16821   case X86ISD::UMAX:               return "X86ISD::UMAX";
16822   case X86ISD::UMIN:               return "X86ISD::UMIN";
16823   case X86ISD::SMAX:               return "X86ISD::SMAX";
16824   case X86ISD::SMIN:               return "X86ISD::SMIN";
16825   case X86ISD::FMAX:               return "X86ISD::FMAX";
16826   case X86ISD::FMIN:               return "X86ISD::FMIN";
16827   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16828   case X86ISD::FMINC:              return "X86ISD::FMINC";
16829   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16830   case X86ISD::FRCP:               return "X86ISD::FRCP";
16831   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16832   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16833   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16834   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16835   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16836   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16837   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16838   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16839   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16840   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16841   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16842   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16843   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16844   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16845   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16846   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16847   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16848   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16849   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16850   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16851   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16852   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16853   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16854   case X86ISD::VSHL:               return "X86ISD::VSHL";
16855   case X86ISD::VSRL:               return "X86ISD::VSRL";
16856   case X86ISD::VSRA:               return "X86ISD::VSRA";
16857   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16858   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16859   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16860   case X86ISD::CMPP:               return "X86ISD::CMPP";
16861   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16862   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16863   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16864   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16865   case X86ISD::ADD:                return "X86ISD::ADD";
16866   case X86ISD::SUB:                return "X86ISD::SUB";
16867   case X86ISD::ADC:                return "X86ISD::ADC";
16868   case X86ISD::SBB:                return "X86ISD::SBB";
16869   case X86ISD::SMUL:               return "X86ISD::SMUL";
16870   case X86ISD::UMUL:               return "X86ISD::UMUL";
16871   case X86ISD::INC:                return "X86ISD::INC";
16872   case X86ISD::DEC:                return "X86ISD::DEC";
16873   case X86ISD::OR:                 return "X86ISD::OR";
16874   case X86ISD::XOR:                return "X86ISD::XOR";
16875   case X86ISD::AND:                return "X86ISD::AND";
16876   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16877   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16878   case X86ISD::PTEST:              return "X86ISD::PTEST";
16879   case X86ISD::TESTP:              return "X86ISD::TESTP";
16880   case X86ISD::TESTM:              return "X86ISD::TESTM";
16881   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16882   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16883   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16884   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16885   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16886   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16887   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16888   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16889   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16890   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16891   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16892   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16893   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16894   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16895   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16896   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16897   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16898   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16899   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16900   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16901   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16902   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16903   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16904   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16905   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16906   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16907   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16908   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16909   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16910   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16911   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16912   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16913   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16914   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16915   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16916   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16917   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16918   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16919   case X86ISD::SAHF:               return "X86ISD::SAHF";
16920   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16921   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16922   case X86ISD::FMADD:              return "X86ISD::FMADD";
16923   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16924   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16925   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16926   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16927   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16928   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16929   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16930   case X86ISD::XTEST:              return "X86ISD::XTEST";
16931   }
16932 }
16933
16934 // isLegalAddressingMode - Return true if the addressing mode represented
16935 // by AM is legal for this target, for a load/store of the specified type.
16936 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16937                                               Type *Ty) const {
16938   // X86 supports extremely general addressing modes.
16939   CodeModel::Model M = getTargetMachine().getCodeModel();
16940   Reloc::Model R = getTargetMachine().getRelocationModel();
16941
16942   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16943   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16944     return false;
16945
16946   if (AM.BaseGV) {
16947     unsigned GVFlags =
16948       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16949
16950     // If a reference to this global requires an extra load, we can't fold it.
16951     if (isGlobalStubReference(GVFlags))
16952       return false;
16953
16954     // If BaseGV requires a register for the PIC base, we cannot also have a
16955     // BaseReg specified.
16956     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16957       return false;
16958
16959     // If lower 4G is not available, then we must use rip-relative addressing.
16960     if ((M != CodeModel::Small || R != Reloc::Static) &&
16961         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16962       return false;
16963   }
16964
16965   switch (AM.Scale) {
16966   case 0:
16967   case 1:
16968   case 2:
16969   case 4:
16970   case 8:
16971     // These scales always work.
16972     break;
16973   case 3:
16974   case 5:
16975   case 9:
16976     // These scales are formed with basereg+scalereg.  Only accept if there is
16977     // no basereg yet.
16978     if (AM.HasBaseReg)
16979       return false;
16980     break;
16981   default:  // Other stuff never works.
16982     return false;
16983   }
16984
16985   return true;
16986 }
16987
16988 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16989   unsigned Bits = Ty->getScalarSizeInBits();
16990
16991   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16992   // particularly cheaper than those without.
16993   if (Bits == 8)
16994     return false;
16995
16996   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16997   // variable shifts just as cheap as scalar ones.
16998   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16999     return false;
17000
17001   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17002   // fully general vector.
17003   return true;
17004 }
17005
17006 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17007   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17008     return false;
17009   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17010   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17011   return NumBits1 > NumBits2;
17012 }
17013
17014 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17015   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17016     return false;
17017
17018   if (!isTypeLegal(EVT::getEVT(Ty1)))
17019     return false;
17020
17021   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17022
17023   // Assuming the caller doesn't have a zeroext or signext return parameter,
17024   // truncation all the way down to i1 is valid.
17025   return true;
17026 }
17027
17028 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17029   return isInt<32>(Imm);
17030 }
17031
17032 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17033   // Can also use sub to handle negated immediates.
17034   return isInt<32>(Imm);
17035 }
17036
17037 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17038   if (!VT1.isInteger() || !VT2.isInteger())
17039     return false;
17040   unsigned NumBits1 = VT1.getSizeInBits();
17041   unsigned NumBits2 = VT2.getSizeInBits();
17042   return NumBits1 > NumBits2;
17043 }
17044
17045 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17046   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17047   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17048 }
17049
17050 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17051   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17052   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17053 }
17054
17055 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17056   EVT VT1 = Val.getValueType();
17057   if (isZExtFree(VT1, VT2))
17058     return true;
17059
17060   if (Val.getOpcode() != ISD::LOAD)
17061     return false;
17062
17063   if (!VT1.isSimple() || !VT1.isInteger() ||
17064       !VT2.isSimple() || !VT2.isInteger())
17065     return false;
17066
17067   switch (VT1.getSimpleVT().SimpleTy) {
17068   default: break;
17069   case MVT::i8:
17070   case MVT::i16:
17071   case MVT::i32:
17072     // X86 has 8, 16, and 32-bit zero-extending loads.
17073     return true;
17074   }
17075
17076   return false;
17077 }
17078
17079 bool
17080 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17081   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17082     return false;
17083
17084   VT = VT.getScalarType();
17085
17086   if (!VT.isSimple())
17087     return false;
17088
17089   switch (VT.getSimpleVT().SimpleTy) {
17090   case MVT::f32:
17091   case MVT::f64:
17092     return true;
17093   default:
17094     break;
17095   }
17096
17097   return false;
17098 }
17099
17100 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17101   // i16 instructions are longer (0x66 prefix) and potentially slower.
17102   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17103 }
17104
17105 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17106 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17107 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17108 /// are assumed to be legal.
17109 bool
17110 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17111                                       EVT VT) const {
17112   if (!VT.isSimple())
17113     return false;
17114
17115   MVT SVT = VT.getSimpleVT();
17116
17117   // Very little shuffling can be done for 64-bit vectors right now.
17118   if (VT.getSizeInBits() == 64)
17119     return false;
17120
17121   // If this is a single-input shuffle with no 128 bit lane crossings we can
17122   // lower it into pshufb.
17123   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17124       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17125     bool isLegal = true;
17126     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17127       if (M[I] >= (int)SVT.getVectorNumElements() ||
17128           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17129         isLegal = false;
17130         break;
17131       }
17132     }
17133     if (isLegal)
17134       return true;
17135   }
17136
17137   // FIXME: blends, shifts.
17138   return (SVT.getVectorNumElements() == 2 ||
17139           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17140           isMOVLMask(M, SVT) ||
17141           isMOVHLPSMask(M, SVT) ||
17142           isSHUFPMask(M, SVT) ||
17143           isPSHUFDMask(M, SVT) ||
17144           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17145           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17146           isPALIGNRMask(M, SVT, Subtarget) ||
17147           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17148           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17149           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17150           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17151           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17152 }
17153
17154 bool
17155 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17156                                           EVT VT) const {
17157   if (!VT.isSimple())
17158     return false;
17159
17160   MVT SVT = VT.getSimpleVT();
17161   unsigned NumElts = SVT.getVectorNumElements();
17162   // FIXME: This collection of masks seems suspect.
17163   if (NumElts == 2)
17164     return true;
17165   if (NumElts == 4 && SVT.is128BitVector()) {
17166     return (isMOVLMask(Mask, SVT)  ||
17167             isCommutedMOVLMask(Mask, SVT, true) ||
17168             isSHUFPMask(Mask, SVT) ||
17169             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17170   }
17171   return false;
17172 }
17173
17174 //===----------------------------------------------------------------------===//
17175 //                           X86 Scheduler Hooks
17176 //===----------------------------------------------------------------------===//
17177
17178 /// Utility function to emit xbegin specifying the start of an RTM region.
17179 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17180                                      const TargetInstrInfo *TII) {
17181   DebugLoc DL = MI->getDebugLoc();
17182
17183   const BasicBlock *BB = MBB->getBasicBlock();
17184   MachineFunction::iterator I = MBB;
17185   ++I;
17186
17187   // For the v = xbegin(), we generate
17188   //
17189   // thisMBB:
17190   //  xbegin sinkMBB
17191   //
17192   // mainMBB:
17193   //  eax = -1
17194   //
17195   // sinkMBB:
17196   //  v = eax
17197
17198   MachineBasicBlock *thisMBB = MBB;
17199   MachineFunction *MF = MBB->getParent();
17200   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17201   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17202   MF->insert(I, mainMBB);
17203   MF->insert(I, sinkMBB);
17204
17205   // Transfer the remainder of BB and its successor edges to sinkMBB.
17206   sinkMBB->splice(sinkMBB->begin(), MBB,
17207                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17208   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17209
17210   // thisMBB:
17211   //  xbegin sinkMBB
17212   //  # fallthrough to mainMBB
17213   //  # abortion to sinkMBB
17214   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17215   thisMBB->addSuccessor(mainMBB);
17216   thisMBB->addSuccessor(sinkMBB);
17217
17218   // mainMBB:
17219   //  EAX = -1
17220   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17221   mainMBB->addSuccessor(sinkMBB);
17222
17223   // sinkMBB:
17224   // EAX is live into the sinkMBB
17225   sinkMBB->addLiveIn(X86::EAX);
17226   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17227           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17228     .addReg(X86::EAX);
17229
17230   MI->eraseFromParent();
17231   return sinkMBB;
17232 }
17233
17234 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17235 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17236 // in the .td file.
17237 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17238                                        const TargetInstrInfo *TII) {
17239   unsigned Opc;
17240   switch (MI->getOpcode()) {
17241   default: llvm_unreachable("illegal opcode!");
17242   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17243   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17244   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17245   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17246   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17247   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17248   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17249   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17250   }
17251
17252   DebugLoc dl = MI->getDebugLoc();
17253   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17254
17255   unsigned NumArgs = MI->getNumOperands();
17256   for (unsigned i = 1; i < NumArgs; ++i) {
17257     MachineOperand &Op = MI->getOperand(i);
17258     if (!(Op.isReg() && Op.isImplicit()))
17259       MIB.addOperand(Op);
17260   }
17261   if (MI->hasOneMemOperand())
17262     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17263
17264   BuildMI(*BB, MI, dl,
17265     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17266     .addReg(X86::XMM0);
17267
17268   MI->eraseFromParent();
17269   return BB;
17270 }
17271
17272 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17273 // defs in an instruction pattern
17274 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17275                                        const TargetInstrInfo *TII) {
17276   unsigned Opc;
17277   switch (MI->getOpcode()) {
17278   default: llvm_unreachable("illegal opcode!");
17279   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17280   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17281   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17282   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17283   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17284   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17285   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17286   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17287   }
17288
17289   DebugLoc dl = MI->getDebugLoc();
17290   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17291
17292   unsigned NumArgs = MI->getNumOperands(); // remove the results
17293   for (unsigned i = 1; i < NumArgs; ++i) {
17294     MachineOperand &Op = MI->getOperand(i);
17295     if (!(Op.isReg() && Op.isImplicit()))
17296       MIB.addOperand(Op);
17297   }
17298   if (MI->hasOneMemOperand())
17299     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17300
17301   BuildMI(*BB, MI, dl,
17302     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17303     .addReg(X86::ECX);
17304
17305   MI->eraseFromParent();
17306   return BB;
17307 }
17308
17309 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17310                                        const TargetInstrInfo *TII,
17311                                        const X86Subtarget* Subtarget) {
17312   DebugLoc dl = MI->getDebugLoc();
17313
17314   // Address into RAX/EAX, other two args into ECX, EDX.
17315   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17316   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17317   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17318   for (int i = 0; i < X86::AddrNumOperands; ++i)
17319     MIB.addOperand(MI->getOperand(i));
17320
17321   unsigned ValOps = X86::AddrNumOperands;
17322   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17323     .addReg(MI->getOperand(ValOps).getReg());
17324   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17325     .addReg(MI->getOperand(ValOps+1).getReg());
17326
17327   // The instruction doesn't actually take any operands though.
17328   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17329
17330   MI->eraseFromParent(); // The pseudo is gone now.
17331   return BB;
17332 }
17333
17334 MachineBasicBlock *
17335 X86TargetLowering::EmitVAARG64WithCustomInserter(
17336                    MachineInstr *MI,
17337                    MachineBasicBlock *MBB) const {
17338   // Emit va_arg instruction on X86-64.
17339
17340   // Operands to this pseudo-instruction:
17341   // 0  ) Output        : destination address (reg)
17342   // 1-5) Input         : va_list address (addr, i64mem)
17343   // 6  ) ArgSize       : Size (in bytes) of vararg type
17344   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17345   // 8  ) Align         : Alignment of type
17346   // 9  ) EFLAGS (implicit-def)
17347
17348   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17349   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17350
17351   unsigned DestReg = MI->getOperand(0).getReg();
17352   MachineOperand &Base = MI->getOperand(1);
17353   MachineOperand &Scale = MI->getOperand(2);
17354   MachineOperand &Index = MI->getOperand(3);
17355   MachineOperand &Disp = MI->getOperand(4);
17356   MachineOperand &Segment = MI->getOperand(5);
17357   unsigned ArgSize = MI->getOperand(6).getImm();
17358   unsigned ArgMode = MI->getOperand(7).getImm();
17359   unsigned Align = MI->getOperand(8).getImm();
17360
17361   // Memory Reference
17362   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17363   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17364   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17365
17366   // Machine Information
17367   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17368   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17369   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17370   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17371   DebugLoc DL = MI->getDebugLoc();
17372
17373   // struct va_list {
17374   //   i32   gp_offset
17375   //   i32   fp_offset
17376   //   i64   overflow_area (address)
17377   //   i64   reg_save_area (address)
17378   // }
17379   // sizeof(va_list) = 24
17380   // alignment(va_list) = 8
17381
17382   unsigned TotalNumIntRegs = 6;
17383   unsigned TotalNumXMMRegs = 8;
17384   bool UseGPOffset = (ArgMode == 1);
17385   bool UseFPOffset = (ArgMode == 2);
17386   unsigned MaxOffset = TotalNumIntRegs * 8 +
17387                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17388
17389   /* Align ArgSize to a multiple of 8 */
17390   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17391   bool NeedsAlign = (Align > 8);
17392
17393   MachineBasicBlock *thisMBB = MBB;
17394   MachineBasicBlock *overflowMBB;
17395   MachineBasicBlock *offsetMBB;
17396   MachineBasicBlock *endMBB;
17397
17398   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17399   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17400   unsigned OffsetReg = 0;
17401
17402   if (!UseGPOffset && !UseFPOffset) {
17403     // If we only pull from the overflow region, we don't create a branch.
17404     // We don't need to alter control flow.
17405     OffsetDestReg = 0; // unused
17406     OverflowDestReg = DestReg;
17407
17408     offsetMBB = nullptr;
17409     overflowMBB = thisMBB;
17410     endMBB = thisMBB;
17411   } else {
17412     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17413     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17414     // If not, pull from overflow_area. (branch to overflowMBB)
17415     //
17416     //       thisMBB
17417     //         |     .
17418     //         |        .
17419     //     offsetMBB   overflowMBB
17420     //         |        .
17421     //         |     .
17422     //        endMBB
17423
17424     // Registers for the PHI in endMBB
17425     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17426     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17427
17428     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17429     MachineFunction *MF = MBB->getParent();
17430     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17431     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17432     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17433
17434     MachineFunction::iterator MBBIter = MBB;
17435     ++MBBIter;
17436
17437     // Insert the new basic blocks
17438     MF->insert(MBBIter, offsetMBB);
17439     MF->insert(MBBIter, overflowMBB);
17440     MF->insert(MBBIter, endMBB);
17441
17442     // Transfer the remainder of MBB and its successor edges to endMBB.
17443     endMBB->splice(endMBB->begin(), thisMBB,
17444                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17445     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17446
17447     // Make offsetMBB and overflowMBB successors of thisMBB
17448     thisMBB->addSuccessor(offsetMBB);
17449     thisMBB->addSuccessor(overflowMBB);
17450
17451     // endMBB is a successor of both offsetMBB and overflowMBB
17452     offsetMBB->addSuccessor(endMBB);
17453     overflowMBB->addSuccessor(endMBB);
17454
17455     // Load the offset value into a register
17456     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17457     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17458       .addOperand(Base)
17459       .addOperand(Scale)
17460       .addOperand(Index)
17461       .addDisp(Disp, UseFPOffset ? 4 : 0)
17462       .addOperand(Segment)
17463       .setMemRefs(MMOBegin, MMOEnd);
17464
17465     // Check if there is enough room left to pull this argument.
17466     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17467       .addReg(OffsetReg)
17468       .addImm(MaxOffset + 8 - ArgSizeA8);
17469
17470     // Branch to "overflowMBB" if offset >= max
17471     // Fall through to "offsetMBB" otherwise
17472     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17473       .addMBB(overflowMBB);
17474   }
17475
17476   // In offsetMBB, emit code to use the reg_save_area.
17477   if (offsetMBB) {
17478     assert(OffsetReg != 0);
17479
17480     // Read the reg_save_area address.
17481     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17482     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17483       .addOperand(Base)
17484       .addOperand(Scale)
17485       .addOperand(Index)
17486       .addDisp(Disp, 16)
17487       .addOperand(Segment)
17488       .setMemRefs(MMOBegin, MMOEnd);
17489
17490     // Zero-extend the offset
17491     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17492       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17493         .addImm(0)
17494         .addReg(OffsetReg)
17495         .addImm(X86::sub_32bit);
17496
17497     // Add the offset to the reg_save_area to get the final address.
17498     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17499       .addReg(OffsetReg64)
17500       .addReg(RegSaveReg);
17501
17502     // Compute the offset for the next argument
17503     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17504     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17505       .addReg(OffsetReg)
17506       .addImm(UseFPOffset ? 16 : 8);
17507
17508     // Store it back into the va_list.
17509     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17510       .addOperand(Base)
17511       .addOperand(Scale)
17512       .addOperand(Index)
17513       .addDisp(Disp, UseFPOffset ? 4 : 0)
17514       .addOperand(Segment)
17515       .addReg(NextOffsetReg)
17516       .setMemRefs(MMOBegin, MMOEnd);
17517
17518     // Jump to endMBB
17519     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17520       .addMBB(endMBB);
17521   }
17522
17523   //
17524   // Emit code to use overflow area
17525   //
17526
17527   // Load the overflow_area address into a register.
17528   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17529   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17530     .addOperand(Base)
17531     .addOperand(Scale)
17532     .addOperand(Index)
17533     .addDisp(Disp, 8)
17534     .addOperand(Segment)
17535     .setMemRefs(MMOBegin, MMOEnd);
17536
17537   // If we need to align it, do so. Otherwise, just copy the address
17538   // to OverflowDestReg.
17539   if (NeedsAlign) {
17540     // Align the overflow address
17541     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17542     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17543
17544     // aligned_addr = (addr + (align-1)) & ~(align-1)
17545     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17546       .addReg(OverflowAddrReg)
17547       .addImm(Align-1);
17548
17549     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17550       .addReg(TmpReg)
17551       .addImm(~(uint64_t)(Align-1));
17552   } else {
17553     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17554       .addReg(OverflowAddrReg);
17555   }
17556
17557   // Compute the next overflow address after this argument.
17558   // (the overflow address should be kept 8-byte aligned)
17559   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17560   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17561     .addReg(OverflowDestReg)
17562     .addImm(ArgSizeA8);
17563
17564   // Store the new overflow address.
17565   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17566     .addOperand(Base)
17567     .addOperand(Scale)
17568     .addOperand(Index)
17569     .addDisp(Disp, 8)
17570     .addOperand(Segment)
17571     .addReg(NextAddrReg)
17572     .setMemRefs(MMOBegin, MMOEnd);
17573
17574   // If we branched, emit the PHI to the front of endMBB.
17575   if (offsetMBB) {
17576     BuildMI(*endMBB, endMBB->begin(), DL,
17577             TII->get(X86::PHI), DestReg)
17578       .addReg(OffsetDestReg).addMBB(offsetMBB)
17579       .addReg(OverflowDestReg).addMBB(overflowMBB);
17580   }
17581
17582   // Erase the pseudo instruction
17583   MI->eraseFromParent();
17584
17585   return endMBB;
17586 }
17587
17588 MachineBasicBlock *
17589 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17590                                                  MachineInstr *MI,
17591                                                  MachineBasicBlock *MBB) const {
17592   // Emit code to save XMM registers to the stack. The ABI says that the
17593   // number of registers to save is given in %al, so it's theoretically
17594   // possible to do an indirect jump trick to avoid saving all of them,
17595   // however this code takes a simpler approach and just executes all
17596   // of the stores if %al is non-zero. It's less code, and it's probably
17597   // easier on the hardware branch predictor, and stores aren't all that
17598   // expensive anyway.
17599
17600   // Create the new basic blocks. One block contains all the XMM stores,
17601   // and one block is the final destination regardless of whether any
17602   // stores were performed.
17603   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17604   MachineFunction *F = MBB->getParent();
17605   MachineFunction::iterator MBBIter = MBB;
17606   ++MBBIter;
17607   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17608   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17609   F->insert(MBBIter, XMMSaveMBB);
17610   F->insert(MBBIter, EndMBB);
17611
17612   // Transfer the remainder of MBB and its successor edges to EndMBB.
17613   EndMBB->splice(EndMBB->begin(), MBB,
17614                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17615   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17616
17617   // The original block will now fall through to the XMM save block.
17618   MBB->addSuccessor(XMMSaveMBB);
17619   // The XMMSaveMBB will fall through to the end block.
17620   XMMSaveMBB->addSuccessor(EndMBB);
17621
17622   // Now add the instructions.
17623   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17624   DebugLoc DL = MI->getDebugLoc();
17625
17626   unsigned CountReg = MI->getOperand(0).getReg();
17627   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17628   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17629
17630   if (!Subtarget->isTargetWin64()) {
17631     // If %al is 0, branch around the XMM save block.
17632     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17633     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17634     MBB->addSuccessor(EndMBB);
17635   }
17636
17637   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17638   // that was just emitted, but clearly shouldn't be "saved".
17639   assert((MI->getNumOperands() <= 3 ||
17640           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17641           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17642          && "Expected last argument to be EFLAGS");
17643   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17644   // In the XMM save block, save all the XMM argument registers.
17645   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17646     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17647     MachineMemOperand *MMO =
17648       F->getMachineMemOperand(
17649           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17650         MachineMemOperand::MOStore,
17651         /*Size=*/16, /*Align=*/16);
17652     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17653       .addFrameIndex(RegSaveFrameIndex)
17654       .addImm(/*Scale=*/1)
17655       .addReg(/*IndexReg=*/0)
17656       .addImm(/*Disp=*/Offset)
17657       .addReg(/*Segment=*/0)
17658       .addReg(MI->getOperand(i).getReg())
17659       .addMemOperand(MMO);
17660   }
17661
17662   MI->eraseFromParent();   // The pseudo instruction is gone now.
17663
17664   return EndMBB;
17665 }
17666
17667 // The EFLAGS operand of SelectItr might be missing a kill marker
17668 // because there were multiple uses of EFLAGS, and ISel didn't know
17669 // which to mark. Figure out whether SelectItr should have had a
17670 // kill marker, and set it if it should. Returns the correct kill
17671 // marker value.
17672 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17673                                      MachineBasicBlock* BB,
17674                                      const TargetRegisterInfo* TRI) {
17675   // Scan forward through BB for a use/def of EFLAGS.
17676   MachineBasicBlock::iterator miI(std::next(SelectItr));
17677   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17678     const MachineInstr& mi = *miI;
17679     if (mi.readsRegister(X86::EFLAGS))
17680       return false;
17681     if (mi.definesRegister(X86::EFLAGS))
17682       break; // Should have kill-flag - update below.
17683   }
17684
17685   // If we hit the end of the block, check whether EFLAGS is live into a
17686   // successor.
17687   if (miI == BB->end()) {
17688     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17689                                           sEnd = BB->succ_end();
17690          sItr != sEnd; ++sItr) {
17691       MachineBasicBlock* succ = *sItr;
17692       if (succ->isLiveIn(X86::EFLAGS))
17693         return false;
17694     }
17695   }
17696
17697   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17698   // out. SelectMI should have a kill flag on EFLAGS.
17699   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17700   return true;
17701 }
17702
17703 MachineBasicBlock *
17704 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17705                                      MachineBasicBlock *BB) const {
17706   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17707   DebugLoc DL = MI->getDebugLoc();
17708
17709   // To "insert" a SELECT_CC instruction, we actually have to insert the
17710   // diamond control-flow pattern.  The incoming instruction knows the
17711   // destination vreg to set, the condition code register to branch on, the
17712   // true/false values to select between, and a branch opcode to use.
17713   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17714   MachineFunction::iterator It = BB;
17715   ++It;
17716
17717   //  thisMBB:
17718   //  ...
17719   //   TrueVal = ...
17720   //   cmpTY ccX, r1, r2
17721   //   bCC copy1MBB
17722   //   fallthrough --> copy0MBB
17723   MachineBasicBlock *thisMBB = BB;
17724   MachineFunction *F = BB->getParent();
17725   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17726   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17727   F->insert(It, copy0MBB);
17728   F->insert(It, sinkMBB);
17729
17730   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17731   // live into the sink and copy blocks.
17732   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17733   if (!MI->killsRegister(X86::EFLAGS) &&
17734       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17735     copy0MBB->addLiveIn(X86::EFLAGS);
17736     sinkMBB->addLiveIn(X86::EFLAGS);
17737   }
17738
17739   // Transfer the remainder of BB and its successor edges to sinkMBB.
17740   sinkMBB->splice(sinkMBB->begin(), BB,
17741                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17742   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17743
17744   // Add the true and fallthrough blocks as its successors.
17745   BB->addSuccessor(copy0MBB);
17746   BB->addSuccessor(sinkMBB);
17747
17748   // Create the conditional branch instruction.
17749   unsigned Opc =
17750     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17751   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17752
17753   //  copy0MBB:
17754   //   %FalseValue = ...
17755   //   # fallthrough to sinkMBB
17756   copy0MBB->addSuccessor(sinkMBB);
17757
17758   //  sinkMBB:
17759   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17760   //  ...
17761   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17762           TII->get(X86::PHI), MI->getOperand(0).getReg())
17763     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17764     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17765
17766   MI->eraseFromParent();   // The pseudo instruction is gone now.
17767   return sinkMBB;
17768 }
17769
17770 MachineBasicBlock *
17771 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17772                                         bool Is64Bit) const {
17773   MachineFunction *MF = BB->getParent();
17774   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17775   DebugLoc DL = MI->getDebugLoc();
17776   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17777
17778   assert(MF->shouldSplitStack());
17779
17780   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17781   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17782
17783   // BB:
17784   //  ... [Till the alloca]
17785   // If stacklet is not large enough, jump to mallocMBB
17786   //
17787   // bumpMBB:
17788   //  Allocate by subtracting from RSP
17789   //  Jump to continueMBB
17790   //
17791   // mallocMBB:
17792   //  Allocate by call to runtime
17793   //
17794   // continueMBB:
17795   //  ...
17796   //  [rest of original BB]
17797   //
17798
17799   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17800   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17801   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17802
17803   MachineRegisterInfo &MRI = MF->getRegInfo();
17804   const TargetRegisterClass *AddrRegClass =
17805     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17806
17807   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17808     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17809     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17810     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17811     sizeVReg = MI->getOperand(1).getReg(),
17812     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17813
17814   MachineFunction::iterator MBBIter = BB;
17815   ++MBBIter;
17816
17817   MF->insert(MBBIter, bumpMBB);
17818   MF->insert(MBBIter, mallocMBB);
17819   MF->insert(MBBIter, continueMBB);
17820
17821   continueMBB->splice(continueMBB->begin(), BB,
17822                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17823   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17824
17825   // Add code to the main basic block to check if the stack limit has been hit,
17826   // and if so, jump to mallocMBB otherwise to bumpMBB.
17827   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17828   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17829     .addReg(tmpSPVReg).addReg(sizeVReg);
17830   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17831     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17832     .addReg(SPLimitVReg);
17833   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17834
17835   // bumpMBB simply decreases the stack pointer, since we know the current
17836   // stacklet has enough space.
17837   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17838     .addReg(SPLimitVReg);
17839   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17840     .addReg(SPLimitVReg);
17841   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17842
17843   // Calls into a routine in libgcc to allocate more space from the heap.
17844   const uint32_t *RegMask =
17845     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17846   if (Is64Bit) {
17847     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17848       .addReg(sizeVReg);
17849     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17850       .addExternalSymbol("__morestack_allocate_stack_space")
17851       .addRegMask(RegMask)
17852       .addReg(X86::RDI, RegState::Implicit)
17853       .addReg(X86::RAX, RegState::ImplicitDefine);
17854   } else {
17855     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17856       .addImm(12);
17857     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17858     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17859       .addExternalSymbol("__morestack_allocate_stack_space")
17860       .addRegMask(RegMask)
17861       .addReg(X86::EAX, RegState::ImplicitDefine);
17862   }
17863
17864   if (!Is64Bit)
17865     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17866       .addImm(16);
17867
17868   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17869     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17870   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17871
17872   // Set up the CFG correctly.
17873   BB->addSuccessor(bumpMBB);
17874   BB->addSuccessor(mallocMBB);
17875   mallocMBB->addSuccessor(continueMBB);
17876   bumpMBB->addSuccessor(continueMBB);
17877
17878   // Take care of the PHI nodes.
17879   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17880           MI->getOperand(0).getReg())
17881     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17882     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17883
17884   // Delete the original pseudo instruction.
17885   MI->eraseFromParent();
17886
17887   // And we're done.
17888   return continueMBB;
17889 }
17890
17891 MachineBasicBlock *
17892 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17893                                         MachineBasicBlock *BB) const {
17894   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17895   DebugLoc DL = MI->getDebugLoc();
17896
17897   assert(!Subtarget->isTargetMacho());
17898
17899   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17900   // non-trivial part is impdef of ESP.
17901
17902   if (Subtarget->isTargetWin64()) {
17903     if (Subtarget->isTargetCygMing()) {
17904       // ___chkstk(Mingw64):
17905       // Clobbers R10, R11, RAX and EFLAGS.
17906       // Updates RSP.
17907       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17908         .addExternalSymbol("___chkstk")
17909         .addReg(X86::RAX, RegState::Implicit)
17910         .addReg(X86::RSP, RegState::Implicit)
17911         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17912         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17913         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17914     } else {
17915       // __chkstk(MSVCRT): does not update stack pointer.
17916       // Clobbers R10, R11 and EFLAGS.
17917       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17918         .addExternalSymbol("__chkstk")
17919         .addReg(X86::RAX, RegState::Implicit)
17920         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17921       // RAX has the offset to be subtracted from RSP.
17922       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17923         .addReg(X86::RSP)
17924         .addReg(X86::RAX);
17925     }
17926   } else {
17927     const char *StackProbeSymbol =
17928       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17929
17930     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17931       .addExternalSymbol(StackProbeSymbol)
17932       .addReg(X86::EAX, RegState::Implicit)
17933       .addReg(X86::ESP, RegState::Implicit)
17934       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17935       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17936       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17937   }
17938
17939   MI->eraseFromParent();   // The pseudo instruction is gone now.
17940   return BB;
17941 }
17942
17943 MachineBasicBlock *
17944 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17945                                       MachineBasicBlock *BB) const {
17946   // This is pretty easy.  We're taking the value that we received from
17947   // our load from the relocation, sticking it in either RDI (x86-64)
17948   // or EAX and doing an indirect call.  The return value will then
17949   // be in the normal return register.
17950   MachineFunction *F = BB->getParent();
17951   const X86InstrInfo *TII
17952     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17953   DebugLoc DL = MI->getDebugLoc();
17954
17955   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17956   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17957
17958   // Get a register mask for the lowered call.
17959   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17960   // proper register mask.
17961   const uint32_t *RegMask =
17962     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17963   if (Subtarget->is64Bit()) {
17964     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17965                                       TII->get(X86::MOV64rm), X86::RDI)
17966     .addReg(X86::RIP)
17967     .addImm(0).addReg(0)
17968     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17969                       MI->getOperand(3).getTargetFlags())
17970     .addReg(0);
17971     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17972     addDirectMem(MIB, X86::RDI);
17973     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17974   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17975     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17976                                       TII->get(X86::MOV32rm), X86::EAX)
17977     .addReg(0)
17978     .addImm(0).addReg(0)
17979     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17980                       MI->getOperand(3).getTargetFlags())
17981     .addReg(0);
17982     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17983     addDirectMem(MIB, X86::EAX);
17984     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17985   } else {
17986     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17987                                       TII->get(X86::MOV32rm), X86::EAX)
17988     .addReg(TII->getGlobalBaseReg(F))
17989     .addImm(0).addReg(0)
17990     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17991                       MI->getOperand(3).getTargetFlags())
17992     .addReg(0);
17993     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17994     addDirectMem(MIB, X86::EAX);
17995     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17996   }
17997
17998   MI->eraseFromParent(); // The pseudo instruction is gone now.
17999   return BB;
18000 }
18001
18002 MachineBasicBlock *
18003 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18004                                     MachineBasicBlock *MBB) const {
18005   DebugLoc DL = MI->getDebugLoc();
18006   MachineFunction *MF = MBB->getParent();
18007   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18008   MachineRegisterInfo &MRI = MF->getRegInfo();
18009
18010   const BasicBlock *BB = MBB->getBasicBlock();
18011   MachineFunction::iterator I = MBB;
18012   ++I;
18013
18014   // Memory Reference
18015   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18016   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18017
18018   unsigned DstReg;
18019   unsigned MemOpndSlot = 0;
18020
18021   unsigned CurOp = 0;
18022
18023   DstReg = MI->getOperand(CurOp++).getReg();
18024   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18025   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18026   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18027   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18028
18029   MemOpndSlot = CurOp;
18030
18031   MVT PVT = getPointerTy();
18032   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18033          "Invalid Pointer Size!");
18034
18035   // For v = setjmp(buf), we generate
18036   //
18037   // thisMBB:
18038   //  buf[LabelOffset] = restoreMBB
18039   //  SjLjSetup restoreMBB
18040   //
18041   // mainMBB:
18042   //  v_main = 0
18043   //
18044   // sinkMBB:
18045   //  v = phi(main, restore)
18046   //
18047   // restoreMBB:
18048   //  v_restore = 1
18049
18050   MachineBasicBlock *thisMBB = MBB;
18051   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18052   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18053   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18054   MF->insert(I, mainMBB);
18055   MF->insert(I, sinkMBB);
18056   MF->push_back(restoreMBB);
18057
18058   MachineInstrBuilder MIB;
18059
18060   // Transfer the remainder of BB and its successor edges to sinkMBB.
18061   sinkMBB->splice(sinkMBB->begin(), MBB,
18062                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18063   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18064
18065   // thisMBB:
18066   unsigned PtrStoreOpc = 0;
18067   unsigned LabelReg = 0;
18068   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18069   Reloc::Model RM = MF->getTarget().getRelocationModel();
18070   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18071                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18072
18073   // Prepare IP either in reg or imm.
18074   if (!UseImmLabel) {
18075     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18076     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18077     LabelReg = MRI.createVirtualRegister(PtrRC);
18078     if (Subtarget->is64Bit()) {
18079       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18080               .addReg(X86::RIP)
18081               .addImm(0)
18082               .addReg(0)
18083               .addMBB(restoreMBB)
18084               .addReg(0);
18085     } else {
18086       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18087       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18088               .addReg(XII->getGlobalBaseReg(MF))
18089               .addImm(0)
18090               .addReg(0)
18091               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18092               .addReg(0);
18093     }
18094   } else
18095     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18096   // Store IP
18097   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18098   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18099     if (i == X86::AddrDisp)
18100       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18101     else
18102       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18103   }
18104   if (!UseImmLabel)
18105     MIB.addReg(LabelReg);
18106   else
18107     MIB.addMBB(restoreMBB);
18108   MIB.setMemRefs(MMOBegin, MMOEnd);
18109   // Setup
18110   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18111           .addMBB(restoreMBB);
18112
18113   const X86RegisterInfo *RegInfo =
18114     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18115   MIB.addRegMask(RegInfo->getNoPreservedMask());
18116   thisMBB->addSuccessor(mainMBB);
18117   thisMBB->addSuccessor(restoreMBB);
18118
18119   // mainMBB:
18120   //  EAX = 0
18121   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18122   mainMBB->addSuccessor(sinkMBB);
18123
18124   // sinkMBB:
18125   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18126           TII->get(X86::PHI), DstReg)
18127     .addReg(mainDstReg).addMBB(mainMBB)
18128     .addReg(restoreDstReg).addMBB(restoreMBB);
18129
18130   // restoreMBB:
18131   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18132   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18133   restoreMBB->addSuccessor(sinkMBB);
18134
18135   MI->eraseFromParent();
18136   return sinkMBB;
18137 }
18138
18139 MachineBasicBlock *
18140 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18141                                      MachineBasicBlock *MBB) const {
18142   DebugLoc DL = MI->getDebugLoc();
18143   MachineFunction *MF = MBB->getParent();
18144   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18145   MachineRegisterInfo &MRI = MF->getRegInfo();
18146
18147   // Memory Reference
18148   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18149   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18150
18151   MVT PVT = getPointerTy();
18152   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18153          "Invalid Pointer Size!");
18154
18155   const TargetRegisterClass *RC =
18156     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18157   unsigned Tmp = MRI.createVirtualRegister(RC);
18158   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18159   const X86RegisterInfo *RegInfo =
18160     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18161   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18162   unsigned SP = RegInfo->getStackRegister();
18163
18164   MachineInstrBuilder MIB;
18165
18166   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18167   const int64_t SPOffset = 2 * PVT.getStoreSize();
18168
18169   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18170   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18171
18172   // Reload FP
18173   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18174   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18175     MIB.addOperand(MI->getOperand(i));
18176   MIB.setMemRefs(MMOBegin, MMOEnd);
18177   // Reload IP
18178   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18179   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18180     if (i == X86::AddrDisp)
18181       MIB.addDisp(MI->getOperand(i), LabelOffset);
18182     else
18183       MIB.addOperand(MI->getOperand(i));
18184   }
18185   MIB.setMemRefs(MMOBegin, MMOEnd);
18186   // Reload SP
18187   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18188   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18189     if (i == X86::AddrDisp)
18190       MIB.addDisp(MI->getOperand(i), SPOffset);
18191     else
18192       MIB.addOperand(MI->getOperand(i));
18193   }
18194   MIB.setMemRefs(MMOBegin, MMOEnd);
18195   // Jump
18196   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18197
18198   MI->eraseFromParent();
18199   return MBB;
18200 }
18201
18202 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18203 // accumulator loops. Writing back to the accumulator allows the coalescer
18204 // to remove extra copies in the loop.   
18205 MachineBasicBlock *
18206 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18207                                  MachineBasicBlock *MBB) const {
18208   MachineOperand &AddendOp = MI->getOperand(3);
18209
18210   // Bail out early if the addend isn't a register - we can't switch these.
18211   if (!AddendOp.isReg())
18212     return MBB;
18213
18214   MachineFunction &MF = *MBB->getParent();
18215   MachineRegisterInfo &MRI = MF.getRegInfo();
18216
18217   // Check whether the addend is defined by a PHI:
18218   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18219   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18220   if (!AddendDef.isPHI())
18221     return MBB;
18222
18223   // Look for the following pattern:
18224   // loop:
18225   //   %addend = phi [%entry, 0], [%loop, %result]
18226   //   ...
18227   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18228
18229   // Replace with:
18230   //   loop:
18231   //   %addend = phi [%entry, 0], [%loop, %result]
18232   //   ...
18233   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18234
18235   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18236     assert(AddendDef.getOperand(i).isReg());
18237     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18238     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18239     if (&PHISrcInst == MI) {
18240       // Found a matching instruction.
18241       unsigned NewFMAOpc = 0;
18242       switch (MI->getOpcode()) {
18243         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18244         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18245         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18246         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18247         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18248         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18249         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18250         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18251         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18252         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18253         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18254         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18255         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18256         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18257         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18258         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18259         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18260         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18261         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18262         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18263         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18264         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18265         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18266         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18267         default: llvm_unreachable("Unrecognized FMA variant.");
18268       }
18269
18270       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18271       MachineInstrBuilder MIB =
18272         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18273         .addOperand(MI->getOperand(0))
18274         .addOperand(MI->getOperand(3))
18275         .addOperand(MI->getOperand(2))
18276         .addOperand(MI->getOperand(1));
18277       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18278       MI->eraseFromParent();
18279     }
18280   }
18281
18282   return MBB;
18283 }
18284
18285 MachineBasicBlock *
18286 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18287                                                MachineBasicBlock *BB) const {
18288   switch (MI->getOpcode()) {
18289   default: llvm_unreachable("Unexpected instr type to insert");
18290   case X86::TAILJMPd64:
18291   case X86::TAILJMPr64:
18292   case X86::TAILJMPm64:
18293     llvm_unreachable("TAILJMP64 would not be touched here.");
18294   case X86::TCRETURNdi64:
18295   case X86::TCRETURNri64:
18296   case X86::TCRETURNmi64:
18297     return BB;
18298   case X86::WIN_ALLOCA:
18299     return EmitLoweredWinAlloca(MI, BB);
18300   case X86::SEG_ALLOCA_32:
18301     return EmitLoweredSegAlloca(MI, BB, false);
18302   case X86::SEG_ALLOCA_64:
18303     return EmitLoweredSegAlloca(MI, BB, true);
18304   case X86::TLSCall_32:
18305   case X86::TLSCall_64:
18306     return EmitLoweredTLSCall(MI, BB);
18307   case X86::CMOV_GR8:
18308   case X86::CMOV_FR32:
18309   case X86::CMOV_FR64:
18310   case X86::CMOV_V4F32:
18311   case X86::CMOV_V2F64:
18312   case X86::CMOV_V2I64:
18313   case X86::CMOV_V8F32:
18314   case X86::CMOV_V4F64:
18315   case X86::CMOV_V4I64:
18316   case X86::CMOV_V16F32:
18317   case X86::CMOV_V8F64:
18318   case X86::CMOV_V8I64:
18319   case X86::CMOV_GR16:
18320   case X86::CMOV_GR32:
18321   case X86::CMOV_RFP32:
18322   case X86::CMOV_RFP64:
18323   case X86::CMOV_RFP80:
18324     return EmitLoweredSelect(MI, BB);
18325
18326   case X86::FP32_TO_INT16_IN_MEM:
18327   case X86::FP32_TO_INT32_IN_MEM:
18328   case X86::FP32_TO_INT64_IN_MEM:
18329   case X86::FP64_TO_INT16_IN_MEM:
18330   case X86::FP64_TO_INT32_IN_MEM:
18331   case X86::FP64_TO_INT64_IN_MEM:
18332   case X86::FP80_TO_INT16_IN_MEM:
18333   case X86::FP80_TO_INT32_IN_MEM:
18334   case X86::FP80_TO_INT64_IN_MEM: {
18335     MachineFunction *F = BB->getParent();
18336     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18337     DebugLoc DL = MI->getDebugLoc();
18338
18339     // Change the floating point control register to use "round towards zero"
18340     // mode when truncating to an integer value.
18341     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18342     addFrameReference(BuildMI(*BB, MI, DL,
18343                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18344
18345     // Load the old value of the high byte of the control word...
18346     unsigned OldCW =
18347       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18348     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18349                       CWFrameIdx);
18350
18351     // Set the high part to be round to zero...
18352     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18353       .addImm(0xC7F);
18354
18355     // Reload the modified control word now...
18356     addFrameReference(BuildMI(*BB, MI, DL,
18357                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18358
18359     // Restore the memory image of control word to original value
18360     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18361       .addReg(OldCW);
18362
18363     // Get the X86 opcode to use.
18364     unsigned Opc;
18365     switch (MI->getOpcode()) {
18366     default: llvm_unreachable("illegal opcode!");
18367     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18368     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18369     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18370     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18371     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18372     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18373     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18374     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18375     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18376     }
18377
18378     X86AddressMode AM;
18379     MachineOperand &Op = MI->getOperand(0);
18380     if (Op.isReg()) {
18381       AM.BaseType = X86AddressMode::RegBase;
18382       AM.Base.Reg = Op.getReg();
18383     } else {
18384       AM.BaseType = X86AddressMode::FrameIndexBase;
18385       AM.Base.FrameIndex = Op.getIndex();
18386     }
18387     Op = MI->getOperand(1);
18388     if (Op.isImm())
18389       AM.Scale = Op.getImm();
18390     Op = MI->getOperand(2);
18391     if (Op.isImm())
18392       AM.IndexReg = Op.getImm();
18393     Op = MI->getOperand(3);
18394     if (Op.isGlobal()) {
18395       AM.GV = Op.getGlobal();
18396     } else {
18397       AM.Disp = Op.getImm();
18398     }
18399     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18400                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18401
18402     // Reload the original control word now.
18403     addFrameReference(BuildMI(*BB, MI, DL,
18404                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18405
18406     MI->eraseFromParent();   // The pseudo instruction is gone now.
18407     return BB;
18408   }
18409     // String/text processing lowering.
18410   case X86::PCMPISTRM128REG:
18411   case X86::VPCMPISTRM128REG:
18412   case X86::PCMPISTRM128MEM:
18413   case X86::VPCMPISTRM128MEM:
18414   case X86::PCMPESTRM128REG:
18415   case X86::VPCMPESTRM128REG:
18416   case X86::PCMPESTRM128MEM:
18417   case X86::VPCMPESTRM128MEM:
18418     assert(Subtarget->hasSSE42() &&
18419            "Target must have SSE4.2 or AVX features enabled");
18420     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18421
18422   // String/text processing lowering.
18423   case X86::PCMPISTRIREG:
18424   case X86::VPCMPISTRIREG:
18425   case X86::PCMPISTRIMEM:
18426   case X86::VPCMPISTRIMEM:
18427   case X86::PCMPESTRIREG:
18428   case X86::VPCMPESTRIREG:
18429   case X86::PCMPESTRIMEM:
18430   case X86::VPCMPESTRIMEM:
18431     assert(Subtarget->hasSSE42() &&
18432            "Target must have SSE4.2 or AVX features enabled");
18433     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18434
18435   // Thread synchronization.
18436   case X86::MONITOR:
18437     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18438
18439   // xbegin
18440   case X86::XBEGIN:
18441     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18442
18443   case X86::VASTART_SAVE_XMM_REGS:
18444     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18445
18446   case X86::VAARG_64:
18447     return EmitVAARG64WithCustomInserter(MI, BB);
18448
18449   case X86::EH_SjLj_SetJmp32:
18450   case X86::EH_SjLj_SetJmp64:
18451     return emitEHSjLjSetJmp(MI, BB);
18452
18453   case X86::EH_SjLj_LongJmp32:
18454   case X86::EH_SjLj_LongJmp64:
18455     return emitEHSjLjLongJmp(MI, BB);
18456
18457   case TargetOpcode::STACKMAP:
18458   case TargetOpcode::PATCHPOINT:
18459     return emitPatchPoint(MI, BB);
18460
18461   case X86::VFMADDPDr213r:
18462   case X86::VFMADDPSr213r:
18463   case X86::VFMADDSDr213r:
18464   case X86::VFMADDSSr213r:
18465   case X86::VFMSUBPDr213r:
18466   case X86::VFMSUBPSr213r:
18467   case X86::VFMSUBSDr213r:
18468   case X86::VFMSUBSSr213r:
18469   case X86::VFNMADDPDr213r:
18470   case X86::VFNMADDPSr213r:
18471   case X86::VFNMADDSDr213r:
18472   case X86::VFNMADDSSr213r:
18473   case X86::VFNMSUBPDr213r:
18474   case X86::VFNMSUBPSr213r:
18475   case X86::VFNMSUBSDr213r:
18476   case X86::VFNMSUBSSr213r:
18477   case X86::VFMADDPDr213rY:
18478   case X86::VFMADDPSr213rY:
18479   case X86::VFMSUBPDr213rY:
18480   case X86::VFMSUBPSr213rY:
18481   case X86::VFNMADDPDr213rY:
18482   case X86::VFNMADDPSr213rY:
18483   case X86::VFNMSUBPDr213rY:
18484   case X86::VFNMSUBPSr213rY:
18485     return emitFMA3Instr(MI, BB);
18486   }
18487 }
18488
18489 //===----------------------------------------------------------------------===//
18490 //                           X86 Optimization Hooks
18491 //===----------------------------------------------------------------------===//
18492
18493 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18494                                                       APInt &KnownZero,
18495                                                       APInt &KnownOne,
18496                                                       const SelectionDAG &DAG,
18497                                                       unsigned Depth) const {
18498   unsigned BitWidth = KnownZero.getBitWidth();
18499   unsigned Opc = Op.getOpcode();
18500   assert((Opc >= ISD::BUILTIN_OP_END ||
18501           Opc == ISD::INTRINSIC_WO_CHAIN ||
18502           Opc == ISD::INTRINSIC_W_CHAIN ||
18503           Opc == ISD::INTRINSIC_VOID) &&
18504          "Should use MaskedValueIsZero if you don't know whether Op"
18505          " is a target node!");
18506
18507   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18508   switch (Opc) {
18509   default: break;
18510   case X86ISD::ADD:
18511   case X86ISD::SUB:
18512   case X86ISD::ADC:
18513   case X86ISD::SBB:
18514   case X86ISD::SMUL:
18515   case X86ISD::UMUL:
18516   case X86ISD::INC:
18517   case X86ISD::DEC:
18518   case X86ISD::OR:
18519   case X86ISD::XOR:
18520   case X86ISD::AND:
18521     // These nodes' second result is a boolean.
18522     if (Op.getResNo() == 0)
18523       break;
18524     // Fallthrough
18525   case X86ISD::SETCC:
18526     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18527     break;
18528   case ISD::INTRINSIC_WO_CHAIN: {
18529     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18530     unsigned NumLoBits = 0;
18531     switch (IntId) {
18532     default: break;
18533     case Intrinsic::x86_sse_movmsk_ps:
18534     case Intrinsic::x86_avx_movmsk_ps_256:
18535     case Intrinsic::x86_sse2_movmsk_pd:
18536     case Intrinsic::x86_avx_movmsk_pd_256:
18537     case Intrinsic::x86_mmx_pmovmskb:
18538     case Intrinsic::x86_sse2_pmovmskb_128:
18539     case Intrinsic::x86_avx2_pmovmskb: {
18540       // High bits of movmskp{s|d}, pmovmskb are known zero.
18541       switch (IntId) {
18542         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18543         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18544         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18545         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18546         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18547         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18548         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18549         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18550       }
18551       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18552       break;
18553     }
18554     }
18555     break;
18556   }
18557   }
18558 }
18559
18560 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18561   SDValue Op,
18562   const SelectionDAG &,
18563   unsigned Depth) const {
18564   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18565   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18566     return Op.getValueType().getScalarType().getSizeInBits();
18567
18568   // Fallback case.
18569   return 1;
18570 }
18571
18572 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18573 /// node is a GlobalAddress + offset.
18574 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18575                                        const GlobalValue* &GA,
18576                                        int64_t &Offset) const {
18577   if (N->getOpcode() == X86ISD::Wrapper) {
18578     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18579       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18580       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18581       return true;
18582     }
18583   }
18584   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18585 }
18586
18587 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18588 /// same as extracting the high 128-bit part of 256-bit vector and then
18589 /// inserting the result into the low part of a new 256-bit vector
18590 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18591   EVT VT = SVOp->getValueType(0);
18592   unsigned NumElems = VT.getVectorNumElements();
18593
18594   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18595   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18596     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18597         SVOp->getMaskElt(j) >= 0)
18598       return false;
18599
18600   return true;
18601 }
18602
18603 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18604 /// same as extracting the low 128-bit part of 256-bit vector and then
18605 /// inserting the result into the high part of a new 256-bit vector
18606 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18607   EVT VT = SVOp->getValueType(0);
18608   unsigned NumElems = VT.getVectorNumElements();
18609
18610   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18611   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18612     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18613         SVOp->getMaskElt(j) >= 0)
18614       return false;
18615
18616   return true;
18617 }
18618
18619 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18620 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18621                                         TargetLowering::DAGCombinerInfo &DCI,
18622                                         const X86Subtarget* Subtarget) {
18623   SDLoc dl(N);
18624   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18625   SDValue V1 = SVOp->getOperand(0);
18626   SDValue V2 = SVOp->getOperand(1);
18627   EVT VT = SVOp->getValueType(0);
18628   unsigned NumElems = VT.getVectorNumElements();
18629
18630   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18631       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18632     //
18633     //                   0,0,0,...
18634     //                      |
18635     //    V      UNDEF    BUILD_VECTOR    UNDEF
18636     //     \      /           \           /
18637     //  CONCAT_VECTOR         CONCAT_VECTOR
18638     //         \                  /
18639     //          \                /
18640     //          RESULT: V + zero extended
18641     //
18642     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18643         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18644         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18645       return SDValue();
18646
18647     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18648       return SDValue();
18649
18650     // To match the shuffle mask, the first half of the mask should
18651     // be exactly the first vector, and all the rest a splat with the
18652     // first element of the second one.
18653     for (unsigned i = 0; i != NumElems/2; ++i)
18654       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18655           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18656         return SDValue();
18657
18658     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18659     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18660       if (Ld->hasNUsesOfValue(1, 0)) {
18661         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18662         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18663         SDValue ResNode =
18664           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18665                                   Ld->getMemoryVT(),
18666                                   Ld->getPointerInfo(),
18667                                   Ld->getAlignment(),
18668                                   false/*isVolatile*/, true/*ReadMem*/,
18669                                   false/*WriteMem*/);
18670
18671         // Make sure the newly-created LOAD is in the same position as Ld in
18672         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18673         // and update uses of Ld's output chain to use the TokenFactor.
18674         if (Ld->hasAnyUseOfValue(1)) {
18675           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18676                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18677           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18678           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18679                                  SDValue(ResNode.getNode(), 1));
18680         }
18681
18682         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18683       }
18684     }
18685
18686     // Emit a zeroed vector and insert the desired subvector on its
18687     // first half.
18688     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18689     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18690     return DCI.CombineTo(N, InsV);
18691   }
18692
18693   //===--------------------------------------------------------------------===//
18694   // Combine some shuffles into subvector extracts and inserts:
18695   //
18696
18697   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18698   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18699     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18700     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18701     return DCI.CombineTo(N, InsV);
18702   }
18703
18704   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18705   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18706     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18707     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18708     return DCI.CombineTo(N, InsV);
18709   }
18710
18711   return SDValue();
18712 }
18713
18714 /// \brief Get the PSHUF-style mask from PSHUF node.
18715 ///
18716 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18717 /// PSHUF-style masks that can be reused with such instructions.
18718 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18719   SmallVector<int, 4> Mask;
18720   bool IsUnary;
18721   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18722   (void)HaveMask;
18723   assert(HaveMask);
18724
18725   switch (N.getOpcode()) {
18726   case X86ISD::PSHUFD:
18727     return Mask;
18728   case X86ISD::PSHUFLW:
18729     Mask.resize(4);
18730     return Mask;
18731   case X86ISD::PSHUFHW:
18732     Mask.erase(Mask.begin(), Mask.begin() + 4);
18733     for (int &M : Mask)
18734       M -= 4;
18735     return Mask;
18736   default:
18737     llvm_unreachable("No valid shuffle instruction found!");
18738   }
18739 }
18740
18741 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18742 ///
18743 /// We walk up the chain and look for a combinable shuffle, skipping over
18744 /// shuffles that we could hoist this shuffle's transformation past without
18745 /// altering anything.
18746 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18747                                          SelectionDAG &DAG,
18748                                          TargetLowering::DAGCombinerInfo &DCI) {
18749   assert(N.getOpcode() == X86ISD::PSHUFD &&
18750          "Called with something other than an x86 128-bit half shuffle!");
18751   SDLoc DL(N);
18752
18753   // Walk up a single-use chain looking for a combinable shuffle.
18754   SDValue V = N.getOperand(0);
18755   for (; V.hasOneUse(); V = V.getOperand(0)) {
18756     switch (V.getOpcode()) {
18757     default:
18758       return false; // Nothing combined!
18759
18760     case ISD::BITCAST:
18761       // Skip bitcasts as we always know the type for the target specific
18762       // instructions.
18763       continue;
18764
18765     case X86ISD::PSHUFD:
18766       // Found another dword shuffle.
18767       break;
18768
18769     case X86ISD::PSHUFLW:
18770       // Check that the low words (being shuffled) are the identity in the
18771       // dword shuffle, and the high words are self-contained.
18772       if (Mask[0] != 0 || Mask[1] != 1 ||
18773           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18774         return false;
18775
18776       continue;
18777
18778     case X86ISD::PSHUFHW:
18779       // Check that the high words (being shuffled) are the identity in the
18780       // dword shuffle, and the low words are self-contained.
18781       if (Mask[2] != 2 || Mask[3] != 3 ||
18782           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18783         return false;
18784
18785       continue;
18786
18787     case X86ISD::UNPCKL:
18788     case X86ISD::UNPCKH:
18789       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18790       // shuffle into a preceding word shuffle.
18791       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18792         return false;
18793
18794       // Search for a half-shuffle which we can combine with.
18795       unsigned CombineOp =
18796           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18797       if (V.getOperand(0) != V.getOperand(1) ||
18798           !V->isOnlyUserOf(V.getOperand(0).getNode()))
18799         return false;
18800       V = V.getOperand(0);
18801       do {
18802         switch (V.getOpcode()) {
18803         default:
18804           return false; // Nothing to combine.
18805
18806         case X86ISD::PSHUFLW:
18807         case X86ISD::PSHUFHW:
18808           if (V.getOpcode() == CombineOp)
18809             break;
18810
18811           // Fallthrough!
18812         case ISD::BITCAST:
18813           V = V.getOperand(0);
18814           continue;
18815         }
18816         break;
18817       } while (V.hasOneUse());
18818       break;
18819     }
18820     // Break out of the loop if we break out of the switch.
18821     break;
18822   }
18823
18824   if (!V.hasOneUse())
18825     // We fell out of the loop without finding a viable combining instruction.
18826     return false;
18827
18828   // Record the old value to use in RAUW-ing.
18829   SDValue Old = V;
18830
18831   // Merge this node's mask and our incoming mask.
18832   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18833   for (int &M : Mask)
18834     M = VMask[M];
18835   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18836                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18837
18838   // It is possible that one of the combinable shuffles was completely absorbed
18839   // by the other, just replace it and revisit all users in that case.
18840   if (Old.getNode() == V.getNode()) {
18841     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18842     return true;
18843   }
18844
18845   // Replace N with its operand as we're going to combine that shuffle away.
18846   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18847
18848   // Replace the combinable shuffle with the combined one, updating all users
18849   // so that we re-evaluate the chain here.
18850   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18851   return true;
18852 }
18853
18854 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18855 ///
18856 /// We walk up the chain, skipping shuffles of the other half and looking
18857 /// through shuffles which switch halves trying to find a shuffle of the same
18858 /// pair of dwords.
18859 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18860                                         SelectionDAG &DAG,
18861                                         TargetLowering::DAGCombinerInfo &DCI) {
18862   assert(
18863       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18864       "Called with something other than an x86 128-bit half shuffle!");
18865   SDLoc DL(N);
18866   unsigned CombineOpcode = N.getOpcode();
18867
18868   // Walk up a single-use chain looking for a combinable shuffle.
18869   SDValue V = N.getOperand(0);
18870   for (; V.hasOneUse(); V = V.getOperand(0)) {
18871     switch (V.getOpcode()) {
18872     default:
18873       return false; // Nothing combined!
18874
18875     case ISD::BITCAST:
18876       // Skip bitcasts as we always know the type for the target specific
18877       // instructions.
18878       continue;
18879
18880     case X86ISD::PSHUFLW:
18881     case X86ISD::PSHUFHW:
18882       if (V.getOpcode() == CombineOpcode)
18883         break;
18884
18885       // Other-half shuffles are no-ops.
18886       continue;
18887
18888     case X86ISD::PSHUFD: {
18889       // We can only handle pshufd if the half we are combining either stays in
18890       // its half, or switches to the other half. Bail if one of these isn't
18891       // true.
18892       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18893       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18894       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18895             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18896         return false;
18897
18898       // Map the mask through the pshufd and keep walking up the chain.
18899       for (int i = 0; i < 4; ++i)
18900         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18901
18902       // Switch halves if the pshufd does.
18903       CombineOpcode =
18904           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18905       continue;
18906     }
18907     }
18908     // Break out of the loop if we break out of the switch.
18909     break;
18910   }
18911
18912   if (!V.hasOneUse())
18913     // We fell out of the loop without finding a viable combining instruction.
18914     return false;
18915
18916   // Record the old value to use in RAUW-ing.
18917   SDValue Old = V;
18918
18919   // Merge this node's mask and our incoming mask (adjusted to account for all
18920   // the pshufd instructions encountered).
18921   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18922   for (int &M : Mask)
18923     M = VMask[M];
18924   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18925                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18926
18927   // Replace N with its operand as we're going to combine that shuffle away.
18928   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18929
18930   // Replace the combinable shuffle with the combined one, updating all users
18931   // so that we re-evaluate the chain here.
18932   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18933   return true;
18934 }
18935
18936 /// \brief Try to combine x86 target specific shuffles.
18937 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18938                                            TargetLowering::DAGCombinerInfo &DCI,
18939                                            const X86Subtarget *Subtarget) {
18940   SDLoc DL(N);
18941   MVT VT = N.getSimpleValueType();
18942   SmallVector<int, 4> Mask;
18943
18944   switch (N.getOpcode()) {
18945   case X86ISD::PSHUFD:
18946   case X86ISD::PSHUFLW:
18947   case X86ISD::PSHUFHW:
18948     Mask = getPSHUFShuffleMask(N);
18949     assert(Mask.size() == 4);
18950     break;
18951   default:
18952     return SDValue();
18953   }
18954
18955   // Nuke no-op shuffles that show up after combining.
18956   if (isNoopShuffleMask(Mask))
18957     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18958
18959   // Look for simplifications involving one or two shuffle instructions.
18960   SDValue V = N.getOperand(0);
18961   switch (N.getOpcode()) {
18962   default:
18963     break;
18964   case X86ISD::PSHUFLW:
18965   case X86ISD::PSHUFHW:
18966     assert(VT == MVT::v8i16);
18967     (void)VT;
18968
18969     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18970       return SDValue(); // We combined away this shuffle, so we're done.
18971
18972     // See if this reduces to a PSHUFD which is no more expensive and can
18973     // combine with more operations.
18974     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18975         areAdjacentMasksSequential(Mask)) {
18976       int DMask[] = {-1, -1, -1, -1};
18977       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18978       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18979       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18980       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18981       DCI.AddToWorklist(V.getNode());
18982       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18983                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18984       DCI.AddToWorklist(V.getNode());
18985       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18986     }
18987
18988     // Look for shuffle patterns which can be implemented as a single unpack.
18989     // FIXME: This doesn't handle the location of the PSHUFD generically, and
18990     // only works when we have a PSHUFD followed by two half-shuffles.
18991     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18992         (V.getOpcode() == X86ISD::PSHUFLW ||
18993          V.getOpcode() == X86ISD::PSHUFHW) &&
18994         V.getOpcode() != N.getOpcode() &&
18995         V.hasOneUse()) {
18996       SDValue D = V.getOperand(0);
18997       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18998         D = D.getOperand(0);
18999       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19000         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19001         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19002         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19003         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19004         int WordMask[8];
19005         for (int i = 0; i < 4; ++i) {
19006           WordMask[i + NOffset] = Mask[i] + NOffset;
19007           WordMask[i + VOffset] = VMask[i] + VOffset;
19008         }
19009         // Map the word mask through the DWord mask.
19010         int MappedMask[8];
19011         for (int i = 0; i < 8; ++i)
19012           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19013         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19014         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19015         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19016                        std::begin(UnpackLoMask)) ||
19017             std::equal(std::begin(MappedMask), std::end(MappedMask),
19018                        std::begin(UnpackHiMask))) {
19019           // We can replace all three shuffles with an unpack.
19020           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19021           DCI.AddToWorklist(V.getNode());
19022           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19023                                                 : X86ISD::UNPCKH,
19024                              DL, MVT::v8i16, V, V);
19025         }
19026       }
19027     }
19028
19029     break;
19030
19031   case X86ISD::PSHUFD:
19032     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19033       return SDValue(); // We combined away this shuffle.
19034
19035     break;
19036   }
19037
19038   return SDValue();
19039 }
19040
19041 /// PerformShuffleCombine - Performs several different shuffle combines.
19042 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19043                                      TargetLowering::DAGCombinerInfo &DCI,
19044                                      const X86Subtarget *Subtarget) {
19045   SDLoc dl(N);
19046   SDValue N0 = N->getOperand(0);
19047   SDValue N1 = N->getOperand(1);
19048   EVT VT = N->getValueType(0);
19049
19050   // Don't create instructions with illegal types after legalize types has run.
19051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19052   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19053     return SDValue();
19054
19055   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19056   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19057       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19058     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19059
19060   // During Type Legalization, when promoting illegal vector types,
19061   // the backend might introduce new shuffle dag nodes and bitcasts.
19062   //
19063   // This code performs the following transformation:
19064   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19065   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19066   //
19067   // We do this only if both the bitcast and the BINOP dag nodes have
19068   // one use. Also, perform this transformation only if the new binary
19069   // operation is legal. This is to avoid introducing dag nodes that
19070   // potentially need to be further expanded (or custom lowered) into a
19071   // less optimal sequence of dag nodes.
19072   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19073       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19074       N0.getOpcode() == ISD::BITCAST) {
19075     SDValue BC0 = N0.getOperand(0);
19076     EVT SVT = BC0.getValueType();
19077     unsigned Opcode = BC0.getOpcode();
19078     unsigned NumElts = VT.getVectorNumElements();
19079     
19080     if (BC0.hasOneUse() && SVT.isVector() &&
19081         SVT.getVectorNumElements() * 2 == NumElts &&
19082         TLI.isOperationLegal(Opcode, VT)) {
19083       bool CanFold = false;
19084       switch (Opcode) {
19085       default : break;
19086       case ISD::ADD :
19087       case ISD::FADD :
19088       case ISD::SUB :
19089       case ISD::FSUB :
19090       case ISD::MUL :
19091       case ISD::FMUL :
19092         CanFold = true;
19093       }
19094
19095       unsigned SVTNumElts = SVT.getVectorNumElements();
19096       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19097       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19098         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19099       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19100         CanFold = SVOp->getMaskElt(i) < 0;
19101
19102       if (CanFold) {
19103         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19104         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19105         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19106         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19107       }
19108     }
19109   }
19110
19111   // Only handle 128 wide vector from here on.
19112   if (!VT.is128BitVector())
19113     return SDValue();
19114
19115   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19116   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19117   // consecutive, non-overlapping, and in the right order.
19118   SmallVector<SDValue, 16> Elts;
19119   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19120     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19121
19122   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19123   if (LD.getNode())
19124     return LD;
19125
19126   if (isTargetShuffle(N->getOpcode())) {
19127     SDValue Shuffle =
19128         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19129     if (Shuffle.getNode())
19130       return Shuffle;
19131   }
19132
19133   return SDValue();
19134 }
19135
19136 /// PerformTruncateCombine - Converts truncate operation to
19137 /// a sequence of vector shuffle operations.
19138 /// It is possible when we truncate 256-bit vector to 128-bit vector
19139 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19140                                       TargetLowering::DAGCombinerInfo &DCI,
19141                                       const X86Subtarget *Subtarget)  {
19142   return SDValue();
19143 }
19144
19145 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19146 /// specific shuffle of a load can be folded into a single element load.
19147 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19148 /// shuffles have been customed lowered so we need to handle those here.
19149 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19150                                          TargetLowering::DAGCombinerInfo &DCI) {
19151   if (DCI.isBeforeLegalizeOps())
19152     return SDValue();
19153
19154   SDValue InVec = N->getOperand(0);
19155   SDValue EltNo = N->getOperand(1);
19156
19157   if (!isa<ConstantSDNode>(EltNo))
19158     return SDValue();
19159
19160   EVT VT = InVec.getValueType();
19161
19162   bool HasShuffleIntoBitcast = false;
19163   if (InVec.getOpcode() == ISD::BITCAST) {
19164     // Don't duplicate a load with other uses.
19165     if (!InVec.hasOneUse())
19166       return SDValue();
19167     EVT BCVT = InVec.getOperand(0).getValueType();
19168     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19169       return SDValue();
19170     InVec = InVec.getOperand(0);
19171     HasShuffleIntoBitcast = true;
19172   }
19173
19174   if (!isTargetShuffle(InVec.getOpcode()))
19175     return SDValue();
19176
19177   // Don't duplicate a load with other uses.
19178   if (!InVec.hasOneUse())
19179     return SDValue();
19180
19181   SmallVector<int, 16> ShuffleMask;
19182   bool UnaryShuffle;
19183   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19184                             UnaryShuffle))
19185     return SDValue();
19186
19187   // Select the input vector, guarding against out of range extract vector.
19188   unsigned NumElems = VT.getVectorNumElements();
19189   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19190   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19191   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19192                                          : InVec.getOperand(1);
19193
19194   // If inputs to shuffle are the same for both ops, then allow 2 uses
19195   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19196
19197   if (LdNode.getOpcode() == ISD::BITCAST) {
19198     // Don't duplicate a load with other uses.
19199     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19200       return SDValue();
19201
19202     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19203     LdNode = LdNode.getOperand(0);
19204   }
19205
19206   if (!ISD::isNormalLoad(LdNode.getNode()))
19207     return SDValue();
19208
19209   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19210
19211   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19212     return SDValue();
19213
19214   if (HasShuffleIntoBitcast) {
19215     // If there's a bitcast before the shuffle, check if the load type and
19216     // alignment is valid.
19217     unsigned Align = LN0->getAlignment();
19218     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19219     unsigned NewAlign = TLI.getDataLayout()->
19220       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19221
19222     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19223       return SDValue();
19224   }
19225
19226   // All checks match so transform back to vector_shuffle so that DAG combiner
19227   // can finish the job
19228   SDLoc dl(N);
19229
19230   // Create shuffle node taking into account the case that its a unary shuffle
19231   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19232   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19233                                  InVec.getOperand(0), Shuffle,
19234                                  &ShuffleMask[0]);
19235   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19236   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19237                      EltNo);
19238 }
19239
19240 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19241 /// generation and convert it from being a bunch of shuffles and extracts
19242 /// to a simple store and scalar loads to extract the elements.
19243 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19244                                          TargetLowering::DAGCombinerInfo &DCI) {
19245   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19246   if (NewOp.getNode())
19247     return NewOp;
19248
19249   SDValue InputVector = N->getOperand(0);
19250
19251   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19252   // from mmx to v2i32 has a single usage.
19253   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19254       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19255       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19256     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19257                        N->getValueType(0),
19258                        InputVector.getNode()->getOperand(0));
19259
19260   // Only operate on vectors of 4 elements, where the alternative shuffling
19261   // gets to be more expensive.
19262   if (InputVector.getValueType() != MVT::v4i32)
19263     return SDValue();
19264
19265   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19266   // single use which is a sign-extend or zero-extend, and all elements are
19267   // used.
19268   SmallVector<SDNode *, 4> Uses;
19269   unsigned ExtractedElements = 0;
19270   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19271        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19272     if (UI.getUse().getResNo() != InputVector.getResNo())
19273       return SDValue();
19274
19275     SDNode *Extract = *UI;
19276     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19277       return SDValue();
19278
19279     if (Extract->getValueType(0) != MVT::i32)
19280       return SDValue();
19281     if (!Extract->hasOneUse())
19282       return SDValue();
19283     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19284         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19285       return SDValue();
19286     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19287       return SDValue();
19288
19289     // Record which element was extracted.
19290     ExtractedElements |=
19291       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19292
19293     Uses.push_back(Extract);
19294   }
19295
19296   // If not all the elements were used, this may not be worthwhile.
19297   if (ExtractedElements != 15)
19298     return SDValue();
19299
19300   // Ok, we've now decided to do the transformation.
19301   SDLoc dl(InputVector);
19302
19303   // Store the value to a temporary stack slot.
19304   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19305   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19306                             MachinePointerInfo(), false, false, 0);
19307
19308   // Replace each use (extract) with a load of the appropriate element.
19309   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19310        UE = Uses.end(); UI != UE; ++UI) {
19311     SDNode *Extract = *UI;
19312
19313     // cOMpute the element's address.
19314     SDValue Idx = Extract->getOperand(1);
19315     unsigned EltSize =
19316         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19317     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19318     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19319     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19320
19321     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19322                                      StackPtr, OffsetVal);
19323
19324     // Load the scalar.
19325     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19326                                      ScalarAddr, MachinePointerInfo(),
19327                                      false, false, false, 0);
19328
19329     // Replace the exact with the load.
19330     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19331   }
19332
19333   // The replacement was made in place; don't return anything.
19334   return SDValue();
19335 }
19336
19337 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19338 static std::pair<unsigned, bool>
19339 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19340                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19341   if (!VT.isVector())
19342     return std::make_pair(0, false);
19343
19344   bool NeedSplit = false;
19345   switch (VT.getSimpleVT().SimpleTy) {
19346   default: return std::make_pair(0, false);
19347   case MVT::v32i8:
19348   case MVT::v16i16:
19349   case MVT::v8i32:
19350     if (!Subtarget->hasAVX2())
19351       NeedSplit = true;
19352     if (!Subtarget->hasAVX())
19353       return std::make_pair(0, false);
19354     break;
19355   case MVT::v16i8:
19356   case MVT::v8i16:
19357   case MVT::v4i32:
19358     if (!Subtarget->hasSSE2())
19359       return std::make_pair(0, false);
19360   }
19361
19362   // SSE2 has only a small subset of the operations.
19363   bool hasUnsigned = Subtarget->hasSSE41() ||
19364                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19365   bool hasSigned = Subtarget->hasSSE41() ||
19366                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19367
19368   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19369
19370   unsigned Opc = 0;
19371   // Check for x CC y ? x : y.
19372   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19373       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19374     switch (CC) {
19375     default: break;
19376     case ISD::SETULT:
19377     case ISD::SETULE:
19378       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19379     case ISD::SETUGT:
19380     case ISD::SETUGE:
19381       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19382     case ISD::SETLT:
19383     case ISD::SETLE:
19384       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19385     case ISD::SETGT:
19386     case ISD::SETGE:
19387       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19388     }
19389   // Check for x CC y ? y : x -- a min/max with reversed arms.
19390   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19391              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19392     switch (CC) {
19393     default: break;
19394     case ISD::SETULT:
19395     case ISD::SETULE:
19396       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19397     case ISD::SETUGT:
19398     case ISD::SETUGE:
19399       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19400     case ISD::SETLT:
19401     case ISD::SETLE:
19402       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19403     case ISD::SETGT:
19404     case ISD::SETGE:
19405       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19406     }
19407   }
19408
19409   return std::make_pair(Opc, NeedSplit);
19410 }
19411
19412 static SDValue
19413 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19414                                       const X86Subtarget *Subtarget) {
19415   SDLoc dl(N);
19416   SDValue Cond = N->getOperand(0);
19417   SDValue LHS = N->getOperand(1);
19418   SDValue RHS = N->getOperand(2);
19419
19420   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19421     SDValue CondSrc = Cond->getOperand(0);
19422     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19423       Cond = CondSrc->getOperand(0);
19424   }
19425
19426   MVT VT = N->getSimpleValueType(0);
19427   MVT EltVT = VT.getVectorElementType();
19428   unsigned NumElems = VT.getVectorNumElements();
19429   // There is no blend with immediate in AVX-512.
19430   if (VT.is512BitVector())
19431     return SDValue();
19432
19433   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19434     return SDValue();
19435   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19436     return SDValue();
19437
19438   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19439     return SDValue();
19440
19441   unsigned MaskValue = 0;
19442   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19443     return SDValue();
19444
19445   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19446   for (unsigned i = 0; i < NumElems; ++i) {
19447     // Be sure we emit undef where we can.
19448     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19449       ShuffleMask[i] = -1;
19450     else
19451       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19452   }
19453
19454   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19455 }
19456
19457 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19458 /// nodes.
19459 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19460                                     TargetLowering::DAGCombinerInfo &DCI,
19461                                     const X86Subtarget *Subtarget) {
19462   SDLoc DL(N);
19463   SDValue Cond = N->getOperand(0);
19464   // Get the LHS/RHS of the select.
19465   SDValue LHS = N->getOperand(1);
19466   SDValue RHS = N->getOperand(2);
19467   EVT VT = LHS.getValueType();
19468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19469
19470   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19471   // instructions match the semantics of the common C idiom x<y?x:y but not
19472   // x<=y?x:y, because of how they handle negative zero (which can be
19473   // ignored in unsafe-math mode).
19474   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19475       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19476       (Subtarget->hasSSE2() ||
19477        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19478     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19479
19480     unsigned Opcode = 0;
19481     // Check for x CC y ? x : y.
19482     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19483         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19484       switch (CC) {
19485       default: break;
19486       case ISD::SETULT:
19487         // Converting this to a min would handle NaNs incorrectly, and swapping
19488         // the operands would cause it to handle comparisons between positive
19489         // and negative zero incorrectly.
19490         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19491           if (!DAG.getTarget().Options.UnsafeFPMath &&
19492               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19493             break;
19494           std::swap(LHS, RHS);
19495         }
19496         Opcode = X86ISD::FMIN;
19497         break;
19498       case ISD::SETOLE:
19499         // Converting this to a min would handle comparisons between positive
19500         // and negative zero incorrectly.
19501         if (!DAG.getTarget().Options.UnsafeFPMath &&
19502             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19503           break;
19504         Opcode = X86ISD::FMIN;
19505         break;
19506       case ISD::SETULE:
19507         // Converting this to a min would handle both negative zeros and NaNs
19508         // incorrectly, but we can swap the operands to fix both.
19509         std::swap(LHS, RHS);
19510       case ISD::SETOLT:
19511       case ISD::SETLT:
19512       case ISD::SETLE:
19513         Opcode = X86ISD::FMIN;
19514         break;
19515
19516       case ISD::SETOGE:
19517         // Converting this to a max would handle comparisons between positive
19518         // and negative zero incorrectly.
19519         if (!DAG.getTarget().Options.UnsafeFPMath &&
19520             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19521           break;
19522         Opcode = X86ISD::FMAX;
19523         break;
19524       case ISD::SETUGT:
19525         // Converting this to a max would handle NaNs incorrectly, and swapping
19526         // the operands would cause it to handle comparisons between positive
19527         // and negative zero incorrectly.
19528         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19529           if (!DAG.getTarget().Options.UnsafeFPMath &&
19530               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19531             break;
19532           std::swap(LHS, RHS);
19533         }
19534         Opcode = X86ISD::FMAX;
19535         break;
19536       case ISD::SETUGE:
19537         // Converting this to a max would handle both negative zeros and NaNs
19538         // incorrectly, but we can swap the operands to fix both.
19539         std::swap(LHS, RHS);
19540       case ISD::SETOGT:
19541       case ISD::SETGT:
19542       case ISD::SETGE:
19543         Opcode = X86ISD::FMAX;
19544         break;
19545       }
19546     // Check for x CC y ? y : x -- a min/max with reversed arms.
19547     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19548                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19549       switch (CC) {
19550       default: break;
19551       case ISD::SETOGE:
19552         // Converting this to a min would handle comparisons between positive
19553         // and negative zero incorrectly, and swapping the operands would
19554         // cause it to handle NaNs incorrectly.
19555         if (!DAG.getTarget().Options.UnsafeFPMath &&
19556             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19557           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19558             break;
19559           std::swap(LHS, RHS);
19560         }
19561         Opcode = X86ISD::FMIN;
19562         break;
19563       case ISD::SETUGT:
19564         // Converting this to a min would handle NaNs incorrectly.
19565         if (!DAG.getTarget().Options.UnsafeFPMath &&
19566             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19567           break;
19568         Opcode = X86ISD::FMIN;
19569         break;
19570       case ISD::SETUGE:
19571         // Converting this to a min would handle both negative zeros and NaNs
19572         // incorrectly, but we can swap the operands to fix both.
19573         std::swap(LHS, RHS);
19574       case ISD::SETOGT:
19575       case ISD::SETGT:
19576       case ISD::SETGE:
19577         Opcode = X86ISD::FMIN;
19578         break;
19579
19580       case ISD::SETULT:
19581         // Converting this to a max would handle NaNs incorrectly.
19582         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19583           break;
19584         Opcode = X86ISD::FMAX;
19585         break;
19586       case ISD::SETOLE:
19587         // Converting this to a max would handle comparisons between positive
19588         // and negative zero incorrectly, and swapping the operands would
19589         // cause it to handle NaNs incorrectly.
19590         if (!DAG.getTarget().Options.UnsafeFPMath &&
19591             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19592           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19593             break;
19594           std::swap(LHS, RHS);
19595         }
19596         Opcode = X86ISD::FMAX;
19597         break;
19598       case ISD::SETULE:
19599         // Converting this to a max would handle both negative zeros and NaNs
19600         // incorrectly, but we can swap the operands to fix both.
19601         std::swap(LHS, RHS);
19602       case ISD::SETOLT:
19603       case ISD::SETLT:
19604       case ISD::SETLE:
19605         Opcode = X86ISD::FMAX;
19606         break;
19607       }
19608     }
19609
19610     if (Opcode)
19611       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19612   }
19613
19614   EVT CondVT = Cond.getValueType();
19615   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19616       CondVT.getVectorElementType() == MVT::i1) {
19617     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19618     // lowering on AVX-512. In this case we convert it to
19619     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19620     // The same situation for all 128 and 256-bit vectors of i8 and i16
19621     EVT OpVT = LHS.getValueType();
19622     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19623         (OpVT.getVectorElementType() == MVT::i8 ||
19624          OpVT.getVectorElementType() == MVT::i16)) {
19625       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19626       DCI.AddToWorklist(Cond.getNode());
19627       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19628     }
19629   }
19630   // If this is a select between two integer constants, try to do some
19631   // optimizations.
19632   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19633     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19634       // Don't do this for crazy integer types.
19635       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19636         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19637         // so that TrueC (the true value) is larger than FalseC.
19638         bool NeedsCondInvert = false;
19639
19640         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19641             // Efficiently invertible.
19642             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19643              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19644               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19645           NeedsCondInvert = true;
19646           std::swap(TrueC, FalseC);
19647         }
19648
19649         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19650         if (FalseC->getAPIntValue() == 0 &&
19651             TrueC->getAPIntValue().isPowerOf2()) {
19652           if (NeedsCondInvert) // Invert the condition if needed.
19653             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19654                                DAG.getConstant(1, Cond.getValueType()));
19655
19656           // Zero extend the condition if needed.
19657           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19658
19659           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19660           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19661                              DAG.getConstant(ShAmt, MVT::i8));
19662         }
19663
19664         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19665         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19666           if (NeedsCondInvert) // Invert the condition if needed.
19667             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19668                                DAG.getConstant(1, Cond.getValueType()));
19669
19670           // Zero extend the condition if needed.
19671           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19672                              FalseC->getValueType(0), Cond);
19673           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19674                              SDValue(FalseC, 0));
19675         }
19676
19677         // Optimize cases that will turn into an LEA instruction.  This requires
19678         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19679         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19680           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19681           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19682
19683           bool isFastMultiplier = false;
19684           if (Diff < 10) {
19685             switch ((unsigned char)Diff) {
19686               default: break;
19687               case 1:  // result = add base, cond
19688               case 2:  // result = lea base(    , cond*2)
19689               case 3:  // result = lea base(cond, cond*2)
19690               case 4:  // result = lea base(    , cond*4)
19691               case 5:  // result = lea base(cond, cond*4)
19692               case 8:  // result = lea base(    , cond*8)
19693               case 9:  // result = lea base(cond, cond*8)
19694                 isFastMultiplier = true;
19695                 break;
19696             }
19697           }
19698
19699           if (isFastMultiplier) {
19700             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19701             if (NeedsCondInvert) // Invert the condition if needed.
19702               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19703                                  DAG.getConstant(1, Cond.getValueType()));
19704
19705             // Zero extend the condition if needed.
19706             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19707                                Cond);
19708             // Scale the condition by the difference.
19709             if (Diff != 1)
19710               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19711                                  DAG.getConstant(Diff, Cond.getValueType()));
19712
19713             // Add the base if non-zero.
19714             if (FalseC->getAPIntValue() != 0)
19715               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19716                                  SDValue(FalseC, 0));
19717             return Cond;
19718           }
19719         }
19720       }
19721   }
19722
19723   // Canonicalize max and min:
19724   // (x > y) ? x : y -> (x >= y) ? x : y
19725   // (x < y) ? x : y -> (x <= y) ? x : y
19726   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19727   // the need for an extra compare
19728   // against zero. e.g.
19729   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19730   // subl   %esi, %edi
19731   // testl  %edi, %edi
19732   // movl   $0, %eax
19733   // cmovgl %edi, %eax
19734   // =>
19735   // xorl   %eax, %eax
19736   // subl   %esi, $edi
19737   // cmovsl %eax, %edi
19738   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19739       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19740       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19741     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19742     switch (CC) {
19743     default: break;
19744     case ISD::SETLT:
19745     case ISD::SETGT: {
19746       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19747       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19748                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19749       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19750     }
19751     }
19752   }
19753
19754   // Early exit check
19755   if (!TLI.isTypeLegal(VT))
19756     return SDValue();
19757
19758   // Match VSELECTs into subs with unsigned saturation.
19759   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19760       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19761       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19762        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19763     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19764
19765     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19766     // left side invert the predicate to simplify logic below.
19767     SDValue Other;
19768     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19769       Other = RHS;
19770       CC = ISD::getSetCCInverse(CC, true);
19771     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19772       Other = LHS;
19773     }
19774
19775     if (Other.getNode() && Other->getNumOperands() == 2 &&
19776         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19777       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19778       SDValue CondRHS = Cond->getOperand(1);
19779
19780       // Look for a general sub with unsigned saturation first.
19781       // x >= y ? x-y : 0 --> subus x, y
19782       // x >  y ? x-y : 0 --> subus x, y
19783       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19784           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19785         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19786
19787       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19788         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19789           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19790             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19791               // If the RHS is a constant we have to reverse the const
19792               // canonicalization.
19793               // x > C-1 ? x+-C : 0 --> subus x, C
19794               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19795                   CondRHSConst->getAPIntValue() ==
19796                       (-OpRHSConst->getAPIntValue() - 1))
19797                 return DAG.getNode(
19798                     X86ISD::SUBUS, DL, VT, OpLHS,
19799                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19800
19801           // Another special case: If C was a sign bit, the sub has been
19802           // canonicalized into a xor.
19803           // FIXME: Would it be better to use computeKnownBits to determine
19804           //        whether it's safe to decanonicalize the xor?
19805           // x s< 0 ? x^C : 0 --> subus x, C
19806           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19807               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19808               OpRHSConst->getAPIntValue().isSignBit())
19809             // Note that we have to rebuild the RHS constant here to ensure we
19810             // don't rely on particular values of undef lanes.
19811             return DAG.getNode(
19812                 X86ISD::SUBUS, DL, VT, OpLHS,
19813                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19814         }
19815     }
19816   }
19817
19818   // Try to match a min/max vector operation.
19819   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19820     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19821     unsigned Opc = ret.first;
19822     bool NeedSplit = ret.second;
19823
19824     if (Opc && NeedSplit) {
19825       unsigned NumElems = VT.getVectorNumElements();
19826       // Extract the LHS vectors
19827       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19828       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19829
19830       // Extract the RHS vectors
19831       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19832       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19833
19834       // Create min/max for each subvector
19835       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19836       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19837
19838       // Merge the result
19839       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19840     } else if (Opc)
19841       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19842   }
19843
19844   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19845   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19846       // Check if SETCC has already been promoted
19847       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19848       // Check that condition value type matches vselect operand type
19849       CondVT == VT) { 
19850
19851     assert(Cond.getValueType().isVector() &&
19852            "vector select expects a vector selector!");
19853
19854     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19855     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19856
19857     if (!TValIsAllOnes && !FValIsAllZeros) {
19858       // Try invert the condition if true value is not all 1s and false value
19859       // is not all 0s.
19860       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19861       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19862
19863       if (TValIsAllZeros || FValIsAllOnes) {
19864         SDValue CC = Cond.getOperand(2);
19865         ISD::CondCode NewCC =
19866           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19867                                Cond.getOperand(0).getValueType().isInteger());
19868         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19869         std::swap(LHS, RHS);
19870         TValIsAllOnes = FValIsAllOnes;
19871         FValIsAllZeros = TValIsAllZeros;
19872       }
19873     }
19874
19875     if (TValIsAllOnes || FValIsAllZeros) {
19876       SDValue Ret;
19877
19878       if (TValIsAllOnes && FValIsAllZeros)
19879         Ret = Cond;
19880       else if (TValIsAllOnes)
19881         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19882                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19883       else if (FValIsAllZeros)
19884         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19885                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19886
19887       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19888     }
19889   }
19890
19891   // Try to fold this VSELECT into a MOVSS/MOVSD
19892   if (N->getOpcode() == ISD::VSELECT &&
19893       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19894     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19895         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19896       bool CanFold = false;
19897       unsigned NumElems = Cond.getNumOperands();
19898       SDValue A = LHS;
19899       SDValue B = RHS;
19900       
19901       if (isZero(Cond.getOperand(0))) {
19902         CanFold = true;
19903
19904         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19905         // fold (vselect <0,-1> -> (movsd A, B)
19906         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19907           CanFold = isAllOnes(Cond.getOperand(i));
19908       } else if (isAllOnes(Cond.getOperand(0))) {
19909         CanFold = true;
19910         std::swap(A, B);
19911
19912         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19913         // fold (vselect <-1,0> -> (movsd B, A)
19914         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19915           CanFold = isZero(Cond.getOperand(i));
19916       }
19917
19918       if (CanFold) {
19919         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19920           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19921         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19922       }
19923
19924       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19925         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19926         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19927         //                             (v2i64 (bitcast B)))))
19928         //
19929         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19930         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19931         //                             (v2f64 (bitcast B)))))
19932         //
19933         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19934         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19935         //                             (v2i64 (bitcast A)))))
19936         //
19937         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19938         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19939         //                             (v2f64 (bitcast A)))))
19940
19941         CanFold = (isZero(Cond.getOperand(0)) &&
19942                    isZero(Cond.getOperand(1)) &&
19943                    isAllOnes(Cond.getOperand(2)) &&
19944                    isAllOnes(Cond.getOperand(3)));
19945
19946         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19947             isAllOnes(Cond.getOperand(1)) &&
19948             isZero(Cond.getOperand(2)) &&
19949             isZero(Cond.getOperand(3))) {
19950           CanFold = true;
19951           std::swap(LHS, RHS);
19952         }
19953
19954         if (CanFold) {
19955           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19956           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19957           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19958           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19959                                                 NewB, DAG);
19960           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19961         }
19962       }
19963     }
19964   }
19965
19966   // If we know that this node is legal then we know that it is going to be
19967   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19968   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19969   // to simplify previous instructions.
19970   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19971       !DCI.isBeforeLegalize() &&
19972       // We explicitly check against v8i16 and v16i16 because, although
19973       // they're marked as Custom, they might only be legal when Cond is a
19974       // build_vector of constants. This will be taken care in a later
19975       // condition.
19976       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19977        VT != MVT::v8i16)) {
19978     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19979
19980     // Don't optimize vector selects that map to mask-registers.
19981     if (BitWidth == 1)
19982       return SDValue();
19983
19984     // Check all uses of that condition operand to check whether it will be
19985     // consumed by non-BLEND instructions, which may depend on all bits are set
19986     // properly.
19987     for (SDNode::use_iterator I = Cond->use_begin(),
19988                               E = Cond->use_end(); I != E; ++I)
19989       if (I->getOpcode() != ISD::VSELECT)
19990         // TODO: Add other opcodes eventually lowered into BLEND.
19991         return SDValue();
19992
19993     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19994     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19995
19996     APInt KnownZero, KnownOne;
19997     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19998                                           DCI.isBeforeLegalizeOps());
19999     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20000         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20001       DCI.CommitTargetLoweringOpt(TLO);
20002   }
20003
20004   // We should generate an X86ISD::BLENDI from a vselect if its argument
20005   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20006   // constants. This specific pattern gets generated when we split a
20007   // selector for a 512 bit vector in a machine without AVX512 (but with
20008   // 256-bit vectors), during legalization:
20009   //
20010   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20011   //
20012   // Iff we find this pattern and the build_vectors are built from
20013   // constants, we translate the vselect into a shuffle_vector that we
20014   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20015   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20016     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20017     if (Shuffle.getNode())
20018       return Shuffle;
20019   }
20020
20021   return SDValue();
20022 }
20023
20024 // Check whether a boolean test is testing a boolean value generated by
20025 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20026 // code.
20027 //
20028 // Simplify the following patterns:
20029 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20030 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20031 // to (Op EFLAGS Cond)
20032 //
20033 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20034 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20035 // to (Op EFLAGS !Cond)
20036 //
20037 // where Op could be BRCOND or CMOV.
20038 //
20039 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20040   // Quit if not CMP and SUB with its value result used.
20041   if (Cmp.getOpcode() != X86ISD::CMP &&
20042       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20043       return SDValue();
20044
20045   // Quit if not used as a boolean value.
20046   if (CC != X86::COND_E && CC != X86::COND_NE)
20047     return SDValue();
20048
20049   // Check CMP operands. One of them should be 0 or 1 and the other should be
20050   // an SetCC or extended from it.
20051   SDValue Op1 = Cmp.getOperand(0);
20052   SDValue Op2 = Cmp.getOperand(1);
20053
20054   SDValue SetCC;
20055   const ConstantSDNode* C = nullptr;
20056   bool needOppositeCond = (CC == X86::COND_E);
20057   bool checkAgainstTrue = false; // Is it a comparison against 1?
20058
20059   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20060     SetCC = Op2;
20061   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20062     SetCC = Op1;
20063   else // Quit if all operands are not constants.
20064     return SDValue();
20065
20066   if (C->getZExtValue() == 1) {
20067     needOppositeCond = !needOppositeCond;
20068     checkAgainstTrue = true;
20069   } else if (C->getZExtValue() != 0)
20070     // Quit if the constant is neither 0 or 1.
20071     return SDValue();
20072
20073   bool truncatedToBoolWithAnd = false;
20074   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20075   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20076          SetCC.getOpcode() == ISD::TRUNCATE ||
20077          SetCC.getOpcode() == ISD::AND) {
20078     if (SetCC.getOpcode() == ISD::AND) {
20079       int OpIdx = -1;
20080       ConstantSDNode *CS;
20081       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20082           CS->getZExtValue() == 1)
20083         OpIdx = 1;
20084       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20085           CS->getZExtValue() == 1)
20086         OpIdx = 0;
20087       if (OpIdx == -1)
20088         break;
20089       SetCC = SetCC.getOperand(OpIdx);
20090       truncatedToBoolWithAnd = true;
20091     } else
20092       SetCC = SetCC.getOperand(0);
20093   }
20094
20095   switch (SetCC.getOpcode()) {
20096   case X86ISD::SETCC_CARRY:
20097     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20098     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20099     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20100     // truncated to i1 using 'and'.
20101     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20102       break;
20103     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20104            "Invalid use of SETCC_CARRY!");
20105     // FALL THROUGH
20106   case X86ISD::SETCC:
20107     // Set the condition code or opposite one if necessary.
20108     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20109     if (needOppositeCond)
20110       CC = X86::GetOppositeBranchCondition(CC);
20111     return SetCC.getOperand(1);
20112   case X86ISD::CMOV: {
20113     // Check whether false/true value has canonical one, i.e. 0 or 1.
20114     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20115     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20116     // Quit if true value is not a constant.
20117     if (!TVal)
20118       return SDValue();
20119     // Quit if false value is not a constant.
20120     if (!FVal) {
20121       SDValue Op = SetCC.getOperand(0);
20122       // Skip 'zext' or 'trunc' node.
20123       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20124           Op.getOpcode() == ISD::TRUNCATE)
20125         Op = Op.getOperand(0);
20126       // A special case for rdrand/rdseed, where 0 is set if false cond is
20127       // found.
20128       if ((Op.getOpcode() != X86ISD::RDRAND &&
20129            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20130         return SDValue();
20131     }
20132     // Quit if false value is not the constant 0 or 1.
20133     bool FValIsFalse = true;
20134     if (FVal && FVal->getZExtValue() != 0) {
20135       if (FVal->getZExtValue() != 1)
20136         return SDValue();
20137       // If FVal is 1, opposite cond is needed.
20138       needOppositeCond = !needOppositeCond;
20139       FValIsFalse = false;
20140     }
20141     // Quit if TVal is not the constant opposite of FVal.
20142     if (FValIsFalse && TVal->getZExtValue() != 1)
20143       return SDValue();
20144     if (!FValIsFalse && TVal->getZExtValue() != 0)
20145       return SDValue();
20146     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20147     if (needOppositeCond)
20148       CC = X86::GetOppositeBranchCondition(CC);
20149     return SetCC.getOperand(3);
20150   }
20151   }
20152
20153   return SDValue();
20154 }
20155
20156 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20157 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20158                                   TargetLowering::DAGCombinerInfo &DCI,
20159                                   const X86Subtarget *Subtarget) {
20160   SDLoc DL(N);
20161
20162   // If the flag operand isn't dead, don't touch this CMOV.
20163   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20164     return SDValue();
20165
20166   SDValue FalseOp = N->getOperand(0);
20167   SDValue TrueOp = N->getOperand(1);
20168   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20169   SDValue Cond = N->getOperand(3);
20170
20171   if (CC == X86::COND_E || CC == X86::COND_NE) {
20172     switch (Cond.getOpcode()) {
20173     default: break;
20174     case X86ISD::BSR:
20175     case X86ISD::BSF:
20176       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20177       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20178         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20179     }
20180   }
20181
20182   SDValue Flags;
20183
20184   Flags = checkBoolTestSetCCCombine(Cond, CC);
20185   if (Flags.getNode() &&
20186       // Extra check as FCMOV only supports a subset of X86 cond.
20187       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20188     SDValue Ops[] = { FalseOp, TrueOp,
20189                       DAG.getConstant(CC, MVT::i8), Flags };
20190     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20191   }
20192
20193   // If this is a select between two integer constants, try to do some
20194   // optimizations.  Note that the operands are ordered the opposite of SELECT
20195   // operands.
20196   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20197     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20198       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20199       // larger than FalseC (the false value).
20200       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20201         CC = X86::GetOppositeBranchCondition(CC);
20202         std::swap(TrueC, FalseC);
20203         std::swap(TrueOp, FalseOp);
20204       }
20205
20206       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20207       // This is efficient for any integer data type (including i8/i16) and
20208       // shift amount.
20209       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20210         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20211                            DAG.getConstant(CC, MVT::i8), Cond);
20212
20213         // Zero extend the condition if needed.
20214         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20215
20216         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20217         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20218                            DAG.getConstant(ShAmt, MVT::i8));
20219         if (N->getNumValues() == 2)  // Dead flag value?
20220           return DCI.CombineTo(N, Cond, SDValue());
20221         return Cond;
20222       }
20223
20224       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20225       // for any integer data type, including i8/i16.
20226       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20227         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20228                            DAG.getConstant(CC, MVT::i8), Cond);
20229
20230         // Zero extend the condition if needed.
20231         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20232                            FalseC->getValueType(0), Cond);
20233         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20234                            SDValue(FalseC, 0));
20235
20236         if (N->getNumValues() == 2)  // Dead flag value?
20237           return DCI.CombineTo(N, Cond, SDValue());
20238         return Cond;
20239       }
20240
20241       // Optimize cases that will turn into an LEA instruction.  This requires
20242       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20243       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20244         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20245         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20246
20247         bool isFastMultiplier = false;
20248         if (Diff < 10) {
20249           switch ((unsigned char)Diff) {
20250           default: break;
20251           case 1:  // result = add base, cond
20252           case 2:  // result = lea base(    , cond*2)
20253           case 3:  // result = lea base(cond, cond*2)
20254           case 4:  // result = lea base(    , cond*4)
20255           case 5:  // result = lea base(cond, cond*4)
20256           case 8:  // result = lea base(    , cond*8)
20257           case 9:  // result = lea base(cond, cond*8)
20258             isFastMultiplier = true;
20259             break;
20260           }
20261         }
20262
20263         if (isFastMultiplier) {
20264           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20265           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20266                              DAG.getConstant(CC, MVT::i8), Cond);
20267           // Zero extend the condition if needed.
20268           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20269                              Cond);
20270           // Scale the condition by the difference.
20271           if (Diff != 1)
20272             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20273                                DAG.getConstant(Diff, Cond.getValueType()));
20274
20275           // Add the base if non-zero.
20276           if (FalseC->getAPIntValue() != 0)
20277             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20278                                SDValue(FalseC, 0));
20279           if (N->getNumValues() == 2)  // Dead flag value?
20280             return DCI.CombineTo(N, Cond, SDValue());
20281           return Cond;
20282         }
20283       }
20284     }
20285   }
20286
20287   // Handle these cases:
20288   //   (select (x != c), e, c) -> select (x != c), e, x),
20289   //   (select (x == c), c, e) -> select (x == c), x, e)
20290   // where the c is an integer constant, and the "select" is the combination
20291   // of CMOV and CMP.
20292   //
20293   // The rationale for this change is that the conditional-move from a constant
20294   // needs two instructions, however, conditional-move from a register needs
20295   // only one instruction.
20296   //
20297   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20298   //  some instruction-combining opportunities. This opt needs to be
20299   //  postponed as late as possible.
20300   //
20301   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20302     // the DCI.xxxx conditions are provided to postpone the optimization as
20303     // late as possible.
20304
20305     ConstantSDNode *CmpAgainst = nullptr;
20306     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20307         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20308         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20309
20310       if (CC == X86::COND_NE &&
20311           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20312         CC = X86::GetOppositeBranchCondition(CC);
20313         std::swap(TrueOp, FalseOp);
20314       }
20315
20316       if (CC == X86::COND_E &&
20317           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20318         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20319                           DAG.getConstant(CC, MVT::i8), Cond };
20320         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20321       }
20322     }
20323   }
20324
20325   return SDValue();
20326 }
20327
20328 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20329                                                 const X86Subtarget *Subtarget) {
20330   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20331   switch (IntNo) {
20332   default: return SDValue();
20333   // SSE/AVX/AVX2 blend intrinsics.
20334   case Intrinsic::x86_avx2_pblendvb:
20335   case Intrinsic::x86_avx2_pblendw:
20336   case Intrinsic::x86_avx2_pblendd_128:
20337   case Intrinsic::x86_avx2_pblendd_256:
20338     // Don't try to simplify this intrinsic if we don't have AVX2.
20339     if (!Subtarget->hasAVX2())
20340       return SDValue();
20341     // FALL-THROUGH
20342   case Intrinsic::x86_avx_blend_pd_256:
20343   case Intrinsic::x86_avx_blend_ps_256:
20344   case Intrinsic::x86_avx_blendv_pd_256:
20345   case Intrinsic::x86_avx_blendv_ps_256:
20346     // Don't try to simplify this intrinsic if we don't have AVX.
20347     if (!Subtarget->hasAVX())
20348       return SDValue();
20349     // FALL-THROUGH
20350   case Intrinsic::x86_sse41_pblendw:
20351   case Intrinsic::x86_sse41_blendpd:
20352   case Intrinsic::x86_sse41_blendps:
20353   case Intrinsic::x86_sse41_blendvps:
20354   case Intrinsic::x86_sse41_blendvpd:
20355   case Intrinsic::x86_sse41_pblendvb: {
20356     SDValue Op0 = N->getOperand(1);
20357     SDValue Op1 = N->getOperand(2);
20358     SDValue Mask = N->getOperand(3);
20359
20360     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20361     if (!Subtarget->hasSSE41())
20362       return SDValue();
20363
20364     // fold (blend A, A, Mask) -> A
20365     if (Op0 == Op1)
20366       return Op0;
20367     // fold (blend A, B, allZeros) -> A
20368     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20369       return Op0;
20370     // fold (blend A, B, allOnes) -> B
20371     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20372       return Op1;
20373     
20374     // Simplify the case where the mask is a constant i32 value.
20375     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20376       if (C->isNullValue())
20377         return Op0;
20378       if (C->isAllOnesValue())
20379         return Op1;
20380     }
20381
20382     return SDValue();
20383   }
20384
20385   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20386   case Intrinsic::x86_sse2_psrai_w:
20387   case Intrinsic::x86_sse2_psrai_d:
20388   case Intrinsic::x86_avx2_psrai_w:
20389   case Intrinsic::x86_avx2_psrai_d:
20390   case Intrinsic::x86_sse2_psra_w:
20391   case Intrinsic::x86_sse2_psra_d:
20392   case Intrinsic::x86_avx2_psra_w:
20393   case Intrinsic::x86_avx2_psra_d: {
20394     SDValue Op0 = N->getOperand(1);
20395     SDValue Op1 = N->getOperand(2);
20396     EVT VT = Op0.getValueType();
20397     assert(VT.isVector() && "Expected a vector type!");
20398
20399     if (isa<BuildVectorSDNode>(Op1))
20400       Op1 = Op1.getOperand(0);
20401
20402     if (!isa<ConstantSDNode>(Op1))
20403       return SDValue();
20404
20405     EVT SVT = VT.getVectorElementType();
20406     unsigned SVTBits = SVT.getSizeInBits();
20407
20408     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20409     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20410     uint64_t ShAmt = C.getZExtValue();
20411
20412     // Don't try to convert this shift into a ISD::SRA if the shift
20413     // count is bigger than or equal to the element size.
20414     if (ShAmt >= SVTBits)
20415       return SDValue();
20416
20417     // Trivial case: if the shift count is zero, then fold this
20418     // into the first operand.
20419     if (ShAmt == 0)
20420       return Op0;
20421
20422     // Replace this packed shift intrinsic with a target independent
20423     // shift dag node.
20424     SDValue Splat = DAG.getConstant(C, VT);
20425     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20426   }
20427   }
20428 }
20429
20430 /// PerformMulCombine - Optimize a single multiply with constant into two
20431 /// in order to implement it with two cheaper instructions, e.g.
20432 /// LEA + SHL, LEA + LEA.
20433 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20434                                  TargetLowering::DAGCombinerInfo &DCI) {
20435   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20436     return SDValue();
20437
20438   EVT VT = N->getValueType(0);
20439   if (VT != MVT::i64)
20440     return SDValue();
20441
20442   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20443   if (!C)
20444     return SDValue();
20445   uint64_t MulAmt = C->getZExtValue();
20446   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20447     return SDValue();
20448
20449   uint64_t MulAmt1 = 0;
20450   uint64_t MulAmt2 = 0;
20451   if ((MulAmt % 9) == 0) {
20452     MulAmt1 = 9;
20453     MulAmt2 = MulAmt / 9;
20454   } else if ((MulAmt % 5) == 0) {
20455     MulAmt1 = 5;
20456     MulAmt2 = MulAmt / 5;
20457   } else if ((MulAmt % 3) == 0) {
20458     MulAmt1 = 3;
20459     MulAmt2 = MulAmt / 3;
20460   }
20461   if (MulAmt2 &&
20462       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20463     SDLoc DL(N);
20464
20465     if (isPowerOf2_64(MulAmt2) &&
20466         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20467       // If second multiplifer is pow2, issue it first. We want the multiply by
20468       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20469       // is an add.
20470       std::swap(MulAmt1, MulAmt2);
20471
20472     SDValue NewMul;
20473     if (isPowerOf2_64(MulAmt1))
20474       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20475                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20476     else
20477       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20478                            DAG.getConstant(MulAmt1, VT));
20479
20480     if (isPowerOf2_64(MulAmt2))
20481       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20482                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20483     else
20484       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20485                            DAG.getConstant(MulAmt2, VT));
20486
20487     // Do not add new nodes to DAG combiner worklist.
20488     DCI.CombineTo(N, NewMul, false);
20489   }
20490   return SDValue();
20491 }
20492
20493 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20494   SDValue N0 = N->getOperand(0);
20495   SDValue N1 = N->getOperand(1);
20496   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20497   EVT VT = N0.getValueType();
20498
20499   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20500   // since the result of setcc_c is all zero's or all ones.
20501   if (VT.isInteger() && !VT.isVector() &&
20502       N1C && N0.getOpcode() == ISD::AND &&
20503       N0.getOperand(1).getOpcode() == ISD::Constant) {
20504     SDValue N00 = N0.getOperand(0);
20505     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20506         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20507           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20508          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20509       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20510       APInt ShAmt = N1C->getAPIntValue();
20511       Mask = Mask.shl(ShAmt);
20512       if (Mask != 0)
20513         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20514                            N00, DAG.getConstant(Mask, VT));
20515     }
20516   }
20517
20518   // Hardware support for vector shifts is sparse which makes us scalarize the
20519   // vector operations in many cases. Also, on sandybridge ADD is faster than
20520   // shl.
20521   // (shl V, 1) -> add V,V
20522   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20523     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20524       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20525       // We shift all of the values by one. In many cases we do not have
20526       // hardware support for this operation. This is better expressed as an ADD
20527       // of two values.
20528       if (N1SplatC->getZExtValue() == 1)
20529         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20530     }
20531
20532   return SDValue();
20533 }
20534
20535 /// \brief Returns a vector of 0s if the node in input is a vector logical
20536 /// shift by a constant amount which is known to be bigger than or equal
20537 /// to the vector element size in bits.
20538 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20539                                       const X86Subtarget *Subtarget) {
20540   EVT VT = N->getValueType(0);
20541
20542   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20543       (!Subtarget->hasInt256() ||
20544        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20545     return SDValue();
20546
20547   SDValue Amt = N->getOperand(1);
20548   SDLoc DL(N);
20549   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20550     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20551       APInt ShiftAmt = AmtSplat->getAPIntValue();
20552       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20553
20554       // SSE2/AVX2 logical shifts always return a vector of 0s
20555       // if the shift amount is bigger than or equal to
20556       // the element size. The constant shift amount will be
20557       // encoded as a 8-bit immediate.
20558       if (ShiftAmt.trunc(8).uge(MaxAmount))
20559         return getZeroVector(VT, Subtarget, DAG, DL);
20560     }
20561
20562   return SDValue();
20563 }
20564
20565 /// PerformShiftCombine - Combine shifts.
20566 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20567                                    TargetLowering::DAGCombinerInfo &DCI,
20568                                    const X86Subtarget *Subtarget) {
20569   if (N->getOpcode() == ISD::SHL) {
20570     SDValue V = PerformSHLCombine(N, DAG);
20571     if (V.getNode()) return V;
20572   }
20573
20574   if (N->getOpcode() != ISD::SRA) {
20575     // Try to fold this logical shift into a zero vector.
20576     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20577     if (V.getNode()) return V;
20578   }
20579
20580   return SDValue();
20581 }
20582
20583 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20584 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20585 // and friends.  Likewise for OR -> CMPNEQSS.
20586 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20587                             TargetLowering::DAGCombinerInfo &DCI,
20588                             const X86Subtarget *Subtarget) {
20589   unsigned opcode;
20590
20591   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20592   // we're requiring SSE2 for both.
20593   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20594     SDValue N0 = N->getOperand(0);
20595     SDValue N1 = N->getOperand(1);
20596     SDValue CMP0 = N0->getOperand(1);
20597     SDValue CMP1 = N1->getOperand(1);
20598     SDLoc DL(N);
20599
20600     // The SETCCs should both refer to the same CMP.
20601     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20602       return SDValue();
20603
20604     SDValue CMP00 = CMP0->getOperand(0);
20605     SDValue CMP01 = CMP0->getOperand(1);
20606     EVT     VT    = CMP00.getValueType();
20607
20608     if (VT == MVT::f32 || VT == MVT::f64) {
20609       bool ExpectingFlags = false;
20610       // Check for any users that want flags:
20611       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20612            !ExpectingFlags && UI != UE; ++UI)
20613         switch (UI->getOpcode()) {
20614         default:
20615         case ISD::BR_CC:
20616         case ISD::BRCOND:
20617         case ISD::SELECT:
20618           ExpectingFlags = true;
20619           break;
20620         case ISD::CopyToReg:
20621         case ISD::SIGN_EXTEND:
20622         case ISD::ZERO_EXTEND:
20623         case ISD::ANY_EXTEND:
20624           break;
20625         }
20626
20627       if (!ExpectingFlags) {
20628         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20629         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20630
20631         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20632           X86::CondCode tmp = cc0;
20633           cc0 = cc1;
20634           cc1 = tmp;
20635         }
20636
20637         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20638             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20639           // FIXME: need symbolic constants for these magic numbers.
20640           // See X86ATTInstPrinter.cpp:printSSECC().
20641           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20642           if (Subtarget->hasAVX512()) {
20643             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20644                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20645             if (N->getValueType(0) != MVT::i1)
20646               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20647                                  FSetCC);
20648             return FSetCC;
20649           }
20650           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20651                                               CMP00.getValueType(), CMP00, CMP01,
20652                                               DAG.getConstant(x86cc, MVT::i8));
20653
20654           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20655           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20656
20657           if (is64BitFP && !Subtarget->is64Bit()) {
20658             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20659             // 64-bit integer, since that's not a legal type. Since
20660             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20661             // bits, but can do this little dance to extract the lowest 32 bits
20662             // and work with those going forward.
20663             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20664                                            OnesOrZeroesF);
20665             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20666                                            Vector64);
20667             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20668                                         Vector32, DAG.getIntPtrConstant(0));
20669             IntVT = MVT::i32;
20670           }
20671
20672           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20673           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20674                                       DAG.getConstant(1, IntVT));
20675           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20676           return OneBitOfTruth;
20677         }
20678       }
20679     }
20680   }
20681   return SDValue();
20682 }
20683
20684 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20685 /// so it can be folded inside ANDNP.
20686 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20687   EVT VT = N->getValueType(0);
20688
20689   // Match direct AllOnes for 128 and 256-bit vectors
20690   if (ISD::isBuildVectorAllOnes(N))
20691     return true;
20692
20693   // Look through a bit convert.
20694   if (N->getOpcode() == ISD::BITCAST)
20695     N = N->getOperand(0).getNode();
20696
20697   // Sometimes the operand may come from a insert_subvector building a 256-bit
20698   // allones vector
20699   if (VT.is256BitVector() &&
20700       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20701     SDValue V1 = N->getOperand(0);
20702     SDValue V2 = N->getOperand(1);
20703
20704     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20705         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20706         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20707         ISD::isBuildVectorAllOnes(V2.getNode()))
20708       return true;
20709   }
20710
20711   return false;
20712 }
20713
20714 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20715 // register. In most cases we actually compare or select YMM-sized registers
20716 // and mixing the two types creates horrible code. This method optimizes
20717 // some of the transition sequences.
20718 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20719                                  TargetLowering::DAGCombinerInfo &DCI,
20720                                  const X86Subtarget *Subtarget) {
20721   EVT VT = N->getValueType(0);
20722   if (!VT.is256BitVector())
20723     return SDValue();
20724
20725   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20726           N->getOpcode() == ISD::ZERO_EXTEND ||
20727           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20728
20729   SDValue Narrow = N->getOperand(0);
20730   EVT NarrowVT = Narrow->getValueType(0);
20731   if (!NarrowVT.is128BitVector())
20732     return SDValue();
20733
20734   if (Narrow->getOpcode() != ISD::XOR &&
20735       Narrow->getOpcode() != ISD::AND &&
20736       Narrow->getOpcode() != ISD::OR)
20737     return SDValue();
20738
20739   SDValue N0  = Narrow->getOperand(0);
20740   SDValue N1  = Narrow->getOperand(1);
20741   SDLoc DL(Narrow);
20742
20743   // The Left side has to be a trunc.
20744   if (N0.getOpcode() != ISD::TRUNCATE)
20745     return SDValue();
20746
20747   // The type of the truncated inputs.
20748   EVT WideVT = N0->getOperand(0)->getValueType(0);
20749   if (WideVT != VT)
20750     return SDValue();
20751
20752   // The right side has to be a 'trunc' or a constant vector.
20753   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20754   ConstantSDNode *RHSConstSplat = nullptr;
20755   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20756     RHSConstSplat = RHSBV->getConstantSplatNode();
20757   if (!RHSTrunc && !RHSConstSplat)
20758     return SDValue();
20759
20760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20761
20762   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20763     return SDValue();
20764
20765   // Set N0 and N1 to hold the inputs to the new wide operation.
20766   N0 = N0->getOperand(0);
20767   if (RHSConstSplat) {
20768     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20769                      SDValue(RHSConstSplat, 0));
20770     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20771     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20772   } else if (RHSTrunc) {
20773     N1 = N1->getOperand(0);
20774   }
20775
20776   // Generate the wide operation.
20777   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20778   unsigned Opcode = N->getOpcode();
20779   switch (Opcode) {
20780   case ISD::ANY_EXTEND:
20781     return Op;
20782   case ISD::ZERO_EXTEND: {
20783     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20784     APInt Mask = APInt::getAllOnesValue(InBits);
20785     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20786     return DAG.getNode(ISD::AND, DL, VT,
20787                        Op, DAG.getConstant(Mask, VT));
20788   }
20789   case ISD::SIGN_EXTEND:
20790     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20791                        Op, DAG.getValueType(NarrowVT));
20792   default:
20793     llvm_unreachable("Unexpected opcode");
20794   }
20795 }
20796
20797 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20798                                  TargetLowering::DAGCombinerInfo &DCI,
20799                                  const X86Subtarget *Subtarget) {
20800   EVT VT = N->getValueType(0);
20801   if (DCI.isBeforeLegalizeOps())
20802     return SDValue();
20803
20804   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20805   if (R.getNode())
20806     return R;
20807
20808   // Create BEXTR instructions
20809   // BEXTR is ((X >> imm) & (2**size-1))
20810   if (VT == MVT::i32 || VT == MVT::i64) {
20811     SDValue N0 = N->getOperand(0);
20812     SDValue N1 = N->getOperand(1);
20813     SDLoc DL(N);
20814
20815     // Check for BEXTR.
20816     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20817         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20818       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20819       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20820       if (MaskNode && ShiftNode) {
20821         uint64_t Mask = MaskNode->getZExtValue();
20822         uint64_t Shift = ShiftNode->getZExtValue();
20823         if (isMask_64(Mask)) {
20824           uint64_t MaskSize = CountPopulation_64(Mask);
20825           if (Shift + MaskSize <= VT.getSizeInBits())
20826             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20827                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20828         }
20829       }
20830     } // BEXTR
20831
20832     return SDValue();
20833   }
20834
20835   // Want to form ANDNP nodes:
20836   // 1) In the hopes of then easily combining them with OR and AND nodes
20837   //    to form PBLEND/PSIGN.
20838   // 2) To match ANDN packed intrinsics
20839   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20840     return SDValue();
20841
20842   SDValue N0 = N->getOperand(0);
20843   SDValue N1 = N->getOperand(1);
20844   SDLoc DL(N);
20845
20846   // Check LHS for vnot
20847   if (N0.getOpcode() == ISD::XOR &&
20848       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20849       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20850     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20851
20852   // Check RHS for vnot
20853   if (N1.getOpcode() == ISD::XOR &&
20854       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20855       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20856     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20857
20858   return SDValue();
20859 }
20860
20861 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20862                                 TargetLowering::DAGCombinerInfo &DCI,
20863                                 const X86Subtarget *Subtarget) {
20864   if (DCI.isBeforeLegalizeOps())
20865     return SDValue();
20866
20867   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20868   if (R.getNode())
20869     return R;
20870
20871   SDValue N0 = N->getOperand(0);
20872   SDValue N1 = N->getOperand(1);
20873   EVT VT = N->getValueType(0);
20874
20875   // look for psign/blend
20876   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20877     if (!Subtarget->hasSSSE3() ||
20878         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20879       return SDValue();
20880
20881     // Canonicalize pandn to RHS
20882     if (N0.getOpcode() == X86ISD::ANDNP)
20883       std::swap(N0, N1);
20884     // or (and (m, y), (pandn m, x))
20885     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20886       SDValue Mask = N1.getOperand(0);
20887       SDValue X    = N1.getOperand(1);
20888       SDValue Y;
20889       if (N0.getOperand(0) == Mask)
20890         Y = N0.getOperand(1);
20891       if (N0.getOperand(1) == Mask)
20892         Y = N0.getOperand(0);
20893
20894       // Check to see if the mask appeared in both the AND and ANDNP and
20895       if (!Y.getNode())
20896         return SDValue();
20897
20898       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20899       // Look through mask bitcast.
20900       if (Mask.getOpcode() == ISD::BITCAST)
20901         Mask = Mask.getOperand(0);
20902       if (X.getOpcode() == ISD::BITCAST)
20903         X = X.getOperand(0);
20904       if (Y.getOpcode() == ISD::BITCAST)
20905         Y = Y.getOperand(0);
20906
20907       EVT MaskVT = Mask.getValueType();
20908
20909       // Validate that the Mask operand is a vector sra node.
20910       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20911       // there is no psrai.b
20912       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20913       unsigned SraAmt = ~0;
20914       if (Mask.getOpcode() == ISD::SRA) {
20915         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20916           if (auto *AmtConst = AmtBV->getConstantSplatNode())
20917             SraAmt = AmtConst->getZExtValue();
20918       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20919         SDValue SraC = Mask.getOperand(1);
20920         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20921       }
20922       if ((SraAmt + 1) != EltBits)
20923         return SDValue();
20924
20925       SDLoc DL(N);
20926
20927       // Now we know we at least have a plendvb with the mask val.  See if
20928       // we can form a psignb/w/d.
20929       // psign = x.type == y.type == mask.type && y = sub(0, x);
20930       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20931           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20932           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20933         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20934                "Unsupported VT for PSIGN");
20935         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20936         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20937       }
20938       // PBLENDVB only available on SSE 4.1
20939       if (!Subtarget->hasSSE41())
20940         return SDValue();
20941
20942       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20943
20944       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20945       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20946       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20947       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20948       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20949     }
20950   }
20951
20952   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20953     return SDValue();
20954
20955   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20956   MachineFunction &MF = DAG.getMachineFunction();
20957   bool OptForSize = MF.getFunction()->getAttributes().
20958     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20959
20960   // SHLD/SHRD instructions have lower register pressure, but on some
20961   // platforms they have higher latency than the equivalent
20962   // series of shifts/or that would otherwise be generated.
20963   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20964   // have higher latencies and we are not optimizing for size.
20965   if (!OptForSize && Subtarget->isSHLDSlow())
20966     return SDValue();
20967
20968   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20969     std::swap(N0, N1);
20970   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20971     return SDValue();
20972   if (!N0.hasOneUse() || !N1.hasOneUse())
20973     return SDValue();
20974
20975   SDValue ShAmt0 = N0.getOperand(1);
20976   if (ShAmt0.getValueType() != MVT::i8)
20977     return SDValue();
20978   SDValue ShAmt1 = N1.getOperand(1);
20979   if (ShAmt1.getValueType() != MVT::i8)
20980     return SDValue();
20981   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20982     ShAmt0 = ShAmt0.getOperand(0);
20983   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20984     ShAmt1 = ShAmt1.getOperand(0);
20985
20986   SDLoc DL(N);
20987   unsigned Opc = X86ISD::SHLD;
20988   SDValue Op0 = N0.getOperand(0);
20989   SDValue Op1 = N1.getOperand(0);
20990   if (ShAmt0.getOpcode() == ISD::SUB) {
20991     Opc = X86ISD::SHRD;
20992     std::swap(Op0, Op1);
20993     std::swap(ShAmt0, ShAmt1);
20994   }
20995
20996   unsigned Bits = VT.getSizeInBits();
20997   if (ShAmt1.getOpcode() == ISD::SUB) {
20998     SDValue Sum = ShAmt1.getOperand(0);
20999     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21000       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21001       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21002         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21003       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21004         return DAG.getNode(Opc, DL, VT,
21005                            Op0, Op1,
21006                            DAG.getNode(ISD::TRUNCATE, DL,
21007                                        MVT::i8, ShAmt0));
21008     }
21009   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21010     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21011     if (ShAmt0C &&
21012         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21013       return DAG.getNode(Opc, DL, VT,
21014                          N0.getOperand(0), N1.getOperand(0),
21015                          DAG.getNode(ISD::TRUNCATE, DL,
21016                                        MVT::i8, ShAmt0));
21017   }
21018
21019   return SDValue();
21020 }
21021
21022 // Generate NEG and CMOV for integer abs.
21023 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21024   EVT VT = N->getValueType(0);
21025
21026   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21027   // 8-bit integer abs to NEG and CMOV.
21028   if (VT.isInteger() && VT.getSizeInBits() == 8)
21029     return SDValue();
21030
21031   SDValue N0 = N->getOperand(0);
21032   SDValue N1 = N->getOperand(1);
21033   SDLoc DL(N);
21034
21035   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21036   // and change it to SUB and CMOV.
21037   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21038       N0.getOpcode() == ISD::ADD &&
21039       N0.getOperand(1) == N1 &&
21040       N1.getOpcode() == ISD::SRA &&
21041       N1.getOperand(0) == N0.getOperand(0))
21042     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21043       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21044         // Generate SUB & CMOV.
21045         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21046                                   DAG.getConstant(0, VT), N0.getOperand(0));
21047
21048         SDValue Ops[] = { N0.getOperand(0), Neg,
21049                           DAG.getConstant(X86::COND_GE, MVT::i8),
21050                           SDValue(Neg.getNode(), 1) };
21051         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21052       }
21053   return SDValue();
21054 }
21055
21056 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21057 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21058                                  TargetLowering::DAGCombinerInfo &DCI,
21059                                  const X86Subtarget *Subtarget) {
21060   if (DCI.isBeforeLegalizeOps())
21061     return SDValue();
21062
21063   if (Subtarget->hasCMov()) {
21064     SDValue RV = performIntegerAbsCombine(N, DAG);
21065     if (RV.getNode())
21066       return RV;
21067   }
21068
21069   return SDValue();
21070 }
21071
21072 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21073 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21074                                   TargetLowering::DAGCombinerInfo &DCI,
21075                                   const X86Subtarget *Subtarget) {
21076   LoadSDNode *Ld = cast<LoadSDNode>(N);
21077   EVT RegVT = Ld->getValueType(0);
21078   EVT MemVT = Ld->getMemoryVT();
21079   SDLoc dl(Ld);
21080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21081
21082   // On Sandybridge unaligned 256bit loads are inefficient.
21083   ISD::LoadExtType Ext = Ld->getExtensionType();
21084   unsigned Alignment = Ld->getAlignment();
21085   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21086   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21087       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21088     unsigned NumElems = RegVT.getVectorNumElements();
21089     if (NumElems < 2)
21090       return SDValue();
21091
21092     SDValue Ptr = Ld->getBasePtr();
21093     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21094
21095     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21096                                   NumElems/2);
21097     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21098                                 Ld->getPointerInfo(), Ld->isVolatile(),
21099                                 Ld->isNonTemporal(), Ld->isInvariant(),
21100                                 Alignment);
21101     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21102     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21103                                 Ld->getPointerInfo(), Ld->isVolatile(),
21104                                 Ld->isNonTemporal(), Ld->isInvariant(),
21105                                 std::min(16U, Alignment));
21106     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21107                              Load1.getValue(1),
21108                              Load2.getValue(1));
21109
21110     SDValue NewVec = DAG.getUNDEF(RegVT);
21111     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21112     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21113     return DCI.CombineTo(N, NewVec, TF, true);
21114   }
21115
21116   return SDValue();
21117 }
21118
21119 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21120 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21121                                    const X86Subtarget *Subtarget) {
21122   StoreSDNode *St = cast<StoreSDNode>(N);
21123   EVT VT = St->getValue().getValueType();
21124   EVT StVT = St->getMemoryVT();
21125   SDLoc dl(St);
21126   SDValue StoredVal = St->getOperand(1);
21127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21128
21129   // If we are saving a concatenation of two XMM registers, perform two stores.
21130   // On Sandy Bridge, 256-bit memory operations are executed by two
21131   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21132   // memory  operation.
21133   unsigned Alignment = St->getAlignment();
21134   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21135   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21136       StVT == VT && !IsAligned) {
21137     unsigned NumElems = VT.getVectorNumElements();
21138     if (NumElems < 2)
21139       return SDValue();
21140
21141     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21142     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21143
21144     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21145     SDValue Ptr0 = St->getBasePtr();
21146     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21147
21148     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21149                                 St->getPointerInfo(), St->isVolatile(),
21150                                 St->isNonTemporal(), Alignment);
21151     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21152                                 St->getPointerInfo(), St->isVolatile(),
21153                                 St->isNonTemporal(),
21154                                 std::min(16U, Alignment));
21155     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21156   }
21157
21158   // Optimize trunc store (of multiple scalars) to shuffle and store.
21159   // First, pack all of the elements in one place. Next, store to memory
21160   // in fewer chunks.
21161   if (St->isTruncatingStore() && VT.isVector()) {
21162     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21163     unsigned NumElems = VT.getVectorNumElements();
21164     assert(StVT != VT && "Cannot truncate to the same type");
21165     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21166     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21167
21168     // From, To sizes and ElemCount must be pow of two
21169     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21170     // We are going to use the original vector elt for storing.
21171     // Accumulated smaller vector elements must be a multiple of the store size.
21172     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21173
21174     unsigned SizeRatio  = FromSz / ToSz;
21175
21176     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21177
21178     // Create a type on which we perform the shuffle
21179     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21180             StVT.getScalarType(), NumElems*SizeRatio);
21181
21182     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21183
21184     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21185     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21186     for (unsigned i = 0; i != NumElems; ++i)
21187       ShuffleVec[i] = i * SizeRatio;
21188
21189     // Can't shuffle using an illegal type.
21190     if (!TLI.isTypeLegal(WideVecVT))
21191       return SDValue();
21192
21193     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21194                                          DAG.getUNDEF(WideVecVT),
21195                                          &ShuffleVec[0]);
21196     // At this point all of the data is stored at the bottom of the
21197     // register. We now need to save it to mem.
21198
21199     // Find the largest store unit
21200     MVT StoreType = MVT::i8;
21201     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21202          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21203       MVT Tp = (MVT::SimpleValueType)tp;
21204       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21205         StoreType = Tp;
21206     }
21207
21208     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21209     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21210         (64 <= NumElems * ToSz))
21211       StoreType = MVT::f64;
21212
21213     // Bitcast the original vector into a vector of store-size units
21214     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21215             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21216     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21217     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21218     SmallVector<SDValue, 8> Chains;
21219     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21220                                         TLI.getPointerTy());
21221     SDValue Ptr = St->getBasePtr();
21222
21223     // Perform one or more big stores into memory.
21224     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21225       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21226                                    StoreType, ShuffWide,
21227                                    DAG.getIntPtrConstant(i));
21228       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21229                                 St->getPointerInfo(), St->isVolatile(),
21230                                 St->isNonTemporal(), St->getAlignment());
21231       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21232       Chains.push_back(Ch);
21233     }
21234
21235     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21236   }
21237
21238   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21239   // the FP state in cases where an emms may be missing.
21240   // A preferable solution to the general problem is to figure out the right
21241   // places to insert EMMS.  This qualifies as a quick hack.
21242
21243   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21244   if (VT.getSizeInBits() != 64)
21245     return SDValue();
21246
21247   const Function *F = DAG.getMachineFunction().getFunction();
21248   bool NoImplicitFloatOps = F->getAttributes().
21249     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21250   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21251                      && Subtarget->hasSSE2();
21252   if ((VT.isVector() ||
21253        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21254       isa<LoadSDNode>(St->getValue()) &&
21255       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21256       St->getChain().hasOneUse() && !St->isVolatile()) {
21257     SDNode* LdVal = St->getValue().getNode();
21258     LoadSDNode *Ld = nullptr;
21259     int TokenFactorIndex = -1;
21260     SmallVector<SDValue, 8> Ops;
21261     SDNode* ChainVal = St->getChain().getNode();
21262     // Must be a store of a load.  We currently handle two cases:  the load
21263     // is a direct child, and it's under an intervening TokenFactor.  It is
21264     // possible to dig deeper under nested TokenFactors.
21265     if (ChainVal == LdVal)
21266       Ld = cast<LoadSDNode>(St->getChain());
21267     else if (St->getValue().hasOneUse() &&
21268              ChainVal->getOpcode() == ISD::TokenFactor) {
21269       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21270         if (ChainVal->getOperand(i).getNode() == LdVal) {
21271           TokenFactorIndex = i;
21272           Ld = cast<LoadSDNode>(St->getValue());
21273         } else
21274           Ops.push_back(ChainVal->getOperand(i));
21275       }
21276     }
21277
21278     if (!Ld || !ISD::isNormalLoad(Ld))
21279       return SDValue();
21280
21281     // If this is not the MMX case, i.e. we are just turning i64 load/store
21282     // into f64 load/store, avoid the transformation if there are multiple
21283     // uses of the loaded value.
21284     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21285       return SDValue();
21286
21287     SDLoc LdDL(Ld);
21288     SDLoc StDL(N);
21289     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21290     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21291     // pair instead.
21292     if (Subtarget->is64Bit() || F64IsLegal) {
21293       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21294       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21295                                   Ld->getPointerInfo(), Ld->isVolatile(),
21296                                   Ld->isNonTemporal(), Ld->isInvariant(),
21297                                   Ld->getAlignment());
21298       SDValue NewChain = NewLd.getValue(1);
21299       if (TokenFactorIndex != -1) {
21300         Ops.push_back(NewChain);
21301         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21302       }
21303       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21304                           St->getPointerInfo(),
21305                           St->isVolatile(), St->isNonTemporal(),
21306                           St->getAlignment());
21307     }
21308
21309     // Otherwise, lower to two pairs of 32-bit loads / stores.
21310     SDValue LoAddr = Ld->getBasePtr();
21311     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21312                                  DAG.getConstant(4, MVT::i32));
21313
21314     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21315                                Ld->getPointerInfo(),
21316                                Ld->isVolatile(), Ld->isNonTemporal(),
21317                                Ld->isInvariant(), Ld->getAlignment());
21318     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21319                                Ld->getPointerInfo().getWithOffset(4),
21320                                Ld->isVolatile(), Ld->isNonTemporal(),
21321                                Ld->isInvariant(),
21322                                MinAlign(Ld->getAlignment(), 4));
21323
21324     SDValue NewChain = LoLd.getValue(1);
21325     if (TokenFactorIndex != -1) {
21326       Ops.push_back(LoLd);
21327       Ops.push_back(HiLd);
21328       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21329     }
21330
21331     LoAddr = St->getBasePtr();
21332     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21333                          DAG.getConstant(4, MVT::i32));
21334
21335     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21336                                 St->getPointerInfo(),
21337                                 St->isVolatile(), St->isNonTemporal(),
21338                                 St->getAlignment());
21339     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21340                                 St->getPointerInfo().getWithOffset(4),
21341                                 St->isVolatile(),
21342                                 St->isNonTemporal(),
21343                                 MinAlign(St->getAlignment(), 4));
21344     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21345   }
21346   return SDValue();
21347 }
21348
21349 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21350 /// and return the operands for the horizontal operation in LHS and RHS.  A
21351 /// horizontal operation performs the binary operation on successive elements
21352 /// of its first operand, then on successive elements of its second operand,
21353 /// returning the resulting values in a vector.  For example, if
21354 ///   A = < float a0, float a1, float a2, float a3 >
21355 /// and
21356 ///   B = < float b0, float b1, float b2, float b3 >
21357 /// then the result of doing a horizontal operation on A and B is
21358 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21359 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21360 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21361 /// set to A, RHS to B, and the routine returns 'true'.
21362 /// Note that the binary operation should have the property that if one of the
21363 /// operands is UNDEF then the result is UNDEF.
21364 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21365   // Look for the following pattern: if
21366   //   A = < float a0, float a1, float a2, float a3 >
21367   //   B = < float b0, float b1, float b2, float b3 >
21368   // and
21369   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21370   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21371   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21372   // which is A horizontal-op B.
21373
21374   // At least one of the operands should be a vector shuffle.
21375   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21376       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21377     return false;
21378
21379   MVT VT = LHS.getSimpleValueType();
21380
21381   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21382          "Unsupported vector type for horizontal add/sub");
21383
21384   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21385   // operate independently on 128-bit lanes.
21386   unsigned NumElts = VT.getVectorNumElements();
21387   unsigned NumLanes = VT.getSizeInBits()/128;
21388   unsigned NumLaneElts = NumElts / NumLanes;
21389   assert((NumLaneElts % 2 == 0) &&
21390          "Vector type should have an even number of elements in each lane");
21391   unsigned HalfLaneElts = NumLaneElts/2;
21392
21393   // View LHS in the form
21394   //   LHS = VECTOR_SHUFFLE A, B, LMask
21395   // If LHS is not a shuffle then pretend it is the shuffle
21396   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21397   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21398   // type VT.
21399   SDValue A, B;
21400   SmallVector<int, 16> LMask(NumElts);
21401   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21402     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21403       A = LHS.getOperand(0);
21404     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21405       B = LHS.getOperand(1);
21406     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21407     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21408   } else {
21409     if (LHS.getOpcode() != ISD::UNDEF)
21410       A = LHS;
21411     for (unsigned i = 0; i != NumElts; ++i)
21412       LMask[i] = i;
21413   }
21414
21415   // Likewise, view RHS in the form
21416   //   RHS = VECTOR_SHUFFLE C, D, RMask
21417   SDValue C, D;
21418   SmallVector<int, 16> RMask(NumElts);
21419   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21420     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21421       C = RHS.getOperand(0);
21422     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21423       D = RHS.getOperand(1);
21424     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21425     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21426   } else {
21427     if (RHS.getOpcode() != ISD::UNDEF)
21428       C = RHS;
21429     for (unsigned i = 0; i != NumElts; ++i)
21430       RMask[i] = i;
21431   }
21432
21433   // Check that the shuffles are both shuffling the same vectors.
21434   if (!(A == C && B == D) && !(A == D && B == C))
21435     return false;
21436
21437   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21438   if (!A.getNode() && !B.getNode())
21439     return false;
21440
21441   // If A and B occur in reverse order in RHS, then "swap" them (which means
21442   // rewriting the mask).
21443   if (A != C)
21444     CommuteVectorShuffleMask(RMask, NumElts);
21445
21446   // At this point LHS and RHS are equivalent to
21447   //   LHS = VECTOR_SHUFFLE A, B, LMask
21448   //   RHS = VECTOR_SHUFFLE A, B, RMask
21449   // Check that the masks correspond to performing a horizontal operation.
21450   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21451     for (unsigned i = 0; i != NumLaneElts; ++i) {
21452       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21453
21454       // Ignore any UNDEF components.
21455       if (LIdx < 0 || RIdx < 0 ||
21456           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21457           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21458         continue;
21459
21460       // Check that successive elements are being operated on.  If not, this is
21461       // not a horizontal operation.
21462       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21463       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21464       if (!(LIdx == Index && RIdx == Index + 1) &&
21465           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21466         return false;
21467     }
21468   }
21469
21470   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21471   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21472   return true;
21473 }
21474
21475 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21476 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21477                                   const X86Subtarget *Subtarget) {
21478   EVT VT = N->getValueType(0);
21479   SDValue LHS = N->getOperand(0);
21480   SDValue RHS = N->getOperand(1);
21481
21482   // Try to synthesize horizontal adds from adds of shuffles.
21483   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21484        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21485       isHorizontalBinOp(LHS, RHS, true))
21486     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21487   return SDValue();
21488 }
21489
21490 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21491 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21492                                   const X86Subtarget *Subtarget) {
21493   EVT VT = N->getValueType(0);
21494   SDValue LHS = N->getOperand(0);
21495   SDValue RHS = N->getOperand(1);
21496
21497   // Try to synthesize horizontal subs from subs of shuffles.
21498   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21499        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21500       isHorizontalBinOp(LHS, RHS, false))
21501     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21502   return SDValue();
21503 }
21504
21505 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21506 /// X86ISD::FXOR nodes.
21507 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21508   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21509   // F[X]OR(0.0, x) -> x
21510   // F[X]OR(x, 0.0) -> x
21511   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21512     if (C->getValueAPF().isPosZero())
21513       return N->getOperand(1);
21514   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21515     if (C->getValueAPF().isPosZero())
21516       return N->getOperand(0);
21517   return SDValue();
21518 }
21519
21520 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21521 /// X86ISD::FMAX nodes.
21522 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21523   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21524
21525   // Only perform optimizations if UnsafeMath is used.
21526   if (!DAG.getTarget().Options.UnsafeFPMath)
21527     return SDValue();
21528
21529   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21530   // into FMINC and FMAXC, which are Commutative operations.
21531   unsigned NewOp = 0;
21532   switch (N->getOpcode()) {
21533     default: llvm_unreachable("unknown opcode");
21534     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21535     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21536   }
21537
21538   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21539                      N->getOperand(0), N->getOperand(1));
21540 }
21541
21542 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21543 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21544   // FAND(0.0, x) -> 0.0
21545   // FAND(x, 0.0) -> 0.0
21546   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21547     if (C->getValueAPF().isPosZero())
21548       return N->getOperand(0);
21549   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21550     if (C->getValueAPF().isPosZero())
21551       return N->getOperand(1);
21552   return SDValue();
21553 }
21554
21555 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21556 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21557   // FANDN(x, 0.0) -> 0.0
21558   // FANDN(0.0, x) -> x
21559   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21560     if (C->getValueAPF().isPosZero())
21561       return N->getOperand(1);
21562   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21563     if (C->getValueAPF().isPosZero())
21564       return N->getOperand(1);
21565   return SDValue();
21566 }
21567
21568 static SDValue PerformBTCombine(SDNode *N,
21569                                 SelectionDAG &DAG,
21570                                 TargetLowering::DAGCombinerInfo &DCI) {
21571   // BT ignores high bits in the bit index operand.
21572   SDValue Op1 = N->getOperand(1);
21573   if (Op1.hasOneUse()) {
21574     unsigned BitWidth = Op1.getValueSizeInBits();
21575     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21576     APInt KnownZero, KnownOne;
21577     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21578                                           !DCI.isBeforeLegalizeOps());
21579     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21580     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21581         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21582       DCI.CommitTargetLoweringOpt(TLO);
21583   }
21584   return SDValue();
21585 }
21586
21587 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21588   SDValue Op = N->getOperand(0);
21589   if (Op.getOpcode() == ISD::BITCAST)
21590     Op = Op.getOperand(0);
21591   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21592   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21593       VT.getVectorElementType().getSizeInBits() ==
21594       OpVT.getVectorElementType().getSizeInBits()) {
21595     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21596   }
21597   return SDValue();
21598 }
21599
21600 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21601                                                const X86Subtarget *Subtarget) {
21602   EVT VT = N->getValueType(0);
21603   if (!VT.isVector())
21604     return SDValue();
21605
21606   SDValue N0 = N->getOperand(0);
21607   SDValue N1 = N->getOperand(1);
21608   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21609   SDLoc dl(N);
21610
21611   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21612   // both SSE and AVX2 since there is no sign-extended shift right
21613   // operation on a vector with 64-bit elements.
21614   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21615   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21616   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21617       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21618     SDValue N00 = N0.getOperand(0);
21619
21620     // EXTLOAD has a better solution on AVX2,
21621     // it may be replaced with X86ISD::VSEXT node.
21622     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21623       if (!ISD::isNormalLoad(N00.getNode()))
21624         return SDValue();
21625
21626     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21627         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21628                                   N00, N1);
21629       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21630     }
21631   }
21632   return SDValue();
21633 }
21634
21635 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21636                                   TargetLowering::DAGCombinerInfo &DCI,
21637                                   const X86Subtarget *Subtarget) {
21638   if (!DCI.isBeforeLegalizeOps())
21639     return SDValue();
21640
21641   if (!Subtarget->hasFp256())
21642     return SDValue();
21643
21644   EVT VT = N->getValueType(0);
21645   if (VT.isVector() && VT.getSizeInBits() == 256) {
21646     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21647     if (R.getNode())
21648       return R;
21649   }
21650
21651   return SDValue();
21652 }
21653
21654 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21655                                  const X86Subtarget* Subtarget) {
21656   SDLoc dl(N);
21657   EVT VT = N->getValueType(0);
21658
21659   // Let legalize expand this if it isn't a legal type yet.
21660   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21661     return SDValue();
21662
21663   EVT ScalarVT = VT.getScalarType();
21664   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21665       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21666     return SDValue();
21667
21668   SDValue A = N->getOperand(0);
21669   SDValue B = N->getOperand(1);
21670   SDValue C = N->getOperand(2);
21671
21672   bool NegA = (A.getOpcode() == ISD::FNEG);
21673   bool NegB = (B.getOpcode() == ISD::FNEG);
21674   bool NegC = (C.getOpcode() == ISD::FNEG);
21675
21676   // Negative multiplication when NegA xor NegB
21677   bool NegMul = (NegA != NegB);
21678   if (NegA)
21679     A = A.getOperand(0);
21680   if (NegB)
21681     B = B.getOperand(0);
21682   if (NegC)
21683     C = C.getOperand(0);
21684
21685   unsigned Opcode;
21686   if (!NegMul)
21687     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21688   else
21689     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21690
21691   return DAG.getNode(Opcode, dl, VT, A, B, C);
21692 }
21693
21694 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21695                                   TargetLowering::DAGCombinerInfo &DCI,
21696                                   const X86Subtarget *Subtarget) {
21697   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21698   //           (and (i32 x86isd::setcc_carry), 1)
21699   // This eliminates the zext. This transformation is necessary because
21700   // ISD::SETCC is always legalized to i8.
21701   SDLoc dl(N);
21702   SDValue N0 = N->getOperand(0);
21703   EVT VT = N->getValueType(0);
21704
21705   if (N0.getOpcode() == ISD::AND &&
21706       N0.hasOneUse() &&
21707       N0.getOperand(0).hasOneUse()) {
21708     SDValue N00 = N0.getOperand(0);
21709     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21710       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21711       if (!C || C->getZExtValue() != 1)
21712         return SDValue();
21713       return DAG.getNode(ISD::AND, dl, VT,
21714                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21715                                      N00.getOperand(0), N00.getOperand(1)),
21716                          DAG.getConstant(1, VT));
21717     }
21718   }
21719
21720   if (N0.getOpcode() == ISD::TRUNCATE &&
21721       N0.hasOneUse() &&
21722       N0.getOperand(0).hasOneUse()) {
21723     SDValue N00 = N0.getOperand(0);
21724     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21725       return DAG.getNode(ISD::AND, dl, VT,
21726                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21727                                      N00.getOperand(0), N00.getOperand(1)),
21728                          DAG.getConstant(1, VT));
21729     }
21730   }
21731   if (VT.is256BitVector()) {
21732     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21733     if (R.getNode())
21734       return R;
21735   }
21736
21737   return SDValue();
21738 }
21739
21740 // Optimize x == -y --> x+y == 0
21741 //          x != -y --> x+y != 0
21742 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21743                                       const X86Subtarget* Subtarget) {
21744   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21745   SDValue LHS = N->getOperand(0);
21746   SDValue RHS = N->getOperand(1);
21747   EVT VT = N->getValueType(0);
21748   SDLoc DL(N);
21749
21750   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21751     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21752       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21753         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21754                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21755         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21756                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21757       }
21758   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21760       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21761         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21762                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21763         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21764                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21765       }
21766
21767   if (VT.getScalarType() == MVT::i1) {
21768     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21769       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21770     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21771     if (!IsSEXT0 && !IsVZero0)
21772       return SDValue();
21773     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21774       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21775     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21776
21777     if (!IsSEXT1 && !IsVZero1)
21778       return SDValue();
21779
21780     if (IsSEXT0 && IsVZero1) {
21781       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21782       if (CC == ISD::SETEQ)
21783         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21784       return LHS.getOperand(0);
21785     }
21786     if (IsSEXT1 && IsVZero0) {
21787       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21788       if (CC == ISD::SETEQ)
21789         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21790       return RHS.getOperand(0);
21791     }
21792   }
21793
21794   return SDValue();
21795 }
21796
21797 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21798                                       const X86Subtarget *Subtarget) {
21799   SDLoc dl(N);
21800   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21801   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21802          "X86insertps is only defined for v4x32");
21803
21804   SDValue Ld = N->getOperand(1);
21805   if (MayFoldLoad(Ld)) {
21806     // Extract the countS bits from the immediate so we can get the proper
21807     // address when narrowing the vector load to a specific element.
21808     // When the second source op is a memory address, interps doesn't use
21809     // countS and just gets an f32 from that address.
21810     unsigned DestIndex =
21811         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21812     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21813   } else
21814     return SDValue();
21815
21816   // Create this as a scalar to vector to match the instruction pattern.
21817   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21818   // countS bits are ignored when loading from memory on insertps, which
21819   // means we don't need to explicitly set them to 0.
21820   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21821                      LoadScalarToVector, N->getOperand(2));
21822 }
21823
21824 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21825 // as "sbb reg,reg", since it can be extended without zext and produces
21826 // an all-ones bit which is more useful than 0/1 in some cases.
21827 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21828                                MVT VT) {
21829   if (VT == MVT::i8)
21830     return DAG.getNode(ISD::AND, DL, VT,
21831                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21832                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21833                        DAG.getConstant(1, VT));
21834   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21835   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21836                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21837                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21838 }
21839
21840 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21841 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21842                                    TargetLowering::DAGCombinerInfo &DCI,
21843                                    const X86Subtarget *Subtarget) {
21844   SDLoc DL(N);
21845   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21846   SDValue EFLAGS = N->getOperand(1);
21847
21848   if (CC == X86::COND_A) {
21849     // Try to convert COND_A into COND_B in an attempt to facilitate
21850     // materializing "setb reg".
21851     //
21852     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21853     // cannot take an immediate as its first operand.
21854     //
21855     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21856         EFLAGS.getValueType().isInteger() &&
21857         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21858       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21859                                    EFLAGS.getNode()->getVTList(),
21860                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21861       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21862       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21863     }
21864   }
21865
21866   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21867   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21868   // cases.
21869   if (CC == X86::COND_B)
21870     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21871
21872   SDValue Flags;
21873
21874   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21875   if (Flags.getNode()) {
21876     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21877     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21878   }
21879
21880   return SDValue();
21881 }
21882
21883 // Optimize branch condition evaluation.
21884 //
21885 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21886                                     TargetLowering::DAGCombinerInfo &DCI,
21887                                     const X86Subtarget *Subtarget) {
21888   SDLoc DL(N);
21889   SDValue Chain = N->getOperand(0);
21890   SDValue Dest = N->getOperand(1);
21891   SDValue EFLAGS = N->getOperand(3);
21892   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21893
21894   SDValue Flags;
21895
21896   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21897   if (Flags.getNode()) {
21898     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21899     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21900                        Flags);
21901   }
21902
21903   return SDValue();
21904 }
21905
21906 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
21907                                                          SelectionDAG &DAG) {
21908   // Take advantage of vector comparisons producing 0 or -1 in each lane to
21909   // optimize away operation when it's from a constant.
21910   //
21911   // The general transformation is:
21912   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
21913   //       AND(VECTOR_CMP(x,y), constant2)
21914   //    constant2 = UNARYOP(constant)
21915
21916   // Early exit if this isn't a vector operation, the operand of the
21917   // unary operation isn't a bitwise AND, or if the sizes of the operations
21918   // aren't the same.
21919   EVT VT = N->getValueType(0);
21920   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
21921       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
21922       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
21923     return SDValue();
21924
21925   // Now check that the other operand of the AND is a constant. We could
21926   // make the transformation for non-constant splats as well, but it's unclear
21927   // that would be a benefit as it would not eliminate any operations, just
21928   // perform one more step in scalar code before moving to the vector unit.
21929   if (BuildVectorSDNode *BV =
21930           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
21931     // Bail out if the vector isn't a constant.
21932     if (!BV->isConstant())
21933       return SDValue();
21934
21935     // Everything checks out. Build up the new and improved node.
21936     SDLoc DL(N);
21937     EVT IntVT = BV->getValueType(0);
21938     // Create a new constant of the appropriate type for the transformed
21939     // DAG.
21940     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
21941     // The AND node needs bitcasts to/from an integer vector type around it.
21942     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
21943     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
21944                                  N->getOperand(0)->getOperand(0), MaskConst);
21945     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
21946     return Res;
21947   }
21948
21949   return SDValue();
21950 }
21951
21952 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21953                                         const X86TargetLowering *XTLI) {
21954   // First try to optimize away the conversion entirely when it's
21955   // conditionally from a constant. Vectors only.
21956   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
21957   if (Res != SDValue())
21958     return Res;
21959
21960   // Now move on to more general possibilities.
21961   SDValue Op0 = N->getOperand(0);
21962   EVT InVT = Op0->getValueType(0);
21963
21964   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21965   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21966     SDLoc dl(N);
21967     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21968     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21969     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21970   }
21971
21972   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21973   // a 32-bit target where SSE doesn't support i64->FP operations.
21974   if (Op0.getOpcode() == ISD::LOAD) {
21975     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21976     EVT VT = Ld->getValueType(0);
21977     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21978         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21979         !XTLI->getSubtarget()->is64Bit() &&
21980         VT == MVT::i64) {
21981       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21982                                           Ld->getChain(), Op0, DAG);
21983       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21984       return FILDChain;
21985     }
21986   }
21987   return SDValue();
21988 }
21989
21990 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21991 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21992                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21993   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21994   // the result is either zero or one (depending on the input carry bit).
21995   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21996   if (X86::isZeroNode(N->getOperand(0)) &&
21997       X86::isZeroNode(N->getOperand(1)) &&
21998       // We don't have a good way to replace an EFLAGS use, so only do this when
21999       // dead right now.
22000       SDValue(N, 1).use_empty()) {
22001     SDLoc DL(N);
22002     EVT VT = N->getValueType(0);
22003     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22004     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22005                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22006                                            DAG.getConstant(X86::COND_B,MVT::i8),
22007                                            N->getOperand(2)),
22008                                DAG.getConstant(1, VT));
22009     return DCI.CombineTo(N, Res1, CarryOut);
22010   }
22011
22012   return SDValue();
22013 }
22014
22015 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22016 //      (add Y, (setne X, 0)) -> sbb -1, Y
22017 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22018 //      (sub (setne X, 0), Y) -> adc -1, Y
22019 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22020   SDLoc DL(N);
22021
22022   // Look through ZExts.
22023   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22024   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22025     return SDValue();
22026
22027   SDValue SetCC = Ext.getOperand(0);
22028   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22029     return SDValue();
22030
22031   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22032   if (CC != X86::COND_E && CC != X86::COND_NE)
22033     return SDValue();
22034
22035   SDValue Cmp = SetCC.getOperand(1);
22036   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22037       !X86::isZeroNode(Cmp.getOperand(1)) ||
22038       !Cmp.getOperand(0).getValueType().isInteger())
22039     return SDValue();
22040
22041   SDValue CmpOp0 = Cmp.getOperand(0);
22042   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22043                                DAG.getConstant(1, CmpOp0.getValueType()));
22044
22045   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22046   if (CC == X86::COND_NE)
22047     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22048                        DL, OtherVal.getValueType(), OtherVal,
22049                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22050   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22051                      DL, OtherVal.getValueType(), OtherVal,
22052                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22053 }
22054
22055 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22056 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22057                                  const X86Subtarget *Subtarget) {
22058   EVT VT = N->getValueType(0);
22059   SDValue Op0 = N->getOperand(0);
22060   SDValue Op1 = N->getOperand(1);
22061
22062   // Try to synthesize horizontal adds from adds of shuffles.
22063   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22064        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22065       isHorizontalBinOp(Op0, Op1, true))
22066     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22067
22068   return OptimizeConditionalInDecrement(N, DAG);
22069 }
22070
22071 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22072                                  const X86Subtarget *Subtarget) {
22073   SDValue Op0 = N->getOperand(0);
22074   SDValue Op1 = N->getOperand(1);
22075
22076   // X86 can't encode an immediate LHS of a sub. See if we can push the
22077   // negation into a preceding instruction.
22078   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22079     // If the RHS of the sub is a XOR with one use and a constant, invert the
22080     // immediate. Then add one to the LHS of the sub so we can turn
22081     // X-Y -> X+~Y+1, saving one register.
22082     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22083         isa<ConstantSDNode>(Op1.getOperand(1))) {
22084       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22085       EVT VT = Op0.getValueType();
22086       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22087                                    Op1.getOperand(0),
22088                                    DAG.getConstant(~XorC, VT));
22089       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22090                          DAG.getConstant(C->getAPIntValue()+1, VT));
22091     }
22092   }
22093
22094   // Try to synthesize horizontal adds from adds of shuffles.
22095   EVT VT = N->getValueType(0);
22096   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22097        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22098       isHorizontalBinOp(Op0, Op1, true))
22099     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22100
22101   return OptimizeConditionalInDecrement(N, DAG);
22102 }
22103
22104 /// performVZEXTCombine - Performs build vector combines
22105 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22106                                         TargetLowering::DAGCombinerInfo &DCI,
22107                                         const X86Subtarget *Subtarget) {
22108   // (vzext (bitcast (vzext (x)) -> (vzext x)
22109   SDValue In = N->getOperand(0);
22110   while (In.getOpcode() == ISD::BITCAST)
22111     In = In.getOperand(0);
22112
22113   if (In.getOpcode() != X86ISD::VZEXT)
22114     return SDValue();
22115
22116   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22117                      In.getOperand(0));
22118 }
22119
22120 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22121                                              DAGCombinerInfo &DCI) const {
22122   SelectionDAG &DAG = DCI.DAG;
22123   switch (N->getOpcode()) {
22124   default: break;
22125   case ISD::EXTRACT_VECTOR_ELT:
22126     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22127   case ISD::VSELECT:
22128   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22129   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22130   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22131   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22132   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22133   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22134   case ISD::SHL:
22135   case ISD::SRA:
22136   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22137   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22138   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22139   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22140   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22141   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22142   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22143   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22144   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22145   case X86ISD::FXOR:
22146   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22147   case X86ISD::FMIN:
22148   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22149   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22150   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22151   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22152   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22153   case ISD::ANY_EXTEND:
22154   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22155   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22156   case ISD::SIGN_EXTEND_INREG:
22157     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22158   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22159   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22160   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22161   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22162   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22163   case X86ISD::SHUFP:       // Handle all target specific shuffles
22164   case X86ISD::PALIGNR:
22165   case X86ISD::UNPCKH:
22166   case X86ISD::UNPCKL:
22167   case X86ISD::MOVHLPS:
22168   case X86ISD::MOVLHPS:
22169   case X86ISD::PSHUFD:
22170   case X86ISD::PSHUFHW:
22171   case X86ISD::PSHUFLW:
22172   case X86ISD::MOVSS:
22173   case X86ISD::MOVSD:
22174   case X86ISD::VPERMILP:
22175   case X86ISD::VPERM2X128:
22176   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22177   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22178   case ISD::INTRINSIC_WO_CHAIN:
22179     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22180   case X86ISD::INSERTPS:
22181     return PerformINSERTPSCombine(N, DAG, Subtarget);
22182   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22183   }
22184
22185   return SDValue();
22186 }
22187
22188 /// isTypeDesirableForOp - Return true if the target has native support for
22189 /// the specified value type and it is 'desirable' to use the type for the
22190 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22191 /// instruction encodings are longer and some i16 instructions are slow.
22192 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22193   if (!isTypeLegal(VT))
22194     return false;
22195   if (VT != MVT::i16)
22196     return true;
22197
22198   switch (Opc) {
22199   default:
22200     return true;
22201   case ISD::LOAD:
22202   case ISD::SIGN_EXTEND:
22203   case ISD::ZERO_EXTEND:
22204   case ISD::ANY_EXTEND:
22205   case ISD::SHL:
22206   case ISD::SRL:
22207   case ISD::SUB:
22208   case ISD::ADD:
22209   case ISD::MUL:
22210   case ISD::AND:
22211   case ISD::OR:
22212   case ISD::XOR:
22213     return false;
22214   }
22215 }
22216
22217 /// IsDesirableToPromoteOp - This method query the target whether it is
22218 /// beneficial for dag combiner to promote the specified node. If true, it
22219 /// should return the desired promotion type by reference.
22220 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22221   EVT VT = Op.getValueType();
22222   if (VT != MVT::i16)
22223     return false;
22224
22225   bool Promote = false;
22226   bool Commute = false;
22227   switch (Op.getOpcode()) {
22228   default: break;
22229   case ISD::LOAD: {
22230     LoadSDNode *LD = cast<LoadSDNode>(Op);
22231     // If the non-extending load has a single use and it's not live out, then it
22232     // might be folded.
22233     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22234                                                      Op.hasOneUse()*/) {
22235       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22236              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22237         // The only case where we'd want to promote LOAD (rather then it being
22238         // promoted as an operand is when it's only use is liveout.
22239         if (UI->getOpcode() != ISD::CopyToReg)
22240           return false;
22241       }
22242     }
22243     Promote = true;
22244     break;
22245   }
22246   case ISD::SIGN_EXTEND:
22247   case ISD::ZERO_EXTEND:
22248   case ISD::ANY_EXTEND:
22249     Promote = true;
22250     break;
22251   case ISD::SHL:
22252   case ISD::SRL: {
22253     SDValue N0 = Op.getOperand(0);
22254     // Look out for (store (shl (load), x)).
22255     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22256       return false;
22257     Promote = true;
22258     break;
22259   }
22260   case ISD::ADD:
22261   case ISD::MUL:
22262   case ISD::AND:
22263   case ISD::OR:
22264   case ISD::XOR:
22265     Commute = true;
22266     // fallthrough
22267   case ISD::SUB: {
22268     SDValue N0 = Op.getOperand(0);
22269     SDValue N1 = Op.getOperand(1);
22270     if (!Commute && MayFoldLoad(N1))
22271       return false;
22272     // Avoid disabling potential load folding opportunities.
22273     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22274       return false;
22275     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22276       return false;
22277     Promote = true;
22278   }
22279   }
22280
22281   PVT = MVT::i32;
22282   return Promote;
22283 }
22284
22285 //===----------------------------------------------------------------------===//
22286 //                           X86 Inline Assembly Support
22287 //===----------------------------------------------------------------------===//
22288
22289 namespace {
22290   // Helper to match a string separated by whitespace.
22291   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22292     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22293
22294     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22295       StringRef piece(*args[i]);
22296       if (!s.startswith(piece)) // Check if the piece matches.
22297         return false;
22298
22299       s = s.substr(piece.size());
22300       StringRef::size_type pos = s.find_first_not_of(" \t");
22301       if (pos == 0) // We matched a prefix.
22302         return false;
22303
22304       s = s.substr(pos);
22305     }
22306
22307     return s.empty();
22308   }
22309   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22310 }
22311
22312 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22313
22314   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22315     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22316         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22317         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22318
22319       if (AsmPieces.size() == 3)
22320         return true;
22321       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22322         return true;
22323     }
22324   }
22325   return false;
22326 }
22327
22328 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22329   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22330
22331   std::string AsmStr = IA->getAsmString();
22332
22333   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22334   if (!Ty || Ty->getBitWidth() % 16 != 0)
22335     return false;
22336
22337   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22338   SmallVector<StringRef, 4> AsmPieces;
22339   SplitString(AsmStr, AsmPieces, ";\n");
22340
22341   switch (AsmPieces.size()) {
22342   default: return false;
22343   case 1:
22344     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22345     // we will turn this bswap into something that will be lowered to logical
22346     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22347     // lower so don't worry about this.
22348     // bswap $0
22349     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22350         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22351         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22352         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22353         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22354         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22355       // No need to check constraints, nothing other than the equivalent of
22356       // "=r,0" would be valid here.
22357       return IntrinsicLowering::LowerToByteSwap(CI);
22358     }
22359
22360     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22361     if (CI->getType()->isIntegerTy(16) &&
22362         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22363         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22364          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22365       AsmPieces.clear();
22366       const std::string &ConstraintsStr = IA->getConstraintString();
22367       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22368       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22369       if (clobbersFlagRegisters(AsmPieces))
22370         return IntrinsicLowering::LowerToByteSwap(CI);
22371     }
22372     break;
22373   case 3:
22374     if (CI->getType()->isIntegerTy(32) &&
22375         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22376         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22377         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22378         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22379       AsmPieces.clear();
22380       const std::string &ConstraintsStr = IA->getConstraintString();
22381       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22382       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22383       if (clobbersFlagRegisters(AsmPieces))
22384         return IntrinsicLowering::LowerToByteSwap(CI);
22385     }
22386
22387     if (CI->getType()->isIntegerTy(64)) {
22388       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22389       if (Constraints.size() >= 2 &&
22390           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22391           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22392         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22393         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22394             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22395             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22396           return IntrinsicLowering::LowerToByteSwap(CI);
22397       }
22398     }
22399     break;
22400   }
22401   return false;
22402 }
22403
22404 /// getConstraintType - Given a constraint letter, return the type of
22405 /// constraint it is for this target.
22406 X86TargetLowering::ConstraintType
22407 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22408   if (Constraint.size() == 1) {
22409     switch (Constraint[0]) {
22410     case 'R':
22411     case 'q':
22412     case 'Q':
22413     case 'f':
22414     case 't':
22415     case 'u':
22416     case 'y':
22417     case 'x':
22418     case 'Y':
22419     case 'l':
22420       return C_RegisterClass;
22421     case 'a':
22422     case 'b':
22423     case 'c':
22424     case 'd':
22425     case 'S':
22426     case 'D':
22427     case 'A':
22428       return C_Register;
22429     case 'I':
22430     case 'J':
22431     case 'K':
22432     case 'L':
22433     case 'M':
22434     case 'N':
22435     case 'G':
22436     case 'C':
22437     case 'e':
22438     case 'Z':
22439       return C_Other;
22440     default:
22441       break;
22442     }
22443   }
22444   return TargetLowering::getConstraintType(Constraint);
22445 }
22446
22447 /// Examine constraint type and operand type and determine a weight value.
22448 /// This object must already have been set up with the operand type
22449 /// and the current alternative constraint selected.
22450 TargetLowering::ConstraintWeight
22451   X86TargetLowering::getSingleConstraintMatchWeight(
22452     AsmOperandInfo &info, const char *constraint) const {
22453   ConstraintWeight weight = CW_Invalid;
22454   Value *CallOperandVal = info.CallOperandVal;
22455     // If we don't have a value, we can't do a match,
22456     // but allow it at the lowest weight.
22457   if (!CallOperandVal)
22458     return CW_Default;
22459   Type *type = CallOperandVal->getType();
22460   // Look at the constraint type.
22461   switch (*constraint) {
22462   default:
22463     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22464   case 'R':
22465   case 'q':
22466   case 'Q':
22467   case 'a':
22468   case 'b':
22469   case 'c':
22470   case 'd':
22471   case 'S':
22472   case 'D':
22473   case 'A':
22474     if (CallOperandVal->getType()->isIntegerTy())
22475       weight = CW_SpecificReg;
22476     break;
22477   case 'f':
22478   case 't':
22479   case 'u':
22480     if (type->isFloatingPointTy())
22481       weight = CW_SpecificReg;
22482     break;
22483   case 'y':
22484     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22485       weight = CW_SpecificReg;
22486     break;
22487   case 'x':
22488   case 'Y':
22489     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22490         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22491       weight = CW_Register;
22492     break;
22493   case 'I':
22494     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22495       if (C->getZExtValue() <= 31)
22496         weight = CW_Constant;
22497     }
22498     break;
22499   case 'J':
22500     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22501       if (C->getZExtValue() <= 63)
22502         weight = CW_Constant;
22503     }
22504     break;
22505   case 'K':
22506     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22507       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22508         weight = CW_Constant;
22509     }
22510     break;
22511   case 'L':
22512     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22513       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22514         weight = CW_Constant;
22515     }
22516     break;
22517   case 'M':
22518     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22519       if (C->getZExtValue() <= 3)
22520         weight = CW_Constant;
22521     }
22522     break;
22523   case 'N':
22524     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22525       if (C->getZExtValue() <= 0xff)
22526         weight = CW_Constant;
22527     }
22528     break;
22529   case 'G':
22530   case 'C':
22531     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22532       weight = CW_Constant;
22533     }
22534     break;
22535   case 'e':
22536     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22537       if ((C->getSExtValue() >= -0x80000000LL) &&
22538           (C->getSExtValue() <= 0x7fffffffLL))
22539         weight = CW_Constant;
22540     }
22541     break;
22542   case 'Z':
22543     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22544       if (C->getZExtValue() <= 0xffffffff)
22545         weight = CW_Constant;
22546     }
22547     break;
22548   }
22549   return weight;
22550 }
22551
22552 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22553 /// with another that has more specific requirements based on the type of the
22554 /// corresponding operand.
22555 const char *X86TargetLowering::
22556 LowerXConstraint(EVT ConstraintVT) const {
22557   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22558   // 'f' like normal targets.
22559   if (ConstraintVT.isFloatingPoint()) {
22560     if (Subtarget->hasSSE2())
22561       return "Y";
22562     if (Subtarget->hasSSE1())
22563       return "x";
22564   }
22565
22566   return TargetLowering::LowerXConstraint(ConstraintVT);
22567 }
22568
22569 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22570 /// vector.  If it is invalid, don't add anything to Ops.
22571 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22572                                                      std::string &Constraint,
22573                                                      std::vector<SDValue>&Ops,
22574                                                      SelectionDAG &DAG) const {
22575   SDValue Result;
22576
22577   // Only support length 1 constraints for now.
22578   if (Constraint.length() > 1) return;
22579
22580   char ConstraintLetter = Constraint[0];
22581   switch (ConstraintLetter) {
22582   default: break;
22583   case 'I':
22584     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22585       if (C->getZExtValue() <= 31) {
22586         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22587         break;
22588       }
22589     }
22590     return;
22591   case 'J':
22592     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22593       if (C->getZExtValue() <= 63) {
22594         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22595         break;
22596       }
22597     }
22598     return;
22599   case 'K':
22600     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22601       if (isInt<8>(C->getSExtValue())) {
22602         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22603         break;
22604       }
22605     }
22606     return;
22607   case 'N':
22608     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22609       if (C->getZExtValue() <= 255) {
22610         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22611         break;
22612       }
22613     }
22614     return;
22615   case 'e': {
22616     // 32-bit signed value
22617     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22618       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22619                                            C->getSExtValue())) {
22620         // Widen to 64 bits here to get it sign extended.
22621         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22622         break;
22623       }
22624     // FIXME gcc accepts some relocatable values here too, but only in certain
22625     // memory models; it's complicated.
22626     }
22627     return;
22628   }
22629   case 'Z': {
22630     // 32-bit unsigned value
22631     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22632       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22633                                            C->getZExtValue())) {
22634         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22635         break;
22636       }
22637     }
22638     // FIXME gcc accepts some relocatable values here too, but only in certain
22639     // memory models; it's complicated.
22640     return;
22641   }
22642   case 'i': {
22643     // Literal immediates are always ok.
22644     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22645       // Widen to 64 bits here to get it sign extended.
22646       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22647       break;
22648     }
22649
22650     // In any sort of PIC mode addresses need to be computed at runtime by
22651     // adding in a register or some sort of table lookup.  These can't
22652     // be used as immediates.
22653     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22654       return;
22655
22656     // If we are in non-pic codegen mode, we allow the address of a global (with
22657     // an optional displacement) to be used with 'i'.
22658     GlobalAddressSDNode *GA = nullptr;
22659     int64_t Offset = 0;
22660
22661     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22662     while (1) {
22663       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22664         Offset += GA->getOffset();
22665         break;
22666       } else if (Op.getOpcode() == ISD::ADD) {
22667         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22668           Offset += C->getZExtValue();
22669           Op = Op.getOperand(0);
22670           continue;
22671         }
22672       } else if (Op.getOpcode() == ISD::SUB) {
22673         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22674           Offset += -C->getZExtValue();
22675           Op = Op.getOperand(0);
22676           continue;
22677         }
22678       }
22679
22680       // Otherwise, this isn't something we can handle, reject it.
22681       return;
22682     }
22683
22684     const GlobalValue *GV = GA->getGlobal();
22685     // If we require an extra load to get this address, as in PIC mode, we
22686     // can't accept it.
22687     if (isGlobalStubReference(
22688             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22689       return;
22690
22691     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22692                                         GA->getValueType(0), Offset);
22693     break;
22694   }
22695   }
22696
22697   if (Result.getNode()) {
22698     Ops.push_back(Result);
22699     return;
22700   }
22701   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22702 }
22703
22704 std::pair<unsigned, const TargetRegisterClass*>
22705 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22706                                                 MVT VT) const {
22707   // First, see if this is a constraint that directly corresponds to an LLVM
22708   // register class.
22709   if (Constraint.size() == 1) {
22710     // GCC Constraint Letters
22711     switch (Constraint[0]) {
22712     default: break;
22713       // TODO: Slight differences here in allocation order and leaving
22714       // RIP in the class. Do they matter any more here than they do
22715       // in the normal allocation?
22716     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22717       if (Subtarget->is64Bit()) {
22718         if (VT == MVT::i32 || VT == MVT::f32)
22719           return std::make_pair(0U, &X86::GR32RegClass);
22720         if (VT == MVT::i16)
22721           return std::make_pair(0U, &X86::GR16RegClass);
22722         if (VT == MVT::i8 || VT == MVT::i1)
22723           return std::make_pair(0U, &X86::GR8RegClass);
22724         if (VT == MVT::i64 || VT == MVT::f64)
22725           return std::make_pair(0U, &X86::GR64RegClass);
22726         break;
22727       }
22728       // 32-bit fallthrough
22729     case 'Q':   // Q_REGS
22730       if (VT == MVT::i32 || VT == MVT::f32)
22731         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22732       if (VT == MVT::i16)
22733         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22734       if (VT == MVT::i8 || VT == MVT::i1)
22735         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22736       if (VT == MVT::i64)
22737         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22738       break;
22739     case 'r':   // GENERAL_REGS
22740     case 'l':   // INDEX_REGS
22741       if (VT == MVT::i8 || VT == MVT::i1)
22742         return std::make_pair(0U, &X86::GR8RegClass);
22743       if (VT == MVT::i16)
22744         return std::make_pair(0U, &X86::GR16RegClass);
22745       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22746         return std::make_pair(0U, &X86::GR32RegClass);
22747       return std::make_pair(0U, &X86::GR64RegClass);
22748     case 'R':   // LEGACY_REGS
22749       if (VT == MVT::i8 || VT == MVT::i1)
22750         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22751       if (VT == MVT::i16)
22752         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22753       if (VT == MVT::i32 || !Subtarget->is64Bit())
22754         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22755       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22756     case 'f':  // FP Stack registers.
22757       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22758       // value to the correct fpstack register class.
22759       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22760         return std::make_pair(0U, &X86::RFP32RegClass);
22761       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22762         return std::make_pair(0U, &X86::RFP64RegClass);
22763       return std::make_pair(0U, &X86::RFP80RegClass);
22764     case 'y':   // MMX_REGS if MMX allowed.
22765       if (!Subtarget->hasMMX()) break;
22766       return std::make_pair(0U, &X86::VR64RegClass);
22767     case 'Y':   // SSE_REGS if SSE2 allowed
22768       if (!Subtarget->hasSSE2()) break;
22769       // FALL THROUGH.
22770     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22771       if (!Subtarget->hasSSE1()) break;
22772
22773       switch (VT.SimpleTy) {
22774       default: break;
22775       // Scalar SSE types.
22776       case MVT::f32:
22777       case MVT::i32:
22778         return std::make_pair(0U, &X86::FR32RegClass);
22779       case MVT::f64:
22780       case MVT::i64:
22781         return std::make_pair(0U, &X86::FR64RegClass);
22782       // Vector types.
22783       case MVT::v16i8:
22784       case MVT::v8i16:
22785       case MVT::v4i32:
22786       case MVT::v2i64:
22787       case MVT::v4f32:
22788       case MVT::v2f64:
22789         return std::make_pair(0U, &X86::VR128RegClass);
22790       // AVX types.
22791       case MVT::v32i8:
22792       case MVT::v16i16:
22793       case MVT::v8i32:
22794       case MVT::v4i64:
22795       case MVT::v8f32:
22796       case MVT::v4f64:
22797         return std::make_pair(0U, &X86::VR256RegClass);
22798       case MVT::v8f64:
22799       case MVT::v16f32:
22800       case MVT::v16i32:
22801       case MVT::v8i64:
22802         return std::make_pair(0U, &X86::VR512RegClass);
22803       }
22804       break;
22805     }
22806   }
22807
22808   // Use the default implementation in TargetLowering to convert the register
22809   // constraint into a member of a register class.
22810   std::pair<unsigned, const TargetRegisterClass*> Res;
22811   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22812
22813   // Not found as a standard register?
22814   if (!Res.second) {
22815     // Map st(0) -> st(7) -> ST0
22816     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22817         tolower(Constraint[1]) == 's' &&
22818         tolower(Constraint[2]) == 't' &&
22819         Constraint[3] == '(' &&
22820         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22821         Constraint[5] == ')' &&
22822         Constraint[6] == '}') {
22823
22824       Res.first = X86::ST0+Constraint[4]-'0';
22825       Res.second = &X86::RFP80RegClass;
22826       return Res;
22827     }
22828
22829     // GCC allows "st(0)" to be called just plain "st".
22830     if (StringRef("{st}").equals_lower(Constraint)) {
22831       Res.first = X86::ST0;
22832       Res.second = &X86::RFP80RegClass;
22833       return Res;
22834     }
22835
22836     // flags -> EFLAGS
22837     if (StringRef("{flags}").equals_lower(Constraint)) {
22838       Res.first = X86::EFLAGS;
22839       Res.second = &X86::CCRRegClass;
22840       return Res;
22841     }
22842
22843     // 'A' means EAX + EDX.
22844     if (Constraint == "A") {
22845       Res.first = X86::EAX;
22846       Res.second = &X86::GR32_ADRegClass;
22847       return Res;
22848     }
22849     return Res;
22850   }
22851
22852   // Otherwise, check to see if this is a register class of the wrong value
22853   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22854   // turn into {ax},{dx}.
22855   if (Res.second->hasType(VT))
22856     return Res;   // Correct type already, nothing to do.
22857
22858   // All of the single-register GCC register classes map their values onto
22859   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22860   // really want an 8-bit or 32-bit register, map to the appropriate register
22861   // class and return the appropriate register.
22862   if (Res.second == &X86::GR16RegClass) {
22863     if (VT == MVT::i8 || VT == MVT::i1) {
22864       unsigned DestReg = 0;
22865       switch (Res.first) {
22866       default: break;
22867       case X86::AX: DestReg = X86::AL; break;
22868       case X86::DX: DestReg = X86::DL; break;
22869       case X86::CX: DestReg = X86::CL; break;
22870       case X86::BX: DestReg = X86::BL; break;
22871       }
22872       if (DestReg) {
22873         Res.first = DestReg;
22874         Res.second = &X86::GR8RegClass;
22875       }
22876     } else if (VT == MVT::i32 || VT == MVT::f32) {
22877       unsigned DestReg = 0;
22878       switch (Res.first) {
22879       default: break;
22880       case X86::AX: DestReg = X86::EAX; break;
22881       case X86::DX: DestReg = X86::EDX; break;
22882       case X86::CX: DestReg = X86::ECX; break;
22883       case X86::BX: DestReg = X86::EBX; break;
22884       case X86::SI: DestReg = X86::ESI; break;
22885       case X86::DI: DestReg = X86::EDI; break;
22886       case X86::BP: DestReg = X86::EBP; break;
22887       case X86::SP: DestReg = X86::ESP; break;
22888       }
22889       if (DestReg) {
22890         Res.first = DestReg;
22891         Res.second = &X86::GR32RegClass;
22892       }
22893     } else if (VT == MVT::i64 || VT == MVT::f64) {
22894       unsigned DestReg = 0;
22895       switch (Res.first) {
22896       default: break;
22897       case X86::AX: DestReg = X86::RAX; break;
22898       case X86::DX: DestReg = X86::RDX; break;
22899       case X86::CX: DestReg = X86::RCX; break;
22900       case X86::BX: DestReg = X86::RBX; break;
22901       case X86::SI: DestReg = X86::RSI; break;
22902       case X86::DI: DestReg = X86::RDI; break;
22903       case X86::BP: DestReg = X86::RBP; break;
22904       case X86::SP: DestReg = X86::RSP; break;
22905       }
22906       if (DestReg) {
22907         Res.first = DestReg;
22908         Res.second = &X86::GR64RegClass;
22909       }
22910     }
22911   } else if (Res.second == &X86::FR32RegClass ||
22912              Res.second == &X86::FR64RegClass ||
22913              Res.second == &X86::VR128RegClass ||
22914              Res.second == &X86::VR256RegClass ||
22915              Res.second == &X86::FR32XRegClass ||
22916              Res.second == &X86::FR64XRegClass ||
22917              Res.second == &X86::VR128XRegClass ||
22918              Res.second == &X86::VR256XRegClass ||
22919              Res.second == &X86::VR512RegClass) {
22920     // Handle references to XMM physical registers that got mapped into the
22921     // wrong class.  This can happen with constraints like {xmm0} where the
22922     // target independent register mapper will just pick the first match it can
22923     // find, ignoring the required type.
22924
22925     if (VT == MVT::f32 || VT == MVT::i32)
22926       Res.second = &X86::FR32RegClass;
22927     else if (VT == MVT::f64 || VT == MVT::i64)
22928       Res.second = &X86::FR64RegClass;
22929     else if (X86::VR128RegClass.hasType(VT))
22930       Res.second = &X86::VR128RegClass;
22931     else if (X86::VR256RegClass.hasType(VT))
22932       Res.second = &X86::VR256RegClass;
22933     else if (X86::VR512RegClass.hasType(VT))
22934       Res.second = &X86::VR512RegClass;
22935   }
22936
22937   return Res;
22938 }
22939
22940 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22941                                             Type *Ty) const {
22942   // Scaling factors are not free at all.
22943   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22944   // will take 2 allocations in the out of order engine instead of 1
22945   // for plain addressing mode, i.e. inst (reg1).
22946   // E.g.,
22947   // vaddps (%rsi,%drx), %ymm0, %ymm1
22948   // Requires two allocations (one for the load, one for the computation)
22949   // whereas:
22950   // vaddps (%rsi), %ymm0, %ymm1
22951   // Requires just 1 allocation, i.e., freeing allocations for other operations
22952   // and having less micro operations to execute.
22953   //
22954   // For some X86 architectures, this is even worse because for instance for
22955   // stores, the complex addressing mode forces the instruction to use the
22956   // "load" ports instead of the dedicated "store" port.
22957   // E.g., on Haswell:
22958   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22959   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22960   if (isLegalAddressingMode(AM, Ty))
22961     // Scale represents reg2 * scale, thus account for 1
22962     // as soon as we use a second register.
22963     return AM.Scale != 0;
22964   return -1;
22965 }
22966
22967 bool X86TargetLowering::isTargetFTOL() const {
22968   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22969 }